Skip to content

fix: gathering preview totals for charge lines - #4458

Merged
turip merged 2 commits into
mainfrom
feat/billing-gathering-preview-charge-totals
Jun 1, 2026
Merged

turip merged 2 commits into
mainfrom
feat/billing-gathering-preview-charge-totals

Conversation

@turip

@turip turip commented May 29, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the gathering invoice live-data preview regression where charge-backed gathering lines produced zero totals when expanded through InvoiceExpandCalculateGatheringInvoiceWithLiveData.

  • add a required BuildStandardLinesForGatheringPreview line-engine path for converting gathering lines into standard preview lines
  • route gathering invoice live-data calculation through the owning line engines while preserving line order
  • populate flat-fee and usage-based charge preview totals using side-effect-free in-memory realization runs
  • document and test that preview runs do not allocate credits or persist realization state

Issue

Fixes the regression where gathering invoice get/list with InvoiceExpandCalculateGatheringInvoiceWithLiveData returned zero totals for charge-based lines.

I could not find a matching GitHub issue by the regression terms, so this PR describes the fixed issue directly rather than linking an unrelated issue.

Testing

  • make lint-go-fast
  • make test-nocache

Summary by CodeRabbit

  • New Features

    • Gathering invoice preview for flat-fee and usage-based charges: shows totals, per-line amounts, and usage quantities without persisting realizations.
    • Previews are side-effect free and preserve original line IDs; preview runs use deterministic preview IDs.
  • Tests

    • Added comprehensive tests asserting preview behavior, totals, and that no realizations are persisted.

Review Change Stack

@turip turip added kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8ea317ff-b70c-4392-8bf3-607f31e31c00

📥 Commits

Reviewing files that changed from the base of the PR and between 1ed1418 and b78f5c3.

📒 Files selected for processing (7)
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/usagebased_test.go
  • openmeter/billing/charges/usagebased/service/run/preview.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/service/invoice.go
  • test/billing/lineengine_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/charges/service/usagebased_test.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/charges/usagebased/service/run/preview.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/charges/service/invoicable_test.go

📝 Walkthrough

Walkthrough

Adds a side-effect-free preview API (BuildStandardLinesForGatheringPreview) to LineEngine, implements it for flat-fee, usage-based, and credit-purchase engines to produce transient standard invoice lines from gathering lines, refactors gathering-invoice assembly to call per-engine preview builders, and adds tests/mocks for the new flow.

Changes

Gathering Preview Line Building

Layer / File(s) Summary
LineEngine interface and gathering->standard conversion
openmeter/billing/lineengine.go, openmeter/billing/gatheringinvoice.go
Adds BuildStandardLinesForGatheringPreview to the LineEngine interface; adds GatheringLines.ToStandardLines(invoiceID) and an unordered ID-match validator.
Flat-fee preview run builder
openmeter/billing/charges/flatfee/service/realizations/preview.go, openmeter/billing/charges/flatfee/service/lineengine.go
New preview-run builder validates inputs, computes/prorates and rounds amounts, rates lines, constructs transient flatfee.RealizationRun (preview-), and the flat-fee LineEngine populates and validates preview standard lines per run.
Usage-based preview run builder
openmeter/billing/charges/usagebased/service/run/preview.go, openmeter/billing/charges/usagebased/service/lineengine.go
New usage-based preview run builder validates input, rates usage, rounds totals, rejects negative totals, and returns a transient usagebased.RealizationRun (preview-) plus expanded runs. LineEngine builds per-line preview runs and populates usage fields.
Credit-purchase preview implementation
openmeter/billing/charges/creditpurchase/lineengine/engine.go
Credit-purchase engine preview path delegates to GatheringLines.ToStandardLines.
Standard invoice line building refactor & wiring
openmeter/billing/lineengine/stdinvoice.go, openmeter/billing/service/invoice.go
Extracts helper to snapshot quantities; gathering-invoice assembly now groups gathering lines by engine and invokes BuildStandardLinesForGatheringPreview per engine, validates ID sets, and assembles in-scope standard lines by ID.
Tests, helpers, and mocks
openmeter/billing/charges/service/gathering_preview_test.go, openmeter/billing/charges/service/invoicable_test.go, openmeter/billing/charges/service/usagebased_test.go, openmeter/billing/testutils/lineengine.go, test/billing/lineengine_test.go
Adds assertGatheringPreview test helper, tests for flat-fee and usage-based gathering-preview totals and fields (including partial-run scenario), and updates test mocks/utilities to support the preview callback path.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

area/billing

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 'fix: gathering preview totals for charge lines' directly addresses the main regression being fixed—gathering invoice previews returning zero totals for charge-backed lines.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/billing-gathering-preview-charge-totals

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

❤️ Share

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

@turip
turip force-pushed the feat/billing-gathering-preview-charge-totals branch from 0b47d40 to 1ed1418 Compare May 29, 2026 13:24
@turip
turip marked this pull request as ready for review May 29, 2026 13:24
@turip
turip requested a review from a team as a code owner May 29, 2026 13:24
@turip turip changed the title Fix gathering preview totals for charge lines fix; gathering preview totals for charge lines May 29, 2026
@turip turip changed the title fix; gathering preview totals for charge lines fix: gathering preview totals for charge lines May 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (5)
openmeter/billing/lineengine.go (1)

218-220: ⚡ Quick win

Document the no-side-effects contract here.

This method is now the preview-specific escape hatch, but the comment only says “transient.” I’d make the contract explicit that implementations must not persist realization state, allocate credits, or cause other side effects, so future engines don’t accidentally reuse the mutating path.

💡 Suggested comment tweak
- // BuildStandardLinesForGatheringPreview materializes gathering lines into a transient standard invoice preview.
- // Returned standard lines must reuse the exact same line IDs as the input gathering lines.
+ // BuildStandardLinesForGatheringPreview materializes gathering lines into a transient standard invoice preview.
+ // Implementations must be side-effect free: they must not persist realization state, allocate credits,
+ // or mutate external state. Returned standard lines must reuse the exact same line IDs as the input
+ // gathering lines.
  BuildStandardLinesForGatheringPreview(ctx context.Context, input BuildStandardInvoiceLinesInput) (StandardLines, error)
🤖 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/lineengine.go` around lines 218 - 220, Update the comment
for BuildStandardLinesForGatheringPreview to explicitly state the
no-side-effects contract: document that implementations must be preview-only and
must not persist any realization state, modify or allocate credits, mutate input
IDs, emit events, or perform external side effects (DB writes, message queues,
billing operations); clarify that returned StandardLines must reuse the exact
same line IDs as the input gathering lines and that this method is safe to call
for read-only previews only. Use the function name
BuildStandardLinesForGatheringPreview and types
BuildStandardInvoiceLinesInput/StandardLines in the comment so future
implementers can find and follow the contract.
openmeter/billing/gatheringinvoice.go (1)

232-245: ⚡ Quick win

This helper name is stronger than the check it does.

ValidateStandardLineIDsMatchGatheringLinesExactly reads like an order-sensitive equality check, but lo.ElementsMatch only verifies the same ID multiset. Either switch to an ordered comparison or rename the helper so the contract stays honest.

As per coding guidelines, "Keep helper functions honest and narrow."

🤖 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/gatheringinvoice.go` around lines 232 - 245, The function
ValidateStandardLineIDsMatchGatheringLinesExactly is misnamed because it
performs an order-insensitive multiset comparison using lo.ElementsMatch; rename
it to a truthful name (e.g., ValidateStandardLineIDsMatchGatheringLinesUnordered
or ValidateStandardLineIDsMatchGatheringLinesAsMultiset) and update all
callers/tests to use the new name, or alternatively change the implementation to
perform an ordered comparison (compare expectedIDs and actualIDs slices
element-by-element) if you intend to enforce order — pick one approach and make
the corresponding updates to the function body and all references to
ValidateStandardLineIDsMatchGatheringLinesExactly.
openmeter/billing/charges/service/invoicable_test.go (1)

52-119: ⚡ Quick win

Cover the “no credit allocation during preview” part explicitly.

These tests nicely prove that preview leaves realization state untouched, but they don’t actually prove the allocator hooks stay idle. With no credits on the customer and no counted allocator installed, they’d still pass if preview accidentally called allocation and just got back zero. I’d add promotional credits or a counted onAllocateCredits handler here and assert zero invocations.

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

Also applies to: 121-206

🤖 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/invoicable_test.go` around lines 52 - 119,
In TestFlatFeeGatheringPreviewPopulatesTotalsWithoutRealizationRun ensure the
allocator isn't invoked during preview by adding a counted onAllocateCredits
handler (or provisioning promotional credits) and asserting it is never called:
wire a mock/counting allocator into the test setup (or attach promotional
credits to customer) before calling s.Charges.Create and the
s.assertGatheringPreview call, then assert the counter is zero (or no credits
were consumed) after preview; reference the test function
TestFlatFeeGatheringPreviewPopulatesTotalsWithoutRealizationRun, the
createMockChargeIntent invocation, the s.assertGatheringPreview call, and the
post-check using mustGetFlatFeeChargeWithExpands/flatFeeChargeID to verify
realizations remain untouched.
openmeter/billing/charges/service/usagebased_test.go (1)

269-315: ⚡ Quick win

Reuse assertGatheringPreview here to keep the preview checks in one place.

This subtest is open-coding the same ListInvoices(...With(InvoiceExpandCalculateGatheringInvoiceWithLiveData)) + invoice/line shape assertions that s.assertGatheringPreview(...) already wraps. Reusing that helper and keeping only the usage-based assertions in AssertLine would make this scenario a lot easier to keep in sync with the other preview tests.

As per coding guidelines, **/*.go: In general when reviewing the Golang code make readability and maintainability a priority.

🤖 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/usagebased_test.go` around lines 269 - 315,
Replace the duplicated invoice preview assertions with a call to
s.assertGatheringPreview that invokes ListInvoices with
InvoiceExpandCalculateGatheringInvoiceWithLiveData; pass an AssertLine closure
that performs only the usage-specific checks (inspect previewLine.UsageBased
fields and DetailedLines) and keep the charge state assertions using
s.mustGetUsageBasedChargeByID(usageBasedChargeID), verifying charge.Status ==
usagebased.StatusActivePartialInvoiceWaitingForCollection,
len(charge.Realizations) == 1 and current run ID equals partialRunID via
charge.GetCurrentRealizationRun(); this consolidates ListInvoices/preview shape
checks into assertGatheringPreview and leaves only the usage-based and
run-status assertions in this subtest.
test/billing/lineengine_test.go (1)

89-95: ⚡ Quick win

Add one small contract test for the preview callback path.

Nice to have the mock support BuildStandardLinesForGatheringPreview, but this file still doesn’t assert that live gathering expansion actually dispatches to that callback instead of BuildStandardInvoiceLines. A tiny test that returns different lines from the two callbacks would lock this regression fix in pretty well.

As per coding guidelines, **/*_test.go: 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 `@test/billing/lineengine_test.go` around lines 89 - 95, Add a unit test that
verifies the preview-path uses the preview callback: instantiate
mockCollectionCompletedLineEngine with buildStandardLinesForGatheringPreview
returning a distinct StandardLines value and
buildStandardInvoiceLinesWithLiveData returning a different value, then exercise
the live-gathering preview code path (the same helper used elsewhere in tests
that previously routed to BuildStandardInvoiceLines) and assert the returned
lines equal the value from BuildStandardLinesForGatheringPreview (not the
BuildStandardInvoiceLines value); reference the mock type
mockCollectionCompletedLineEngine and the methods
BuildStandardLinesForGatheringPreview, BuildStandardInvoiceLines (and helper
mustAsNewStandardLines if needed) to locate where to wire the callbacks.
🤖 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/run/preview.go`:
- Around line 49-50: The Validate() logic currently only checks
in.FeatureMeter.Meter and can panic when code later dereferences
in.FeatureMeter.Feature.ID; update the validation in the preview run (the
Validate function handling FeatureMeter) to also verify that
in.FeatureMeter.Feature is non-nil and that Feature.ID (or equivalent
identifier) is present/non-empty, and if not append a validation error (e.g.,
errors.New("feature is required" or "feature ID is required")) to errs so the
preview path returns a validation error instead of panicking.

---

Nitpick comments:
In `@openmeter/billing/charges/service/invoicable_test.go`:
- Around line 52-119: In
TestFlatFeeGatheringPreviewPopulatesTotalsWithoutRealizationRun ensure the
allocator isn't invoked during preview by adding a counted onAllocateCredits
handler (or provisioning promotional credits) and asserting it is never called:
wire a mock/counting allocator into the test setup (or attach promotional
credits to customer) before calling s.Charges.Create and the
s.assertGatheringPreview call, then assert the counter is zero (or no credits
were consumed) after preview; reference the test function
TestFlatFeeGatheringPreviewPopulatesTotalsWithoutRealizationRun, the
createMockChargeIntent invocation, the s.assertGatheringPreview call, and the
post-check using mustGetFlatFeeChargeWithExpands/flatFeeChargeID to verify
realizations remain untouched.

In `@openmeter/billing/charges/service/usagebased_test.go`:
- Around line 269-315: Replace the duplicated invoice preview assertions with a
call to s.assertGatheringPreview that invokes ListInvoices with
InvoiceExpandCalculateGatheringInvoiceWithLiveData; pass an AssertLine closure
that performs only the usage-specific checks (inspect previewLine.UsageBased
fields and DetailedLines) and keep the charge state assertions using
s.mustGetUsageBasedChargeByID(usageBasedChargeID), verifying charge.Status ==
usagebased.StatusActivePartialInvoiceWaitingForCollection,
len(charge.Realizations) == 1 and current run ID equals partialRunID via
charge.GetCurrentRealizationRun(); this consolidates ListInvoices/preview shape
checks into assertGatheringPreview and leaves only the usage-based and
run-status assertions in this subtest.

In `@openmeter/billing/gatheringinvoice.go`:
- Around line 232-245: The function
ValidateStandardLineIDsMatchGatheringLinesExactly is misnamed because it
performs an order-insensitive multiset comparison using lo.ElementsMatch; rename
it to a truthful name (e.g., ValidateStandardLineIDsMatchGatheringLinesUnordered
or ValidateStandardLineIDsMatchGatheringLinesAsMultiset) and update all
callers/tests to use the new name, or alternatively change the implementation to
perform an ordered comparison (compare expectedIDs and actualIDs slices
element-by-element) if you intend to enforce order — pick one approach and make
the corresponding updates to the function body and all references to
ValidateStandardLineIDsMatchGatheringLinesExactly.

In `@openmeter/billing/lineengine.go`:
- Around line 218-220: Update the comment for
BuildStandardLinesForGatheringPreview to explicitly state the no-side-effects
contract: document that implementations must be preview-only and must not
persist any realization state, modify or allocate credits, mutate input IDs,
emit events, or perform external side effects (DB writes, message queues,
billing operations); clarify that returned StandardLines must reuse the exact
same line IDs as the input gathering lines and that this method is safe to call
for read-only previews only. Use the function name
BuildStandardLinesForGatheringPreview and types
BuildStandardInvoiceLinesInput/StandardLines in the comment so future
implementers can find and follow the contract.

In `@test/billing/lineengine_test.go`:
- Around line 89-95: Add a unit test that verifies the preview-path uses the
preview callback: instantiate mockCollectionCompletedLineEngine with
buildStandardLinesForGatheringPreview returning a distinct StandardLines value
and buildStandardInvoiceLinesWithLiveData returning a different value, then
exercise the live-gathering preview code path (the same helper used elsewhere in
tests that previously routed to BuildStandardInvoiceLines) and assert the
returned lines equal the value from BuildStandardLinesForGatheringPreview (not
the BuildStandardInvoiceLines value); reference the mock type
mockCollectionCompletedLineEngine and the methods
BuildStandardLinesForGatheringPreview, BuildStandardInvoiceLines (and helper
mustAsNewStandardLines if needed) to locate where to wire the callbacks.
🪄 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: 9e80a6ea-eee1-4991-b869-5d9322f631d1

📥 Commits

Reviewing files that changed from the base of the PR and between 819c22b and 1ed1418.

📒 Files selected for processing (14)
  • openmeter/billing/charges/creditpurchase/lineengine/engine.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/realizations/preview.go
  • openmeter/billing/charges/service/gathering_preview_test.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/service/usagebased_test.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/run/preview.go
  • openmeter/billing/gatheringinvoice.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/lineengine/stdinvoice.go
  • openmeter/billing/service/invoice.go
  • openmeter/billing/testutils/lineengine.go
  • test/billing/lineengine_test.go

@turip
turip merged commit 7d639dd into main Jun 1, 2026
27 checks passed
@turip
turip deleted the feat/billing-gathering-preview-charge-totals branch June 1, 2026 09:36

This branch was previously deployed

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

Labels

kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants