Repository navigation
feat: persist detailed lines - #4202
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 (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds persisted “detailed lines” for flat‑fee and usage‑based charges, a shared Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant FlatFeeService as Flat‑Fee Service
participant FlatFeeAdapter as Flat‑Fee Adapter
participant DB as Database
Client->>FlatFeeService: UpsertDetailedLines(chargeID, lines)
FlatFeeService->>FlatFeeAdapter: UpsertDetailedLines(chargeID, lines)
FlatFeeAdapter->>DB: Soft‑delete existing lines by (namespace,chargeID,child_ref)
FlatFeeAdapter->>DB: Bulk create/upsert lines (ON CONFLICT update)
DB-->>FlatFeeAdapter: OK/Error
FlatFeeAdapter-->>FlatFeeService: OK/Error
FlatFeeService-->>Client: OK/Error
Client->>FlatFeeService: GetByID(..., ExpandDetailedLines)
FlatFeeService->>FlatFeeAdapter: GetByID(..., ExpandDetailedLines)
FlatFeeAdapter->>DB: Query charge + realizations
FlatFeeAdapter->>DB: Query detailed lines (namespace,chargeID)
DB-->>FlatFeeAdapter: DetailedLines
FlatFeeAdapter->>FlatFeeService: Charge with DetailedLines
FlatFeeService-->>Client: Charge with DetailedLines
sequenceDiagram
participant StateMachine as Usage StateMachine
participant UsageService as Usage Service
participant Adapter as Usage Adapter
participant DB as Database
participant Rater as Rating Service
StateMachine->>Adapter: FetchDetailedLines(charge) %% ensureDetailedLinesLoadedForRating
Adapter->>DB: Query run detailed lines by (namespace,chargeID,runID)
DB-->>Adapter: DetailedLines
Adapter-->>StateMachine: charge with DetailedLines
StateMachine->>Rater: GetDetailedLinesForUsage(Charge, PriorRuns,...)
Rater->>Rater: GenerateDetailedLines(...)
Rater->>Rater: Append service period to ChildUniqueReferenceIDs
Rater-->>StateMachine: DetailedLines result
StateMachine->>Adapter: UpsertRunDetailedLines(chargeID, runID, lines)
Adapter->>DB: Soft‑delete existing run lines not in incoming child refs
Adapter->>DB: Bulk create/upsert new run lines
DB-->>Adapter: OK/Error
Adapter-->>StateMachine: OK/Error
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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 |
bddc2c1 to
732e69a
Compare
732e69a to
dd4bd45
Compare
dd4bd45 to
d5fe4e0
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (16)
openmeter/billing/charges/usagebased/service/get.go (1)
111-175: Minor: error-channel draining is correct but a bit heavyweight.The
errChbuffered atlen(charges)+sync.Map+ post-loop range is fine and safe, but since you're already usingwg, this could be simplified with anerrgroup.Group(with a semaphore-like concurrency cap viag.SetLimit(defaultMaxParallelRatingsPerRequest)), which would replace the semaphore, WaitGroup, errCh, and the nil-check filter loop. Totally optional — leaving as-is is also perfectly readable.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/get.go` around lines 111 - 175, Replace the manual semaphore/wg/errCh pattern with an errgroup to simplify concurrency: create an errgroup via errgroup.WithContext(ctx), call g.SetLimit(defaultMaxParallelRatingsPerRequest), and for each charge use g.Go(func() error { ... }) to run the rating work (invoke s.rater.GetTotalsForUsage) and return any error instead of pushing to errCh; store results into ratingResults (keep sync.Map or switch to a map guarded by a mutex) inside the goroutine; after the loop call g.Wait() and return its error (or nil) — remove sem.Acquire/Release, wg, errCh, the post-loop draining logic, and the manual error aggregation.openmeter/billing/charges/usagebased/service_test.go (1)
11-17: Nice little unit test — optional polish with table-driven cases.Tight and covers the key rules. 👍 Couple of tiny ideas if you feel like it:
- Add a case for empty
meta.Expands{}to lock in the "no expands requested" behavior.- Convert to a table-driven test with
t.Run(name, ...)subtests so failures point at the specific case that broke.- Consider asserting on the error type/message (e.g.,
require.ErrorIsor a substring match) so a refactor doesn't silently change which error is returned.All optional — happy with the current file if you want to keep it minimal.
♻️ Example table-driven rewrite
-func TestValidateExpands(t *testing.T) { - t.Parallel() - - require.NoError(t, validateExpands(meta.Expands{meta.ExpandRealizations})) - require.NoError(t, validateExpands(meta.Expands{meta.ExpandRealizations, meta.ExpandDetailedLines})) - require.Error(t, validateExpands(meta.Expands{meta.ExpandDetailedLines})) -} +func TestValidateExpands(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expands meta.Expands + wantErr bool + }{ + {"empty", meta.Expands{}, false}, + {"realizations only", meta.Expands{meta.ExpandRealizations}, false}, + {"realizations + detailed lines", meta.Expands{meta.ExpandRealizations, meta.ExpandDetailedLines}, false}, + {"detailed lines without realizations", meta.Expands{meta.ExpandDetailedLines}, true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + err := validateExpands(tc.expands) + if tc.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) + } +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service_test.go` around lines 11 - 17, Update TestValidateExpands to a table-driven subtest style: create a slice of cases (name, input meta.Expands, expected error boolean and optionally expected error value/message), iterate cases and call t.Run(case.name, func(t *testing.T){ t.Parallel(); if case.expectError { require.ErrorIs(t, validateExpands(case.input), <expected error>) or require.Error(t, validateExpands(case.input)) } else { require.NoError(t, validateExpands(case.input)) } }); include a case for an empty meta.Expands{} to lock in "no expands requested" behavior and use meta.ExpandRealizations and meta.ExpandDetailedLines in the inputs; assert specific error type/message with require.ErrorIs or a substring match where appropriate.openmeter/billing/charges/usagebased/service/creditsonly.go (1)
216-221: Tiny nit: the localcurrentRun.DetailedLinesmutation is effectively unused here.Setting
currentRun.DetailedLines = mo.Some(runDetailedLines)on line 220 only updates a local value copy — it isn't written back tos.Charge.Realizations(unlike increditheninvoice.gowheres.Charge.Realizations.SetRealizationRun(currentRun)is called afterwards). The subsequentUpdateRealizationRundoesn't carry detailed lines either, andRefetchChargeat the end reloads state from the DB, so nothing downstream reads this field before the refetch.Either drop the assignment or add a
SetRealizationRun(currentRun)for symmetry withcreditheninvoice.go. Not a functional bug, just a readability snag that future-you will thank present-you for. 🙂♻️ Option A — drop the dead assignment
- runDetailedLines, err := s.Runs.PersistRunDetailedLines(ctx, s.Charge, currentRun, ratingResult) - if err != nil { + if _, err := s.Runs.PersistRunDetailedLines(ctx, s.Charge, currentRun, ratingResult); err != nil { return err } - currentRun.DetailedLines = mo.Some(runDetailedLines)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/creditsonly.go` around lines 216 - 221, The local assignment currentRun.DetailedLines = mo.Some(runDetailedLines) is dead because it isn't propagated to s.Charge.Realizations or read before RefetchCharge; either remove that assignment entirely, or if you want symmetry with creditheninvoice.go, call s.Charge.Realizations.SetRealizationRun(currentRun) after computing runDetailedLines so the updated DetailedLines is stored in the charge realizations; update the code around PersistRunDetailedLines/UpdateRealizationRun accordingly.openmeter/billing/charges/usagebased/adapter/charge.go (1)
158-165: Potential N+1 inGetByIDswhen expanding detailed lines.Nice conditional expansion — but calling
tx.FetchDetailedLines(ctx, charge)once per charge insideslicesx.MapWithErrmeans a batchGetByIDswithExpandDetailedLinesdoes N separate DB queries (one per charge). For small batches it's fine, but on hot paths this could add up.A single batched query that fetches all detailed lines for all charges at once, then stitches them back in memory, would cut this down to one DB round-trip. Worth considering as a future optimization if batch expand calls become frequent.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/adapter/charge.go` around lines 158 - 165, GetByIDs is causing an N+1 when input.Expands.Has(meta.ExpandDetailedLines) because the current slicesx.MapWithErr loop calls tx.FetchDetailedLines(ctx, charge) per charge; change this to a single batched fetch: collect all charge IDs in GetByIDs, call a new tx.FetchDetailedLinesBatch(ctx, ids) (or overload FetchDetailedLines to accept []ids) to load all detailed lines in one DB round-trip, then stitch the returned lines back into the corresponding usagebased.Charge objects before returning; update the call site where slicesx.MapWithErr and tx.FetchDetailedLines are used so it uses the batched fetch and in-memory join instead of per-charge DB calls.openmeter/billing/charges/flatfee/service/helpers.go (1)
22-26: Add a clarifying comment about soft-delete semantics.The helper is correct, but since
UpsertDetailedLinessoft-deletes any existing rows not present in the input list (reconciliation pattern), it's worth documenting that an emptyDetailedLineswould wipe all persisted detailed lines for the charge. A brief comment like// Note: empty DetailedLines soft-deletes all existing detailed lines for this chargehelps future readers understand the reconcile behavior without digging into the adapter.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/service/helpers.go` around lines 22 - 26, Add a brief clarifying comment above the persistDetailedLines function to note the soft-delete/reconciliation semantics: explain that s.adapter.UpsertDetailedLines will soft-delete any existing detailed lines not present in the provided list, so passing an empty line.DetailedLines will remove all persisted detailed lines for that charge; reference persistDetailedLines, UpsertDetailedLines, and DetailedLines in the comment so future readers understand the reconcile behavior without inspecting the adapter.openmeter/billing/charges/usagebased/service/run/create.go (1)
191-198: Tiny cleanup: avoid setting the current run twice.With the unconditional
SetRealizationRunbelow, the credit-allocation branch no longer needs its own copy. The shared error message can also stay generic since it now covers both credits and detailed lines.♻️ Proposed cleanup
- if err := updatedCharge.Realizations.SetRealizationRun(currentRun); err != nil { - return CreateRatedRunResult{}, fmt.Errorf("update realization run: %w", err) - } } if err := updatedCharge.Realizations.SetRealizationRun(currentRun); err != nil { - return CreateRatedRunResult{}, fmt.Errorf("update realization run detailed lines: %w", err) + return CreateRatedRunResult{}, fmt.Errorf("update realization run: %w", err) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/run/create.go` around lines 191 - 198, The code calls updatedCharge.Realizations.SetRealizationRun(currentRun) twice (once inside a conditional branch and again unconditionally), so remove the duplicate inside the credit-allocation branch and keep only the single unconditional call; consolidate the error handling to return CreateRatedRunResult{} with a single generic fmt.Errorf("update realization run: %w", err) from the remaining SetRealizationRun call to cover both credits and detailed lines, referencing updatedCharge.Realizations.SetRealizationRun and CreateRatedRunResult.tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql (1)
1-12: Double-check the lock window for this index rebuild.The predicate change is consistent, but dropping/recreating three unique indexes can block writes while the indexes rebuild if these detailed-line tables are already large. Worth scheduling carefully or using a concurrent/expand-contract plan if production row counts are high.
As per coding guidelines, Performance should be a priority in critical code paths. Anything related to event ingestion, message processing, database operations (regardless of database) should be vetted for potential performance bottlenecks.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql` around lines 1 - 12, Dropping and recreating the three unique indexes (billingstdinvdetailedline_ns_parent_child_id on billing_standard_invoice_detailed_lines, chargeffdetailedline_ns_charge_child_id on charge_flat_fee_detailed_line, and chargeubdetailedline_ns_charge_run_child_id on charge_usage_based_run_detailed_line) will rebuild the indexes and can block writes; change the migration to use a non-blocking expand/contract approach (create the new UNIQUE INDEX CONCURRENTLY with the new predicate or a temporary non-unique concurrent index, backfill/verify, then drop the old index and rename the new one) or run CREATE INDEX CONCURRENTLY for the new index and then DROP INDEX CONCURRENTLY for the old one, and document scheduling requirements so this runs in a maintenance window if row counts are large.openmeter/billing/models/stddetailedline/create.go (1)
32-51: Minor consistency nit:DeletedAtisn't normalized to UTC.The service-period bounds are explicitly
.In(time.UTC), andFromDBinmapping.gonormalizesDeletedAtviaconvert.TimePtrIn(..., time.UTC). HereSetNillableDeletedAt(line.DeletedAt)passes the pointer through as-is, so a caller handing in a non-UTC time will persist it in whatever zone they supplied — asymmetric with the read path and potentially confusing down the line.♻️ Suggested tweak
create := creator. SetName(line.Name). SetNillableDescription(line.Description). SetCurrency(line.Currency). SetServicePeriodStart(line.ServicePeriod.From.In(time.UTC)). SetServicePeriodEnd(line.ServicePeriod.To.In(time.UTC)). SetQuantity(line.Quantity). SetPerUnitAmount(line.PerUnitAmount). SetCategory(line.Category). SetPaymentTerm(line.PaymentTerm). SetNillableIndex(line.Index). SetChildUniqueReferenceID(line.ChildUniqueReferenceID). - SetNillableDeletedAt(line.DeletedAt) + SetNillableDeletedAt(convert.TimePtrIn(line.DeletedAt, time.UTC))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/models/stddetailedline/create.go` around lines 32 - 51, The Create function is passing line.DeletedAt through without timezone normalization (via SetNillableDeletedAt), causing asymmetry with the read-path which uses convert.TimePtrIn(..., time.UTC) in FromDB; update Create (in create.go) to normalize DeletedAt to UTC before calling SetNillableDeletedAt (e.g., apply the same conversion used in mapping.go/FromDB) so persisted DeletedAt values are consistently in UTC.openmeter/billing/charges/usagebased/adapter/detailedline_test.go (2)
192-196: Nice replacement/soft-delete coverage — one extra assertion could harden it.You validate that
"keep"was updated (quantity 3, description cleared) and"delete"was soft-deleted, which is great. Consider also asserting that the new"new"line came through with its description set — right now a regression that dropped descriptions on fresh upserts wouldn't be caught.✨ Suggested extra assertion
s.Nil(fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[0].Description) + s.Equal(lo.ToPtr("new description"), fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[1].Description) + s.Equal(float64(4), fetchedCharge.Realizations[0].DetailedLines.OrEmpty()[1].Quantity.InexactFloat64())🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go` around lines 192 - 196, Add an assertion to verify the newly upserted detailed line ("new@[2026-01-01T00:00:00Z..2026-02-01T00:00:00Z]") includes its description (and optionally its expected quantity) so regressions that drop descriptions on fresh upserts are detected; locate the test block that inspects fetchedCharge.Realizations[0].DetailedLines.OrEmpty() and add an s.NotNil / s.Equal check against DetailedLines.OrEmpty()[1].Description (and/or s.Equal on DetailedLines.OrEmpty()[1].Quantity.InexactFloat64()) to confirm the "new" line's description is present and correct.
57-64:defer migrator.CloseOrLogError()insideSetupSuitecloses before tests run.Because
deferfires whenSetupSuitereturns (not when the suite tears down), the migrator is closed right afterUp()completes. That's actually fine since you only need it for migrations here — just flagging so it doesn't surprise anyone later if the migrator is needed across tests. If you prefer symmetry, an explicitmigrator.CloseOrLogError()right aftermigrator.Up()would read more intentionally than a defer that runs immediately.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go` around lines 57 - 64, The defer call to migrator.CloseOrLogError() inside SetupSuite closes the migrator as soon as SetupSuite returns (so it runs immediately after migrator.Up()), which can be surprising; either replace the defer with an explicit migrator.CloseOrLogError() immediately after calling migrator.Up() inside SetupSuite, or move the defer (or a call) into your suite teardown (e.g., TearDownSuite) so the migrator remains open for the lifetime of the tests; update references to migrator, SetupSuite, migrator.Up(), and migrator.CloseOrLogError() accordingly.openmeter/billing/charges/usagebased/service/run/detailedline.go (1)
36-71:runparameter is unused in the mapper.
mapRatingResultToRunDetailedLinestakesrun usagebased.RealizationRunbut never reads it — the run linkage is established later inPersistRunDetailedLinesviarun.IDpassed to the adapter. Either drop it from the signature or thread run-scoped data (e.g., a run-specific timestamp) onto the mapped line so the name reflects reality.♻️ Quick cleanup if the argument truly isn't needed
-func mapRatingResultToRunDetailedLines( - charge usagebased.Charge, - run usagebased.RealizationRun, - ratingResult usagebasedrating.GetRatingForUsageResult, -) usagebased.DetailedLines { +func mapRatingResultToRunDetailedLines( + charge usagebased.Charge, + ratingResult usagebasedrating.GetRatingForUsageResult, +) usagebased.DetailedLines { ... - detailedLines := mapRatingResultToRunDetailedLines(charge, run, ratingResult) + detailedLines := mapRatingResultToRunDetailedLines(charge, ratingResult)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/run/detailedline.go` around lines 36 - 71, The mapRatingResultToRunDetailedLines function currently accepts run usagebased.RealizationRun but never uses it; remove the unused run parameter from mapRatingResultToRunDetailedLines (and update all callers, e.g., where PersistRunDetailedLines invokes it) OR if run-scoped data is required, thread run into the mapping and populate a run-specific field on usagebased.DetailedLine (for example RunID or RunTimestamp) so the mapped lines reflect the run (update the function signature mapRatingResultToRunDetailedLines and the return population of usagebased.DetailedLine accordingly, and adjust PersistRunDetailedLines and any adapter calls that expect the new field).openmeter/billing/charges/usagebased/service/run/detailedline_test.go (1)
70-79: Consider assertingChildUniqueReferenceID,Name, and the numeric fields too.This test nicely covers the scaffolding fields, but a core mapping responsibility is carrying
ChildUniqueReferenceID(andName/Quantity/PerUnitAmount) from the rating result onto the detailed line. Right now a regression there would slip through silently. Adding a few morerequire.Equalcalls would lock that behavior down.✨ Suggested additional assertions
require.NotNil(t, out[0].TaxConfig) require.NotSame(t, charge.Intent.TaxConfig, out[0].TaxConfig) + require.Equal(t, "Usage", out[0].Name) + require.Equal(t, "unit-price-usage@[2025-01-01T00:00:00Z..2025-02-01T00:00:00Z]", out[0].ChildUniqueReferenceID) + require.True(t, alpacadecimal.NewFromInt(12).Equal(out[0].Quantity)) + require.True(t, alpacadecimal.NewFromInt(3).Equal(out[0].PerUnitAmount))Note: the test input sets
ChildUniqueReferenceIDto"unit-price-usage@[...]"already, so the mapper is expected to pass it through verbatim (service-period suffixing is handled upstream inrating.GetDetailedLinesForUsage).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/run/detailedline_test.go` around lines 70 - 79, Add assertions that verify the mapper carries through the item identity and numeric values: in the test using mapRatingResultToRunDetailedLines (detailedline_test.go) add require.Equal checks on out[0].ChildUniqueReferenceID, out[0].Name and the numeric fields out[0].Quantity and out[0].PerUnitAmount (and/or TotalAmount if applicable) to match the input rating result values used in the test; this ensures mapRatingResultToRunDetailedLines preserves the ChildUniqueReferenceID/name/quantity/per-unit amount mapping rather than silently regressing.openmeter/billing/charges/usagebased/adapter/detailedline.go (1)
65-102: Optional: guard againstchargeID/runIDnamespace mismatch. 🔒
UpsertRunDetailedLinesusesrunID.Namespacefor the soft-deleteWhereclause and forlineToPersist.Namespace, whilechargeID.IDis used for the charge filter. If a caller ever passes achargeIDandrunIDfrom different namespaces, the soft-delete/upsert would silently operate on the wrong partition. A cheapif chargeID.Namespace != runID.Namespace { return fmt.Errorf(...) }at the top would make the invariant explicit and future-proof. Not a blocker — current callers likely always pass matching namespaces.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/adapter/detailedline.go` around lines 65 - 102, Add a namespace-consistency guard at the start of UpsertRunDetailedLines (after chargeID.Validate(), runID.Validate(), lines.Validate()) that checks chargeID.Namespace vs runID.Namespace and returns a clear error if they differ; use the existing symbols (chargeID.Namespace, runID.Namespace) and return a fmt.Errorf or wrapped error indicating the mismatch so the soft-delete and created line.Namespace cannot cross partitions silently.openmeter/billing/charges/flatfee/adapter/detailedline_test.go (1)
145-177: Nice coverage — one tiny suggestion. ✨Consider also asserting that the
"keep"line preserves its original DBIDandCreatedAtacross the two upserts. That would lock in theSetIgnore(FieldID)/SetIgnore(FieldCreatedAt)behavior in theOnConflictresolver and catch any future regression that accidentally regenerates IDs on conflict. Totally optional — what's here already covers the main replacement + soft-delete semantics well.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/adapter/detailedline_test.go` around lines 145 - 177, Add assertions that the "keep" detailed line preserves its DB ID and CreatedAt across the two UpsertDetailedLines calls: when you create initialLines capture the ID and CreatedAt for the line whose ChildUniqueReferenceID == "keep" (from the value returned by UpsertDetailedLines or by fetching it after the first upsert via adapter.GetByID), then after the replacement UpsertDetailedLines call fetch the charge (as you already do) and assert that fetchedCharge.Realizations.DetailedLines.OrEmpty()[0].ID equals the original ID and that its CreatedAt equals the original CreatedAt; this locks in the SetIgnore(FieldID)/SetIgnore(FieldCreatedAt) behavior in the UpsertDetailedLines conflict resolver.openmeter/billing/charges/flatfee/service/lineengine.go (1)
60-89: Consider batching charge fetches to avoid N+1 on invoice creation.Each line triggers its own
GetByID(...)call withExpandRealizations—for invoices with many flat-fee lines, this adds up fast on a hot path. Since you're already collecting allChargeIDs upfront, you could useGetByIDs(...)for a single batch fetch, then loop through lines with a map lookup before callingPostLineAssignedToInvoiceper-line.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/service/lineengine.go` around lines 60 - 89, The current loop over input.Lines causes an N+1 by calling e.service.GetByID for each line; change to collect all ChargeIDs from input.Lines first, call a batched e.service.GetByIDs (requesting meta.ExpandRealizations) to fetch all charges at once, populate a chargesByID map from the batch result, then iterate input.Lines to look up charge := chargesByID[*stdLine.ChargeID] and proceed to call e.service.PostLineAssignedToInvoice and convertCreditRealizations as before; ensure you still validate missing ChargeID and preserve existing error wrapping and behavior when PostLineAssignedToInvoice returns an error.openmeter/billing/charges/flatfee/adapter/detailedline.go (1)
88-95: Small style inconsistency with the usage-based adapter around emptyChildUniqueReferenceID.Here you use
lo.Mapunconditionally on all lines, while the sibling usage-based adapter (openmeter/billing/charges/usagebased/adapter/detailedline.golines 104-110) useslo.FilterMapto skip empty strings. SinceDetailedLines.Validate()already callsline.Validate()on each line—which enforces non-emptyChildUniqueReferenceID—either approach works fine in practice. That said, the usage-based approach is more defensive. For consistency and clarity across the two adapters, consider aligning to the same pattern.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/flatfee/adapter/detailedline.go` around lines 88 - 95, Replace the unconditional lo.Map over lines with a defensive lo.FilterMap that skips empty ChildUniqueReferenceID values: build childRefsToKeep from flatfee.DetailedLine items by filtering out "" before mapping to ChildUniqueReferenceID, so deleteQuery.Where(dbchargeflatfeedetailedline.ChildUniqueReferenceIDNotIn(childRefsToKeep...)) receives only non-empty refs; this aligns the flatfee adapter (childRefsToKeep, lines, ChildUniqueReferenceID) with the usage-based adapter's pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/charges/flatfee/adapter/charge.go`:
- Around line 198-202: The current expand path maps over each flatfee.Charge and
calls tx.FetchDetailedLines per-charge causing N+1 DB queries; change this to
perform a single batched fetch by collecting all charge IDs from the returned
out slice and calling a new or existing batch helper (e.g.,
tx.FetchDetailedLinesBatch or extend tx.FetchDetailedLines to accept
[]flatfee.Charge or []ID) that issues one query returning detailed lines grouped
by charge ID, then merge the results back into each flatfee.Charge (preserve
order) instead of using slicesx.MapWithErr to call FetchDetailedLines for each
element; update signatures and tests accordingly to ensure one DB round-trip for
the expand path.
In `@openmeter/billing/charges/flatfee/charge.go`:
- Line 232: The DetailedLines field uses a non-pointer mo.Option[DetailedLines],
so omitempty won't omit the field when the Option is absent; change the struct
field type to *mo.Option[DetailedLines] (i.e., DetailedLines
*mo.Option[DetailedLines]) and ensure code sets it to nil when the expansion is
not present, or alternatively replace `omitempty` with `omitzero` if you verify
samber/mo's Option implements IsZero() in your dependency version; apply the
same change to the analogous Option field in usagebased/realizationrun.go.
In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Line 89: Replace the use of context.Background() with the test's cancellable
context by using s.T().Context(); specifically change the ctx variable
initialization (ctx := context.Background()) in the detailed line test to ctx :=
s.T().Context() so the test inherits cancellation/timeouts from the testing
framework (referencing the test suite receiver s and its T().Context() method).
---
Nitpick comments:
In `@openmeter/billing/charges/flatfee/adapter/detailedline_test.go`:
- Around line 145-177: Add assertions that the "keep" detailed line preserves
its DB ID and CreatedAt across the two UpsertDetailedLines calls: when you
create initialLines capture the ID and CreatedAt for the line whose
ChildUniqueReferenceID == "keep" (from the value returned by UpsertDetailedLines
or by fetching it after the first upsert via adapter.GetByID), then after the
replacement UpsertDetailedLines call fetch the charge (as you already do) and
assert that fetchedCharge.Realizations.DetailedLines.OrEmpty()[0].ID equals the
original ID and that its CreatedAt equals the original CreatedAt; this locks in
the SetIgnore(FieldID)/SetIgnore(FieldCreatedAt) behavior in the
UpsertDetailedLines conflict resolver.
In `@openmeter/billing/charges/flatfee/adapter/detailedline.go`:
- Around line 88-95: Replace the unconditional lo.Map over lines with a
defensive lo.FilterMap that skips empty ChildUniqueReferenceID values: build
childRefsToKeep from flatfee.DetailedLine items by filtering out "" before
mapping to ChildUniqueReferenceID, so
deleteQuery.Where(dbchargeflatfeedetailedline.ChildUniqueReferenceIDNotIn(childRefsToKeep...))
receives only non-empty refs; this aligns the flatfee adapter (childRefsToKeep,
lines, ChildUniqueReferenceID) with the usage-based adapter's pattern.
In `@openmeter/billing/charges/flatfee/service/helpers.go`:
- Around line 22-26: Add a brief clarifying comment above the
persistDetailedLines function to note the soft-delete/reconciliation semantics:
explain that s.adapter.UpsertDetailedLines will soft-delete any existing
detailed lines not present in the provided list, so passing an empty
line.DetailedLines will remove all persisted detailed lines for that charge;
reference persistDetailedLines, UpsertDetailedLines, and DetailedLines in the
comment so future readers understand the reconcile behavior without inspecting
the adapter.
In `@openmeter/billing/charges/flatfee/service/lineengine.go`:
- Around line 60-89: The current loop over input.Lines causes an N+1 by calling
e.service.GetByID for each line; change to collect all ChargeIDs from
input.Lines first, call a batched e.service.GetByIDs (requesting
meta.ExpandRealizations) to fetch all charges at once, populate a chargesByID
map from the batch result, then iterate input.Lines to look up charge :=
chargesByID[*stdLine.ChargeID] and proceed to call
e.service.PostLineAssignedToInvoice and convertCreditRealizations as before;
ensure you still validate missing ChargeID and preserve existing error wrapping
and behavior when PostLineAssignedToInvoice returns an error.
In `@openmeter/billing/charges/usagebased/adapter/charge.go`:
- Around line 158-165: GetByIDs is causing an N+1 when
input.Expands.Has(meta.ExpandDetailedLines) because the current
slicesx.MapWithErr loop calls tx.FetchDetailedLines(ctx, charge) per charge;
change this to a single batched fetch: collect all charge IDs in GetByIDs, call
a new tx.FetchDetailedLinesBatch(ctx, ids) (or overload FetchDetailedLines to
accept []ids) to load all detailed lines in one DB round-trip, then stitch the
returned lines back into the corresponding usagebased.Charge objects before
returning; update the call site where slicesx.MapWithErr and
tx.FetchDetailedLines are used so it uses the batched fetch and in-memory join
instead of per-charge DB calls.
In `@openmeter/billing/charges/usagebased/adapter/detailedline_test.go`:
- Around line 192-196: Add an assertion to verify the newly upserted detailed
line ("new@[2026-01-01T00:00:00Z..2026-02-01T00:00:00Z]") includes its
description (and optionally its expected quantity) so regressions that drop
descriptions on fresh upserts are detected; locate the test block that inspects
fetchedCharge.Realizations[0].DetailedLines.OrEmpty() and add an s.NotNil /
s.Equal check against DetailedLines.OrEmpty()[1].Description (and/or s.Equal on
DetailedLines.OrEmpty()[1].Quantity.InexactFloat64()) to confirm the "new"
line's description is present and correct.
- Around line 57-64: The defer call to migrator.CloseOrLogError() inside
SetupSuite closes the migrator as soon as SetupSuite returns (so it runs
immediately after migrator.Up()), which can be surprising; either replace the
defer with an explicit migrator.CloseOrLogError() immediately after calling
migrator.Up() inside SetupSuite, or move the defer (or a call) into your suite
teardown (e.g., TearDownSuite) so the migrator remains open for the lifetime of
the tests; update references to migrator, SetupSuite, migrator.Up(), and
migrator.CloseOrLogError() accordingly.
In `@openmeter/billing/charges/usagebased/adapter/detailedline.go`:
- Around line 65-102: Add a namespace-consistency guard at the start of
UpsertRunDetailedLines (after chargeID.Validate(), runID.Validate(),
lines.Validate()) that checks chargeID.Namespace vs runID.Namespace and returns
a clear error if they differ; use the existing symbols (chargeID.Namespace,
runID.Namespace) and return a fmt.Errorf or wrapped error indicating the
mismatch so the soft-delete and created line.Namespace cannot cross partitions
silently.
In `@openmeter/billing/charges/usagebased/service_test.go`:
- Around line 11-17: Update TestValidateExpands to a table-driven subtest style:
create a slice of cases (name, input meta.Expands, expected error boolean and
optionally expected error value/message), iterate cases and call
t.Run(case.name, func(t *testing.T){ t.Parallel(); if case.expectError {
require.ErrorIs(t, validateExpands(case.input), <expected error>) or
require.Error(t, validateExpands(case.input)) } else { require.NoError(t,
validateExpands(case.input)) } }); include a case for an empty meta.Expands{} to
lock in "no expands requested" behavior and use meta.ExpandRealizations and
meta.ExpandDetailedLines in the inputs; assert specific error type/message with
require.ErrorIs or a substring match where appropriate.
In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 216-221: The local assignment currentRun.DetailedLines =
mo.Some(runDetailedLines) is dead because it isn't propagated to
s.Charge.Realizations or read before RefetchCharge; either remove that
assignment entirely, or if you want symmetry with creditheninvoice.go, call
s.Charge.Realizations.SetRealizationRun(currentRun) after computing
runDetailedLines so the updated DetailedLines is stored in the charge
realizations; update the code around
PersistRunDetailedLines/UpdateRealizationRun accordingly.
In `@openmeter/billing/charges/usagebased/service/get.go`:
- Around line 111-175: Replace the manual semaphore/wg/errCh pattern with an
errgroup to simplify concurrency: create an errgroup via
errgroup.WithContext(ctx), call g.SetLimit(defaultMaxParallelRatingsPerRequest),
and for each charge use g.Go(func() error { ... }) to run the rating work
(invoke s.rater.GetTotalsForUsage) and return any error instead of pushing to
errCh; store results into ratingResults (keep sync.Map or switch to a map
guarded by a mutex) inside the goroutine; after the loop call g.Wait() and
return its error (or nil) — remove sem.Acquire/Release, wg, errCh, the post-loop
draining logic, and the manual error aggregation.
In `@openmeter/billing/charges/usagebased/service/run/create.go`:
- Around line 191-198: The code calls
updatedCharge.Realizations.SetRealizationRun(currentRun) twice (once inside a
conditional branch and again unconditionally), so remove the duplicate inside
the credit-allocation branch and keep only the single unconditional call;
consolidate the error handling to return CreateRatedRunResult{} with a single
generic fmt.Errorf("update realization run: %w", err) from the remaining
SetRealizationRun call to cover both credits and detailed lines, referencing
updatedCharge.Realizations.SetRealizationRun and CreateRatedRunResult.
In `@openmeter/billing/charges/usagebased/service/run/detailedline_test.go`:
- Around line 70-79: Add assertions that verify the mapper carries through the
item identity and numeric values: in the test using
mapRatingResultToRunDetailedLines (detailedline_test.go) add require.Equal
checks on out[0].ChildUniqueReferenceID, out[0].Name and the numeric fields
out[0].Quantity and out[0].PerUnitAmount (and/or TotalAmount if applicable) to
match the input rating result values used in the test; this ensures
mapRatingResultToRunDetailedLines preserves the
ChildUniqueReferenceID/name/quantity/per-unit amount mapping rather than
silently regressing.
In `@openmeter/billing/charges/usagebased/service/run/detailedline.go`:
- Around line 36-71: The mapRatingResultToRunDetailedLines function currently
accepts run usagebased.RealizationRun but never uses it; remove the unused run
parameter from mapRatingResultToRunDetailedLines (and update all callers, e.g.,
where PersistRunDetailedLines invokes it) OR if run-scoped data is required,
thread run into the mapping and populate a run-specific field on
usagebased.DetailedLine (for example RunID or RunTimestamp) so the mapped lines
reflect the run (update the function signature mapRatingResultToRunDetailedLines
and the return population of usagebased.DetailedLine accordingly, and adjust
PersistRunDetailedLines and any adapter calls that expect the new field).
In `@openmeter/billing/models/stddetailedline/create.go`:
- Around line 32-51: The Create function is passing line.DeletedAt through
without timezone normalization (via SetNillableDeletedAt), causing asymmetry
with the read-path which uses convert.TimePtrIn(..., time.UTC) in FromDB; update
Create (in create.go) to normalize DeletedAt to UTC before calling
SetNillableDeletedAt (e.g., apply the same conversion used in mapping.go/FromDB)
so persisted DeletedAt values are consistently in UTC.
In
`@tools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql`:
- Around line 1-12: Dropping and recreating the three unique indexes
(billingstdinvdetailedline_ns_parent_child_id on
billing_standard_invoice_detailed_lines, chargeffdetailedline_ns_charge_child_id
on charge_flat_fee_detailed_line, and
chargeubdetailedline_ns_charge_run_child_id on
charge_usage_based_run_detailed_line) will rebuild the indexes and can block
writes; change the migration to use a non-blocking expand/contract approach
(create the new UNIQUE INDEX CONCURRENTLY with the new predicate or a temporary
non-unique concurrent index, backfill/verify, then drop the old index and rename
the new one) or run CREATE INDEX CONCURRENTLY for the new index and then DROP
INDEX CONCURRENTLY for the old one, and document scheduling requirements so this
runs in a maintenance window if row counts are large.
🪄 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: 57dd8601-1486-47b8-814d-e11a7ecaa293
⛔ Files ignored due to path filters (2)
openmeter/ent/db/migrate/schema.gois excluded by!**/ent/db/**tools/migrate/migrations/atlas.sumis excluded by!**/*.sum,!**/*.sum
📒 Files selected for processing (53)
.agents/skills/charges/SKILL.mdapp/common/charges.goopenmeter/billing/adapter/stdinvoicelinemapper.goopenmeter/billing/adapter/stdinvoicelines.goopenmeter/billing/charges/flatfee/adapter.goopenmeter/billing/charges/flatfee/adapter/charge.goopenmeter/billing/charges/flatfee/adapter/detailedline.goopenmeter/billing/charges/flatfee/adapter/detailedline_test.goopenmeter/billing/charges/flatfee/adapter/mapper.goopenmeter/billing/charges/flatfee/charge.goopenmeter/billing/charges/flatfee/detailedline.goopenmeter/billing/charges/flatfee/service.goopenmeter/billing/charges/flatfee/service/helpers.goopenmeter/billing/charges/flatfee/service/invoice.goopenmeter/billing/charges/flatfee/service/lineengine.goopenmeter/billing/charges/flatfee/service/service.goopenmeter/billing/charges/meta/charge.goopenmeter/billing/charges/service/base_test.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/charges/usagebased/adapter.goopenmeter/billing/charges/usagebased/adapter/charge.goopenmeter/billing/charges/usagebased/adapter/detailedline.goopenmeter/billing/charges/usagebased/adapter/detailedline_test.goopenmeter/billing/charges/usagebased/detailedline.goopenmeter/billing/charges/usagebased/realizationrun.goopenmeter/billing/charges/usagebased/service.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/charges/usagebased/service/currenttotals.goopenmeter/billing/charges/usagebased/service/get.goopenmeter/billing/charges/usagebased/service/rating/details.goopenmeter/billing/charges/usagebased/service/rating/quantitysnapshot.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/rating/uniqueref.goopenmeter/billing/charges/usagebased/service/run/create.goopenmeter/billing/charges/usagebased/service/run/detailedline.goopenmeter/billing/charges/usagebased/service/run/detailedline_test.goopenmeter/billing/charges/usagebased/service/run/service.goopenmeter/billing/charges/usagebased/service/service.goopenmeter/billing/charges/usagebased/service/statemachine.goopenmeter/billing/charges/usagebased/service_test.goopenmeter/billing/models/stddetailedline/create.goopenmeter/billing/models/stddetailedline/mapping.goopenmeter/billing/models/stddetailedline/model.goopenmeter/ent/schema/billing.goopenmeter/ent/schema/chargesflatfee.goopenmeter/ent/schema/chargesusagebased.goopenmeter/ledger/customerbalance/testenv_test.gotools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.down.sqltools/migrate/migrations/20260422051837_simplify_mixin_detailed_line_partial_indexes.up.sql
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/charges/usagebased/service/rating/details.go (1)
16-57: Nice, clean input/result split — LGTM. 👍The
GetDetailedLinesForUsageInput.Validate()order is sensible (charge → customer → meter → offset → prior runs → detailed-lines expansion), and bundling the snapshotQuantityalongsideGenerateDetailedLinesResultinGetRatingForUsageResultgives callers everything they need for persistence without re-deriving it.Tiny optional nit: the result type is
GetRatingForUsageResultwhile the method isGetDetailedLinesForUsage— renaming toGetDetailedLinesForUsageResultwould make the pairing obvious at call sites. Totally up to you.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/charges/usagebased/service/rating/details.go` around lines 16 - 57, Rename the result struct GetRatingForUsageResult to GetDetailedLinesForUsageResult so it clearly pairs with the GetDetailedLinesForUsage method; update the type name wherever referenced (e.g., construction, return signatures, imports or tests) to use GetDetailedLinesForUsageResult and keep the embedded billingrating.GenerateDetailedLinesResult and Quantity alpacadecimal.Decimal fields unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/rating/details.go`:
- Around line 16-57: Rename the result struct GetRatingForUsageResult to
GetDetailedLinesForUsageResult so it clearly pairs with the
GetDetailedLinesForUsage method; update the type name wherever referenced (e.g.,
construction, return signatures, imports or tests) to use
GetDetailedLinesForUsageResult and keep the embedded
billingrating.GenerateDetailedLinesResult and Quantity alpacadecimal.Decimal
fields unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b0c1ece4-7a64-47f6-b4a3-b7d996871005
📒 Files selected for processing (1)
openmeter/billing/charges/usagebased/service/rating/details.go
Summary
This PR adds durable charge-side detailed-line persistence for usage-based realization runs and flat-fee realizations, and moves flat-fee line-engine ownership behind flatfee.Service to match the usage-based structure.
The main goal is to preserve the rated/billed detailed-line representation on the charge side, not only on invoice lines. That gives charge lifecycles a stable, queryable view of what was rated for a run or realization,
which is needed for future rerating, previous-run context, and expand-based read models.
Why
Today, charge lifecycles can rate or bill lines transiently, but the detailed-line output is not consistently persisted as part of the charge aggregate. That creates a few problems:
This change addresses those by making detailed lines first-class persisted charge data and by pushing line-engine ownership back into the charge services.
Why This Shape
A few design choices were intentional:
Summary by CodeRabbit
New Features
Bug Fixes
Tests