Skip to content

feat: apply unit config in rating via mutator - OM-397 - #4616

Merged
rolosp merged 6 commits into
mainfrom
feat/om-397-apply-unit-config
Jul 2, 2026
Merged

rolosp merged 6 commits into
mainfrom
feat/om-397-apply-unit-config

Conversation

@rolosp

@rolosp rolosp commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Apply unit_config in rating (charges path)

Wires unit_config into the billing rating engine so a usage-based rate card's conversion (operation × factor, then rounding) is applied to the metered quantity before pricing — previously authored and persisted (OM-395, OM-396) but inert at billing time. Dark behind unitConfig.enabled; with the flag off, rating is byte-identical to today.

This covers the charges path end-to-end. Standard/legacy invoice lines return no config yet — that's the next ticket (persist applied_unit_config on invoice lines), where the convert+round also gets applied in the charges line-mapper.

Changes

  • New UnitConfig pre-calculation mutator: converts + rounds on the cumulative endpoints (round(convert(pre+qty)) − round(convert(pre))) so progressive splits
    round on the cumulative boundary, then hands converted units to the existing
    unit/graduated/volume pricers (unchanged, conversion-unaware). Uses UnitConfig.Apply.
  • Registered ahead of DiscountUsage (convert → round → discount), gated by the flag.
  • unitConfig.enabled threaded into the rating service via DI, defaulting off.
  • GetUnitConfig() on the rating line accessor; RateableIntent returns the
    snapshotted charge-intent config.

Testing

  • Mutator unit tests (multiply/divide, all rounding modes, cumulative boundary, idempotency).
  • Pricer registration test (flag on/off ordering, flat price unaffected).
  • End-to-end rating + DB-backed charges integration tests: flag-on bills the converted
    quantity, flag-off bills raw.

Summary by CodeRabbit

  • New Features
    • Added deploy-wide enablement for unit_config during billing rating, including unit conversion with configurable rounding for eligible usage-based pricing.
    • Usage-based charge intents now capture unit_config from rate cards so rating uses the intended units.
  • Bug Fixes
    • Rating now rejects charges when unit_config is present but the feature is disabled, instead of falling back to raw quantities.
    • Split/progressive usage calculations now apply conversion+rounding consistently to the correct endpoints.
  • Tests
    • Added/updated end-to-end and unit tests covering enabled/disabled flows and conversion/rounding behavior.

@rolosp
rolosp requested a review from a team as a code owner June 30, 2026 15:05
@rolosp rolosp added the release-note/feature Release note: Exciting New Features label Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds unit-config-aware billing rating, including a feature flag, conversion/rejection mutators, validation updates, and wiring changes through app, tests, and usage-based intent propagation.

Changes

UnitConfig Rating Feature

Layer / File(s) Summary
Pricing contracts and unit_config accessors
openmeter/productcatalog/price.go, openmeter/productcatalog/price_test.go, openmeter/productcatalog/ratecard.go, openmeter/billing/rating/line.go, openmeter/billing/stdinvoiceline.go, openmeter/billing/charges/usagebased/rating.go, openmeter/billing/charges/usagebased/charge.go
Adds SupportsUnitConfig() on Price, updates rate-card validation to use it, and exposes optional unit-config accessors on billing line and usage-based intent types.
UnitConfig mutators and errors
openmeter/billing/rating/service/mutator/errors.go, openmeter/billing/rating/service/mutator/forbidunitconfig.go, openmeter/billing/rating/service/mutator/forbidunitconfig_test.go, openmeter/billing/rating/service/mutator/unitconfig.go, openmeter/billing/rating/service/mutator/unitconfig_test.go
Adds unit-config-specific errors, a mutator that converts usage quantities when enabled, and a mutator that rejects unit-config-bearing inputs when disabled, with tests.
Rating service config and pricer pipeline
openmeter/billing/rating/service/service.go, openmeter/billing/rating/service/pricer.go, openmeter/billing/rating/service/detailedline.go, openmeter/billing/rating/service/billableperiod.go, openmeter/billing/rating/service/testutil/ubptest.go, openmeter/billing/rating/service/unitconfig_registration_test.go, openmeter/billing/rating/service/rate/unitconfig_rating_test.go, openmeter/billing/charges/usagebased/service/rating/delta/base_test.go, openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go, openmeter/billing/charges/usagebased/service/rating/service_test.go, openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
Adds Config{UnitConfigEnabled} to the rating service, threads it into pricer selection, conditionally registers the new mutators, and covers the resulting rating behavior in unit and integration tests.
App and Wire provider wiring
app/common/config.go, app/common/billing.go, cmd/billing-worker/wire_gen.go, cmd/jobs/internal/wire_gen.go, cmd/server/wire_gen.go
Extends shared config wiring with UnitConfig and updates generated/app constructors to pass unit-config configuration into billing rating service creation.
Charge service wiring and end-to-end unit_config tests
openmeter/billing/charges/service/base_test.go, openmeter/billing/charges/service/unitconfig_rating_test.go, openmeter/billing/charges/testutils/service.go, openmeter/ledger/customerbalance/testenv_test.go, test/app/testenv.go, test/billing/suite.go, test/customer/testenv.go, test/subscription/framework_test.go
Carries unit-config flags and intent data through charge-service test wiring and adds an end-to-end billing test for enabled and disabled unit-config scenarios.
Usage-based intent unit_config snapshot
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go, openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased_test.go
Copies rate-card unit_config into generated usage-based charge intents and verifies cloning and nil handling.
Usage-based line unit_config propagation
openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/usagebased/service/linemapper.go, openmeter/billing/charges/usagebased/service/linemapper_test.go
Threads effective unit_config into usage-based line population and applies unit conversion before usage discounts.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

Suggested labels: release-note/feature, area/billing

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.59% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: applying unit config in rating through a mutator.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/om-397-apply-unit-config

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR applies unit_config during billing rating for the charges path. The main changes are:

  • Wires the unitConfig.enabled setting into the rating service.
  • Adds unit conversion before usage discounts in the rating pipeline.
  • Rejects charge rating when unit_config reaches rating while the feature is disabled.
  • Snapshots unit_config onto usage-based charge intents.
  • Updates charge-backed invoice line mapping to show converted billable quantities.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.
  • The charge rating path now carries unit_config through intent creation, rating, and line mapping.
  • The disabled-feature path now fails closed when charge inputs still carry unit_config.

Important Files Changed

Filename Overview
openmeter/billing/rating/service/mutator/unitconfig.go Adds the unit_config mutator and shared conversion helper used by both rating and charge line mapping.
openmeter/billing/rating/service/pricer.go Registers unit_config handling before usage discounts and adds disabled-feature rejection for charge inputs that carry unit_config.
openmeter/billing/charges/usagebased/charge.go Adds effective unit_config resolution for usage-based charge intents with override-layer precedence.
openmeter/billing/charges/usagebased/service/linemapper.go Applies unit_config before usage discounts when mapping charge runs back to standard invoice lines.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go Copies rate-card unit_config onto subscription-created usage-based charge intents.

Reviews (6): Last reviewed commit: "refactor: use a struct for populateStand..." | Re-trigger Greptile

Comment thread openmeter/billing/stdinvoiceline.go Resolved
@rolosp rolosp changed the title feat: apply unit config in rating via mutator - OM-397 - STILL WIP feat: apply unit config in rating via mutator - OM-397 Jun 30, 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

🤖 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/rating/service/rate/unitconfig_rating_test.go`:
- Around line 18-155: The test suite in TestUnitConfigRating only covers
zero-start usage paths, so it can miss regressions in PreLinePeriodQty handling.
Add one end-to-end split-line case in this test that uses a non-zero pre-line
quantity (for example a 1400 -> 2700 interval with ceiling rounding) and assert
the converted, rounded billed amount. Use the existing TestUnitConfigRating,
GenerateDetailedLines, and mutator.UnitConfig wiring context to verify the
cumulative start/end behavior is exercised.
🪄 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: fe7d7f63-b6e4-4730-860f-5b0d9525e71b

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9649e and e8e7cef.

📒 Files selected for processing (32)
  • app/common/billing.go
  • app/common/config.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/unitconfig_rating_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/service/rating/delta/base_test.go
  • openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
  • openmeter/billing/rating/line.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/detailedline.go
  • openmeter/billing/rating/service/mutator/unitconfig.go
  • openmeter/billing/rating/service/mutator/unitconfig_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/rate/unitconfig_rating_test.go
  • openmeter/billing/rating/service/service.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/rating/service/unitconfig_registration_test.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/productcatalog/price.go
  • openmeter/productcatalog/price_test.go
  • openmeter/productcatalog/ratecard.go
  • test/app/testenv.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go

@rolosp
rolosp force-pushed the feat/om-397-apply-unit-config branch from e8e7cef to d713239 Compare June 30, 2026 17:07
Comment on lines +77 to +79
if unitConfigEnabled {
preCalculationMutators = append(preCalculationMutators, &mutator.UnitConfig{})
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Call me paranoid, but instead of this, I would do something like this:

	if unitConfigEnabled {
		preCalculationMutators = append(preCalculationMutators, &mutator.UnitConfig{})
	} else {
        preCalculationMutators = append(preCalculationMutators, &mutator.ForbidUnitConfig{})
    }

Forbid unit config is a noop, but returns error when the unit config is set on the rateable. This way we are not accidentally ignoring unit configs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

added ForbidUnitConfig

}

_, start := unitConfig.Apply(usage.PreLinePeriodQuantity)
_, end := unitConfig.Apply(usage.PreLinePeriodQuantity.Add(usage.Quantity))

@turip turip Jul 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

just convert the quantity, don't do calculations here. It is not necessarily true that quantity = perlineperiodquantity + periodquantity (e.g. for exotic meters, and charges rating)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment thread test/app/testenv.go Outdated
require.NoError(t, err)

billingRatingService := billingratingservice.New()
billingRatingService := billingratingservice.New(billingratingservice.Config{})

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

enable in all test envs, so that you are validating that there's no regression due to this being enabled.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

return r.Discounts.Clone()
}

func (r RateableIntent) GetUnitConfig() *productcatalog.UnitConfig {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[P1] Subscription charges drop unit_config before rating

This new rating path only sees unit_config through RateableIntent.GetUnitConfig(), but normal subscription-created usage-based charges still never populate Intent.UnitConfig: newUsageBasedChargeIntent in openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go copies price and discounts from rateCardMeta but leaves UnitConfig behind. With unitConfig.enabled on, a plan/subscription rate card using unit_config will still invoice raw metered quantity, while only direct charge-intent tests exercise the converted path. Please snapshot rateCardMeta.UnitConfig into the usage-based charge intent, with a subscription round-trip/invoice test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done, newUsageBasedChargeIntent now snapshots rateCardMeta.UnitConfig onto the usage-based charge intent

price := l.GetPrice()
if price == nil || !price.SupportsUnitConfig() {
return l, nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this should be an error. Don't ignore inconsistencies in billing or rating, instead make them surfaced.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

Comment on lines +59 to 70
// unitConfigLineAccessor wraps a StandardLine to expose a unit_config, which the
// StandardLine type itself never carries.
type unitConfigLineAccessor struct {
*billing.StandardLine

unitConfig *productcatalog.UnitConfig
}

func (l unitConfigLineAccessor) GetUnitConfig() *productcatalog.UnitConfig {
return l.unitConfig
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I would prefer if you add this to the line even if it's not persisted, or add a TODO here to use the line's unit config once it's there.

Given you have done it for charges, you might aswell do this for standard lines.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a TODO comment and deferred the standard-line wiring

@rolosp
rolosp force-pushed the feat/om-397-apply-unit-config branch from d713239 to 2e269dd Compare July 1, 2026 14:09

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
openmeter/billing/charges/service/unitconfig_rating_test.go (2)

128-130: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Second clock.FreezeTime call isn't paired with its own defer UnFreeze().

Line 168 re-freezes time to invoiceAt without a fresh defer clock.UnFreeze() next to it — it only works because the first defer (line 129) still fires at the end. As per coding guidelines, **/*_test.go: "When using clock.FreezeTime(...) in tests, immediately pair it with defer clock.UnFreeze() in the same scope."

Also applies to: 168-168

🤖 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/service/unitconfig_rating_test.go` around lines 128
- 130, The test in unitconfig_rating_test.go freezes time more than once without
pairing each freeze with its own immediate defer UnFreeze call. Update the test
around the second clock.FreezeTime usage so it is followed in the same scope by
defer clock.UnFreeze(), matching the existing pattern used near the first freeze
and keeping the test cleanup local and explicit.

Source: Coding guidelines


40-42: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Redundant TearDownTest overrides.

Both suites override TearDownTest just to forward to s.BaseSuite.TearDownTest() — since BaseSuite is embedded, that method is already promoted automatically. These overrides can just be dropped.

♻️ Drop the no-op overrides
-func (s *unitConfigRatingEnabledSuite) TearDownTest() {
-	s.BaseSuite.TearDownTest()
-}
-

(and the equivalent block for unitConfigRatingDisabledSuite)

Also applies to: 83-85

🤖 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/service/unitconfig_rating_test.go` around lines 40
- 42, Remove the no-op TearDownTest overrides from both
unitConfigRatingEnabledSuite and unitConfigRatingDisabledSuite, since the
embedded BaseSuite already promotes TearDownTest automatically. Keep the suite
types intact and delete the forwarding methods so the test setup/teardown
behavior continues to come from BaseSuite without redundant wrappers.
🤖 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.

Nitpick comments:
In `@openmeter/billing/charges/service/unitconfig_rating_test.go`:
- Around line 128-130: The test in unitconfig_rating_test.go freezes time more
than once without pairing each freeze with its own immediate defer UnFreeze
call. Update the test around the second clock.FreezeTime usage so it is followed
in the same scope by defer clock.UnFreeze(), matching the existing pattern used
near the first freeze and keeping the test cleanup local and explicit.
- Around line 40-42: Remove the no-op TearDownTest overrides from both
unitConfigRatingEnabledSuite and unitConfigRatingDisabledSuite, since the
embedded BaseSuite already promotes TearDownTest automatically. Keep the suite
types intact and delete the forwarding methods so the test setup/teardown
behavior continues to come from BaseSuite without redundant wrappers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: b2f31ac0-ae17-4963-ac0f-b6df6f9605ef

📥 Commits

Reviewing files that changed from the base of the PR and between d713239 and 2e269dd.

📒 Files selected for processing (37)
  • app/common/billing.go
  • app/common/config.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/unitconfig_rating_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/charges/usagebased/service/rating/delta/base_test.go
  • openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
  • openmeter/billing/rating/line.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/detailedline.go
  • openmeter/billing/rating/service/mutator/errors.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig_test.go
  • openmeter/billing/rating/service/mutator/unitconfig.go
  • openmeter/billing/rating/service/mutator/unitconfig_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/rate/unitconfig_rating_test.go
  • openmeter/billing/rating/service/service.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/rating/service/unitconfig_registration_test.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/productcatalog/price.go
  • openmeter/productcatalog/price_test.go
  • openmeter/productcatalog/ratecard.go
  • test/app/testenv.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go
✅ Files skipped from review due to trivial changes (4)
  • openmeter/productcatalog/price_test.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
🚧 Files skipped from review as they are similar to previous changes (20)
  • openmeter/billing/rating/service/unitconfig_registration_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/productcatalog/ratecard.go
  • openmeter/billing/rating/service/detailedline.go
  • app/common/billing.go
  • openmeter/productcatalog/price.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/charges/usagebased/rating.go
  • cmd/billing-worker/wire_gen.go
  • openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go
  • test/billing/suite.go
  • app/common/config.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/rating/service/service.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/charges/usagebased/service/rating/delta/base_test.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/rating/line.go
  • openmeter/billing/charges/service/base_test.go


usage, err := l.GetUsage()
if err != nil {
return l, err

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.

Please wrap the error

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

borosr
borosr previously approved these changes Jul 2, 2026

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

lgtm

tothandras
tothandras previously approved these changes Jul 2, 2026
Amount: 8,
Total: 8,
}, stdLine.Totals)
}

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.

Suggested change
}
s.Require().NotNil(stdLine.UsageBased.Quantity)
s.Equal(float64(8), lo.FromPtr(stdLine.UsageBased.Quantity).InexactFloat64())
}

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.

MeteredQuantity and Quantity mean different things. MeteredQuantity should stay as raw usage, e.g. 7400, while Quantity should be the billable converted amount, e.g. ceil(7400 / 1000) = 8.

The PR makes rating/totals use the converted quantity correctly, so totals become $8, but the invoice line mapper still exposes UsageBased.Quantity = 7400. That makes the invoice/API line internally inconsistent:
raw metered usage is 7400, billable total is based on 8, but customer-facing quantity still says 7400.

The expected result is:

MeteredQuantity: 7400
Quantity: 8
Totals.Amount: 8

A good regression test should assert both: MeteredQuantity == 7400 and Quantity == 8.

@rolosp rolosp Jul 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It was a known issue and was deferred to a later ticket originally, but it is pretty surgical and makes sense to do it here so I've pushed the changes.

@rolosp
rolosp dismissed stale reviews from tothandras and borosr via 70db41a July 2, 2026 13:17
@rolosp
rolosp force-pushed the feat/om-397-apply-unit-config branch from 2e269dd to 70db41a Compare July 2, 2026 13:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
openmeter/billing/charges/usagebased/service/linemapper_test.go (1)

100-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider adding a direct unit_config case here too.

All three tests just pass nil, so the new mutator.ApplyUnitConfig conversion path in populateUsageBasedStandardLineFromRun isn't exercised at this unit-test level (only via nil/identity). If the end-to-end unitconfig_rating_test.go doesn't pin down the exact quantity math for this mapper, a small added case with a non-nil unitConfig would make regressions here easier to catch and localize.

Also applies to: 166-166, 209-209

🤖 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/linemapper_test.go` at line 100,
The tests around populateUsageBasedStandardLineFromRun only exercise the nil
unitConfig path, so the new mutator.ApplyUnitConfig conversion branch is not
covered here. Add at least one direct unit_config case in the linemapper tests
by passing a non-nil unitConfig into populateUsageBasedStandardLineFromRun (or
the related test helper) and assert the resulting quantity math. Use the
existing test setup in the RealizationRuns-based cases so this path is exercised
alongside the current nil/identity coverage.
🤖 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.

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/linemapper_test.go`:
- Line 100: The tests around populateUsageBasedStandardLineFromRun only exercise
the nil unitConfig path, so the new mutator.ApplyUnitConfig conversion branch is
not covered here. Add at least one direct unit_config case in the linemapper
tests by passing a non-nil unitConfig into populateUsageBasedStandardLineFromRun
(or the related test helper) and assert the resulting quantity math. Use the
existing test setup in the RealizationRuns-based cases so this path is exercised
alongside the current nil/identity coverage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d46e9a99-0d8d-4ec4-ba93-c47814d2b901

📥 Commits

Reviewing files that changed from the base of the PR and between 2e269dd and 70db41a.

📒 Files selected for processing (41)
  • app/common/billing.go
  • app/common/config.go
  • cmd/billing-worker/wire_gen.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/unitconfig_rating_test.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/rating.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/rating/delta/base_test.go
  • openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
  • openmeter/billing/rating/line.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/billing/rating/service/detailedline.go
  • openmeter/billing/rating/service/mutator/errors.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig_test.go
  • openmeter/billing/rating/service/mutator/unitconfig.go
  • openmeter/billing/rating/service/mutator/unitconfig_test.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/rating/service/rate/unitconfig_rating_test.go
  • openmeter/billing/rating/service/service.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/rating/service/unitconfig_registration_test.go
  • openmeter/billing/stdinvoiceline.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased_test.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/productcatalog/price.go
  • openmeter/productcatalog/price_test.go
  • openmeter/productcatalog/ratecard.go
  • test/app/testenv.go
  • test/billing/suite.go
  • test/customer/testenv.go
  • test/subscription/framework_test.go
✅ Files skipped from review due to trivial changes (5)
  • app/common/config.go
  • openmeter/billing/rating/service/unitconfig_registration_test.go
  • cmd/billing-worker/wire_gen.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • cmd/jobs/internal/wire_gen.go
🚧 Files skipped from review as they are similar to previous changes (32)
  • test/customer/testenv.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig.go
  • cmd/server/wire_gen.go
  • openmeter/billing/rating/service/billableperiod.go
  • openmeter/productcatalog/price_test.go
  • openmeter/billing/charges/testutils/service.go
  • app/common/billing.go
  • openmeter/billing/rating/line.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased_test.go
  • openmeter/billing/charges/usagebased/service/rating/subtract/subtract_test.go
  • openmeter/billing/rating/service/mutator/errors.go
  • openmeter/billing/stdinvoiceline.go
  • test/app/testenv.go
  • openmeter/productcatalog/ratecard.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • test/billing/suite.go
  • openmeter/billing/rating/service/service.go
  • openmeter/productcatalog/price.go
  • openmeter/ledger/customerbalance/testenv_test.go
  • openmeter/billing/rating/service/mutator/forbidunitconfig_test.go
  • test/subscription/framework_test.go
  • openmeter/billing/rating/service/rate/unitconfig_rating_test.go
  • openmeter/billing/charges/usagebased/service/rating/delta/base_test.go
  • openmeter/billing/charges/usagebased/rating.go
  • openmeter/billing/rating/service/detailedline.go
  • openmeter/billing/rating/service/pricer.go
  • openmeter/billing/charges/service/unitconfig_rating_test.go
  • openmeter/billing/rating/service/mutator/unitconfig_test.go
  • openmeter/billing/rating/service/testutil/ubptest.go
  • openmeter/billing/rating/service/mutator/unitconfig.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/usagebased/service/rating/periodpreserving/engine_test.go

)

func populateUsageBasedStandardLineFromRun(stdLine *billing.StandardLine, run usagebased.RealizationRun, runs usagebased.RealizationRuns) error {
func populateUsageBasedStandardLineFromRun(stdLine *billing.StandardLine, run usagebased.RealizationRun, runs usagebased.RealizationRuns, unitConfig *productcatalog.UnitConfig) error {

@mark-vass-konghq mark-vass-konghq Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Super nit, but these could be more readable in the future and does not have to pass too much parameters to the function itself

Suggested change
func populateUsageBasedStandardLineFromRun(stdLine *billing.StandardLine, run usagebased.RealizationRun, runs usagebased.RealizationRuns, unitConfig *productcatalog.UnitConfig) error {
type populateStandardLineFromRunInput struct {
Run usagebased.RealizationRun
Runs usagebased.RealizationRuns
UnitConfig *productcatalog.UnitConfig
}
func populateStandardLineFromRun(stdLine *billing.StandardLine, input populateStandardLineFromRunInput) error {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

@rolosp
rolosp enabled auto-merge (squash) July 2, 2026 14:19
@rolosp
rolosp disabled auto-merge July 2, 2026 14:23
@rolosp
rolosp enabled auto-merge (squash) July 2, 2026 14:23
@rolosp
rolosp merged commit 0eede87 into main Jul 2, 2026
26 checks passed
@rolosp
rolosp deleted the feat/om-397-apply-unit-config branch July 2, 2026 14:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants