Repository navigation
fix: gathering preview totals for charge lines - #4458
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (6)
📝 WalkthroughWalkthroughAdds 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. ChangesGathering Preview Line Building
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
0b47d40 to
1ed1418
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
openmeter/billing/lineengine.go (1)
218-220: ⚡ Quick winDocument 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 winThis helper name is stronger than the check it does.
ValidateStandardLineIDsMatchGatheringLinesExactlyreads like an order-sensitive equality check, butlo.ElementsMatchonly 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 winCover 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
onAllocateCreditshandler 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 winReuse
assertGatheringPreviewhere to keep the preview checks in one place.This subtest is open-coding the same
ListInvoices(...With(InvoiceExpandCalculateGatheringInvoiceWithLiveData))+ invoice/line shape assertions thats.assertGatheringPreview(...)already wraps. Reusing that helper and keeping only the usage-based assertions inAssertLinewould 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 winAdd 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 ofBuildStandardInvoiceLines. 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
📒 Files selected for processing (14)
openmeter/billing/charges/creditpurchase/lineengine/engine.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/realizations/preview.goopenmeter/billing/charges/service/gathering_preview_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/service/usagebased_test.goopenmeter/billing/charges/usagebased/service/lineengine.goopenmeter/billing/charges/usagebased/service/run/preview.goopenmeter/billing/gatheringinvoice.goopenmeter/billing/lineengine.goopenmeter/billing/lineengine/stdinvoice.goopenmeter/billing/service/invoice.goopenmeter/billing/testutils/lineengine.gotest/billing/lineengine_test.go
Summary
Fixes the gathering invoice live-data preview regression where charge-backed gathering lines produced zero totals when expanded through
InvoiceExpandCalculateGatheringInvoiceWithLiveData.BuildStandardLinesForGatheringPreviewline-engine path for converting gathering lines into standard preview linesIssue
Fixes the regression where gathering invoice get/list with
InvoiceExpandCalculateGatheringInvoiceWithLiveDatareturned 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-fastmake test-nocacheSummary by CodeRabbit
New Features
Tests