Skip to content

feat: credit then invoice delete - #4327

Merged
turip merged 2 commits into
mainfrom
chore/credit-then-invoice-delete
May 8, 2026
Merged

turip merged 2 commits into
mainfrom
chore/credit-then-invoice-delete

Conversation

@turip

@turip turip commented May 8, 2026 •

Copy link
Copy Markdown
Member

Overview

Add support for deleting charges via the charge delete hook.

Notes for reviewer

Summary by CodeRabbit

  • New Features

    • Charge deletion now automatically removes related invoice gathering lines and consolidates invoice updates so deletions correctly clean up invoices.
    • Usage-based charges support soft-deleting realization runs and preserve correct credit handling when removing charges.
  • Behavior Changes

    • Charge patching now returns both updated charge and any invoice updates so invoice changes are applied atomically.
  • Tests

    • Expanded test suite covering deletion scenarios, ledger balances, and realization-run behavior.
  • Documentation

    • Clarified timestamp normalization for deletion timestamps.

@coderabbitai

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

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: 50374af7-4ba1-41f9-8736-8943aeabb0f9

📥 Commits

Reviewing files that changed from the base of the PR and between 2291455 and 205a245.

📒 Files selected for processing (6)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • test/credits/suite_test.go
✅ Files skipped from review due to trivial changes (2)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/usagebased/realizationrun_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • test/credits/suite_test.go
  • openmeter/billing/charges/usagebased/realizationrun.go

📝 Walkthrough

Walkthrough

This PR adds a generic TriggerPatchResult to pair charges with invoice patches, threads slog.Logger into charges service construction, records and drains invoice patches from state machines, resolves delete-by-charge-id patch ops into concrete invoice-line deletions, supports realization-run soft-deletes and filtering, and implements delete-patch behaviors with tests.

Changes

Charge Deletion with Invoice Patch Tracking

Layer / File(s) Summary
Result type & Patch model
openmeter/billing/charges/meta/patch.go, openmeter/billing/charges/invoiceupdater/patch.go
Introduces TriggerPatchResult[T]; adds delete_gathering_line_by_charge_id patch op, payload struct, accessor, constructor, and logging.
State machine patch APIs
openmeter/billing/charges/statemachine/machine.go
Adds internal invoicePatches slice and Machine methods AddInvoicePatch, InvoicePatches, DrainInvoicePatches; extends StateMachine interface.
Service & helper interface updates
openmeter/billing/charges/flatfee/service.go, openmeter/billing/charges/usagebased/service.go, openmeter/billing/charges/service/helpers.go
Update TriggerPatch signatures to return meta.TriggerPatchResult[...] and add local alias TriggerPatchResult.
TriggerPatch implementations
openmeter/billing/charges/flatfee/service/triggers.go, openmeter/billing/charges/usagebased/service/triggers.go, openmeter/billing/charges/service/helpers.go
Refactor trigger handlers to return structured TriggerPatchResult, drain invoice patches from state machine, and forward them via invocable wrappers.
Invoice patch batching & application
openmeter/billing/charges/service/patch.go
Collect InvoicePatches from invocable TriggerPatch calls and apply them in a single s.invoiceUpdater.ApplyPatches() call.
Invoice updater parse & resolve
openmeter/billing/charges/invoiceupdater/invoiceupdate.go
Parse delete_gathering_line_by_charge_id patches to collect ChargeIDs, recognize op in dry-run logs, and resolve ChargeIDs into per-invoice deleted line IDs before applying updates.
Service init & logger wiring
app/common/charges.go, openmeter/billing/charges/service/service.go, openmeter/billing/charges/testutils/service.go, openmeter/billing/charges/service/base_test.go
Thread *slog.Logger into NewChargesService and charges Config, require Logger in Config, add invoiceUpdater field and initialize it with invoiceupdater.New(..., Logger), update tests to provide slog.Default().
Realization run model & helpers
openmeter/billing/charges/usagebased/realizationrun.go, openmeter/billing/charges/usagebased/realizationrun_test.go
Add optional DeletedAt to UpdateRealizationRunInput with validation and add RealizationRuns.GetByLineID plus tests.
Realization run persistence & adapter filtering
openmeter/billing/charges/usagebased/adapter/realizationrun.go, openmeter/billing/charges/usagebased/adapter/charge.go, openmeter/billing/charges/usagebased/adapter/detailedline_test.go
Normalize input during updates, persist DeletedAt when present, and add DeletedAtIsNil() filter in expandRealizations; add test verifying deleted runs excluded.
Mutable standard line deletion & credit correction
openmeter/billing/charges/usagebased/service/lineengine.go, openmeter/billing/charges/usagebased/service/creditheninvoice.go
Implement OnMutableStandardLinesDeleted to correct credits and soft-delete realization runs; update DeleteCharge to enqueue invoice patches deleting gathering/invoice lines before adapter deletion.
Test suite reorg & delete-patch tests
test/credits/sanity_test.go, test/credits/suite_test.go, test/credits/credit_then_invoice_test.go
Move suite scaffolding into suite_test.go, update imports in sanity_test.go, and add three delete-patch tests covering pending gathering lines, mutable standard lines (credit corrections), and immutable standard lines (preserved ledger) with ledger snapshot helpers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% 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 'feat: credit then invoice delete' clearly and concisely summarizes the main feature: adding support for deleting charges via the charge delete hook, which aligns with the changeset's primary objective.
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 chore/credit-then-invoice-delete

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 chore/credit-then-invoice-delete branch from d477e34 to 47ab99e Compare May 8, 2026 13:22
@turip
turip force-pushed the chore/lineengine-mutable-line-delete-hook branch from 66ba7d0 to 36daa87 Compare May 8, 2026 13:23
Base automatically changed from chore/lineengine-mutable-line-delete-hook to main May 8, 2026 14:30
@turip
turip force-pushed the chore/credit-then-invoice-delete branch from 47ab99e to 2291455 Compare May 8, 2026 15:12
@turip
turip marked this pull request as ready for review May 8, 2026 15:13
@turip
turip requested a review from a team as a code owner May 8, 2026 15:13
@turip turip added area/billing release-note/feature Release note: Exciting New Features labels May 8, 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 (9)
openmeter/billing/charges/usagebased/service/lineengine.go (3)

343-353: ⚡ Quick win

ExpandDetailedLines looks like over-fetching here.

The deletion loop only consumes charge.Realizations (for GetByLineID, payment/usage checks, currency, run ID) and never touches DetailedLines. Including meta.ExpandDetailedLines will fan out an extra query per realization and materialize potentially large rows that aren't used. Dropping it should keep behavior identical and trim DB work on hot deletion paths.

♻️ Suggested tweak
 	charges, err := e.service.GetByIDs(ctx, usagebased.GetByIDsInput{
 		Namespace: input.Invoice.Namespace,
 		IDs:       chargeIDs,
-		Expands: meta.Expands{
-			meta.ExpandRealizations,
-			meta.ExpandDetailedLines,
-		},
+		Expands: meta.Expands{
+			meta.ExpandRealizations,
+		},
 	})

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 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/lineengine.go` around lines 343
- 353, The call to e.service.GetByIDs in lineengine.go is over-fetching by
including meta.ExpandDetailedLines even though the deletion logic only uses
charge.Realizations; remove meta.ExpandDetailedLines from the Expands slice in
the usagebased.GetByIDsInput so only meta.ExpandRealizations is requested (keep
the Namespace and IDs as-is) to avoid the extra per-realization queries and
large materialized rows during deletion.

322-358: 💤 Low value

Helper reads cleanly — small readability nit.

getChargesForMutableStandardLineDelete does dedup + validation + batch fetch nicely. Tiny nit: since seenChargeIDs already records membership, you can drop the parallel chargeIDs slice and derive it via lo.Keys(seenChargeIDs) at the end (or use slicesx/sorted form if order matters). Not a blocker — current form is also perfectly readable.

🤖 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/lineengine.go` around lines 322
- 358, The function getChargesForMutableStandardLineDelete currently builds both
seenChargeIDs and a parallel chargeIDs slice; remove the redundant chargeIDs
accumulation and instead derive the ID list from seenChargeIDs before calling
e.service.GetByIDs (e.g., use lo.Keys(seenChargeIDs) or an equivalent to produce
the []string), keeping the same Namespace and Expands passed to GetByIDs and
preserving any ordering choice if required; update references to chargeIDs
accordingly so GetByIDs receives the derived slice.

234-290: ⚡ Quick win

Use a single now for AllocateAt and DeletedAt.

clock.Now() is called twice (line 275 and 281), so the credit correction's AllocateAt and the realization run's DeletedAt can drift apart by a few microseconds. Capturing one timestamp at the top of the loop iteration (or once at the top of the function) keeps the two semantically aligned and slightly easier to reason about during incident triage.

♻️ Suggested tweak
 	for _, stdLine := range input.Lines {
 		charge, ok := chargesByID[*stdLine.ChargeID]
@@
+		now := clock.Now()
+
 		if _, err := e.service.runs.CorrectAllCredits(ctx, usagebasedrun.CorrectAllCreditRealizationsInput{
 			Charge:             charge,
 			Run:                run,
-			AllocateAt:         clock.Now(),
+			AllocateAt:         now,
 			CurrencyCalculator: currencyCalculator,
 		}); err != nil {
 			return fmt.Errorf("correcting credits for deleted usage based standard line[%s] run[%s]: %w", stdLine.ID, run.ID.ID, err)
 		}
 
-		charge, err = e.markMutableStandardLineRunDeleted(ctx, charge, run, clock.Now())
+		charge, err = e.markMutableStandardLineRunDeleted(ctx, charge, run, now)
🤖 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/lineengine.go` around lines 234
- 290, The loop in OnMutableStandardLinesDeleted calls clock.Now() twice causing
AllocateAt and DeletedAt to differ; fix by capturing a single timestamp (e.g.,
now := clock.Now()) at the start of each iteration (or once before the loop) and
use that single now value for usagebasedrun.CorrectAllCredits's AllocateAt and
for markMutableStandardLineRunDeleted's DeletedAt, replacing both clock.Now()
calls so both operations share the same timestamp.
test/credits/suite_test.go (1)

68-99: 💤 Low value

Tiny readability win: extract the repeated ResolverDependencies.

The same transactions.ResolverDependencies{AccountService: deps.ResolversService, AccountCatalog: deps.AccountService, BalanceQuerier: deps.HistoricalLedger} literal is built three times (recognizer, collector, flat-fee/usage-based handlers). Pulling it into a local variable shortens those lines and makes future signature changes a one-liner.

♻️ Suggested tweak
+	resolverDeps := transactions.ResolverDependencies{
+		AccountService: deps.ResolversService,
+		AccountCatalog: deps.AccountService,
+		BalanceQuerier: deps.HistoricalLedger,
+	}
+
 	revenueRecognizer, err := recognizer.NewService(recognizer.Config{
 		Ledger:             deps.HistoricalLedger,
-		Dependencies:       transactions.ResolverDependencies{
-			AccountService: deps.ResolversService,
-			AccountCatalog: deps.AccountService,
-			BalanceQuerier: deps.HistoricalLedger,
-		},
+		Dependencies:       resolverDeps,
 		Lineage:            lineageService,
 		TransactionManager: enttx.NewCreator(s.DBClient),
 	})
@@
-	collectorService := ledgercollector.NewService(ledgercollector.Config{
-		Ledger: deps.HistoricalLedger,
-		Dependencies: transactions.ResolverDependencies{
-			AccountService: deps.ResolversService,
-			AccountCatalog: deps.AccountService,
-			BalanceQuerier: deps.HistoricalLedger,
-		},
-	})
+	collectorService := ledgercollector.NewService(ledgercollector.Config{
+		Ledger:       deps.HistoricalLedger,
+		Dependencies: resolverDeps,
+	})
@@
-		FlatFeeHandler:        ledgerchargeadapter.NewFlatFeeHandler(deps.HistoricalLedger, transactions.ResolverDependencies{AccountService: deps.ResolversService, AccountCatalog: deps.AccountService, BalanceQuerier: deps.HistoricalLedger}, collectorService),
+		FlatFeeHandler:        ledgerchargeadapter.NewFlatFeeHandler(deps.HistoricalLedger, resolverDeps, collectorService),
 		CreditPurchaseHandler: ledgerchargeadapter.NewCreditPurchaseHandler(deps.HistoricalLedger, deps.HistoricalLedger, deps.ResolversService, deps.AccountService),
-		UsageBasedHandler:     ledgerchargeadapter.NewUsageBasedHandler(deps.HistoricalLedger, transactions.ResolverDependencies{AccountService: deps.ResolversService, AccountCatalog: deps.AccountService, BalanceQuerier: deps.HistoricalLedger}, collectorService),
+		UsageBasedHandler:     ledgerchargeadapter.NewUsageBasedHandler(deps.HistoricalLedger, resolverDeps, collectorService),
🤖 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/credits/suite_test.go` around lines 68 - 99, Extract the repeated
transactions.ResolverDependencies literal into a local variable (e.g.,
resolverDeps) and use it when constructing recognizer.NewService,
ledgercollector.NewService, and the ledgerchargeadapter.NewFlatFeeHandler /
NewUsageBasedHandler calls; replace each inline
transactions.ResolverDependencies{AccountService: deps.ResolversService,
AccountCatalog: deps.AccountService, BalanceQuerier: deps.HistoricalLedger} with
resolverDeps so future signature changes are one-line and the calls in
recognizer.NewService, ledgercollector.NewService, and the ledgerchargeadapter
constructors are shorter and consistent.
openmeter/billing/charges/usagebased/realizationrun_test.go (1)

93-118: 💤 Low value

Solid coverage on the happy and not-found paths.

One small thing you could optionally add: a run with LineID: nil mixed in to explicitly assert the nil-guard inside GetByLineID (run.LineID != nil). Today the nil branch isn't directly exercised, and a regression there would silently dereference a nil pointer.

♻️ Optional extra case
 	runs := RealizationRuns{
+		{
+			RealizationRunBase: RealizationRunBase{
+				ID:     RealizationRunID{Namespace: "namespace", ID: "run-without-line"},
+				LineID: nil,
+			},
+		},
 		{
 			RealizationRunBase: RealizationRunBase{
 				ID:     RealizationRunID{Namespace: "namespace", ID: "run-1"},
 				LineID: &otherLineID,
 			},
 		},
🤖 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/realizationrun_test.go` around lines 93
- 118, Add a third test case entry in TestRealizationRuns_GetByLineID: insert a
RealizationRun whose RealizationRunBase has LineID set to nil (explicitly omit
or set to nil) into the runs slice before calling runs.GetByLineID; this will
exercise the nil-guard inside RealizationRuns.GetByLineID and you should keep
the same assertions (finding "run-2" for line-1 and the "realization run not
found" error for "missing-line") to ensure the nil LineID does not cause a panic
or change behavior.
openmeter/billing/charges/usagebased/adapter/realizationrun.go (1)

49-66: 💤 Low value

Clean refactor — normalization moved up and DeletedAt plumbed through cleanly.

Pulling input = input.Normalized() to the top removes the per-call meta.NormalizeTimestamp(...) wrapping at the SetStoredAtLt site. Just one small consistency note: UpdateRealizationRunInput.Normalized() only normalizes StoredAtLT, so DeletedAt will be persisted with whatever precision the caller passed in (typically clock.Now()). If your DB column relies on the normalized precision elsewhere in the code path, consider normalizing DeletedAt too. Otherwise this is fine as-is.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openmeter/billing/charges/usagebased/adapter/realizationrun.go` around lines
49 - 66, UpdateRealizationRun moves input = input.Normalized() which only
normalizes StoredAtLT, so DeletedAt may be stored with caller precision; fix by
normalizing DeletedAt as well — either update
UpdateRealizationRunInput.Normalized() to normalize DeletedAt (preferred) or
call meta.NormalizeTimestamp/appropriate normalizer on input.DeletedAt before
calling SetOrClearDeletedAt in UpdateRealizationRun; reference
UpdateRealizationRun, UpdateRealizationRunInput.Normalized, DeletedAt,
StoredAtLT, SetOrClearDeletedAt and SetStoredAtLt when making the change.
openmeter/billing/charges/usagebased/realizationrun.go (1)

361-370: 💤 Low value

GetByLineID returns the first match — worth a quick sanity check.

lo.Find returns the first run whose LineID matches. If invariant-wise a LineID always maps to at most one realization run (which seems to be the case given how OnStandardInvoiceCreated creates a single current run per line), this is perfect. If there's any chance a LineID could be referenced by more than one run (e.g., a corrected/superseded run plus a current one), the caller in lineengine.go#OnMutableStandardLinesDeleted would silently operate on whichever happens to come first.

If the one-run-per-line invariant holds, feel free to ignore — possibly worth a short comment on the function to capture the assumption.

🤖 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/realizationrun.go` around lines 361 -
370, GetByLineID currently returns the first match found which can silently pick
between multiple runs for the same LineID; update RealizationRuns.GetByLineID to
collect all matches (e.g., via lo.Filter or equivalent), then: if zero matches
return the existing "not found" error, if exactly one return it, and if more
than one return an explicit error stating multiple realization runs found for
the LineID (so callers like OnMutableStandardLinesDeleted must not silently
operate on an arbitrary run); reference RealizationRuns.GetByLineID,
RealizationRun, OnStandardInvoiceCreated and OnMutableStandardLinesDeleted when
making this change (or alternatively add a concise comment above GetByLineID
documenting the one-run-per-line invariant if you prefer to keep current
behavior).
openmeter/billing/charges/invoiceupdater/invoiceupdate.go (1)

136-166: 💤 Low value

isDryRunLoggablePatch silently handles the new op via default

The new PatchOpDeleteGatheringLineByChargeID falls through to default: return true, so it'll always be logged in dry-run mode. That's the safe choice, but making it explicit keeps the function honest about what each op does:

✨ Suggested explicit case
 	case PatchOpLineUpdate:
 		updatePatch, err := patch.AsUpdateLinePatch()
 		if err != nil {
 			return true
 		}
 
 		return isMutableInvoice(updatePatch.TargetState.GetInvoiceID(), invoicesByID)
+	case PatchOpDeleteGatheringLineByChargeID:
+		// Always log charge-level deletes in dry-run output.
+		return true
 	default:
 		return true
 	}
🤖 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/invoiceupdater/invoiceupdate.go` around lines 136 -
166, isDryRunLoggablePatch currently falls into the default branch for the new
PatchOpDeleteGatheringLineByChargeID, so add an explicit case for
PatchOpDeleteGatheringLineByChargeID inside isDryRunLoggablePatch and return the
intended boolean (e.g., true to always log in dry-run like the safe default) to
make the behavior explicit; reference the PatchOpDeleteGatheringLineByChargeID
symbol and update the switch in isDryRunLoggablePatch accordingly.
test/credits/credit_then_invoice_test.go (1)

560-1033: ⚡ Quick win

Missing test case: delete a charge mid-way through progressive billing (partial paid + in-progress)

The three scenarios cover gathering-only, mutable-draft, and immutable-approved — great coverage for the single-run cases. But DeleteCharge iterates over all realization runs and emits a NewDeleteLinePatch for each one with LineID/InvoiceID. The multi-run progressive billing scenario (e.g., one finalized+paid run making the line immutable, plus a currently-in-progress run making its line mutable) isn't covered yet.

That case would exercise both the warning path (immutable line survives) and the deletion path (mutable line gets soft-deleted) in a single mustRefundCharge call, which is the most realistic "cancelled subscription mid-billing-cycle" scenario.

Worth adding to validate that the patch accumulation loop in DeleteCharge handles the mix correctly.

🤖 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/credits/credit_then_invoice_test.go` around lines 560 - 1033, Add a new
test that covers a progressive multi-run scenario where one realization run is
finalized/approved (immutable) and another run is in-progress/draft (mutable);
use the same helpers as other tests (createMockChargeIntent,
MockStreamingConnector.AddSimpleEvent, BillingService.InvoicePendingLines,
AdvanceInvoice, ApproveInvoice) to produce two runs for the same usage-based
charge, then call mustRefundCharge to trigger DeleteCharge; assert that the
immutable run's line remains undeleted and produces a ValidationIssue warning
(as checked in
TestUsageBasedCreditThenInvoiceDeletePatchKeepsImmutableStandardLineAndLedgerBookings)
while the mutable run's line is soft-deleted and its realization run DeletedAt
is set (as in
TestUsageBasedCreditThenInvoiceDeletePatchDeletesMutableStandardLineAndCorrectsCredits),
and finally verify ledger snapshots only reverse the mutable run's credit
allocations using the existing snapshot/assert helpers.
🤖 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 `@test/credits/suite_test.go`:
- Around line 45-101: In SetupSuite replace the non-fatal assertions with fatal
ones so setup stops on error: for each call where you currently use
s.NoError(err) after ledgertestutils.InitDeps, lineageadapter.New,
lineageservice.New, recognizer.NewService, and chargestestutils.NewServices,
change to s.Require().NoError(err) to immediately abort the suite on setup
failures and avoid dereferencing partially-initialized state (refer to the
SetupSuite method and those function calls).

---

Nitpick comments:
In `@openmeter/billing/charges/invoiceupdater/invoiceupdate.go`:
- Around line 136-166: isDryRunLoggablePatch currently falls into the default
branch for the new PatchOpDeleteGatheringLineByChargeID, so add an explicit case
for PatchOpDeleteGatheringLineByChargeID inside isDryRunLoggablePatch and return
the intended boolean (e.g., true to always log in dry-run like the safe default)
to make the behavior explicit; reference the
PatchOpDeleteGatheringLineByChargeID symbol and update the switch in
isDryRunLoggablePatch accordingly.

In `@openmeter/billing/charges/usagebased/adapter/realizationrun.go`:
- Around line 49-66: UpdateRealizationRun moves input = input.Normalized() which
only normalizes StoredAtLT, so DeletedAt may be stored with caller precision;
fix by normalizing DeletedAt as well — either update
UpdateRealizationRunInput.Normalized() to normalize DeletedAt (preferred) or
call meta.NormalizeTimestamp/appropriate normalizer on input.DeletedAt before
calling SetOrClearDeletedAt in UpdateRealizationRun; reference
UpdateRealizationRun, UpdateRealizationRunInput.Normalized, DeletedAt,
StoredAtLT, SetOrClearDeletedAt and SetStoredAtLt when making the change.

In `@openmeter/billing/charges/usagebased/realizationrun_test.go`:
- Around line 93-118: Add a third test case entry in
TestRealizationRuns_GetByLineID: insert a RealizationRun whose
RealizationRunBase has LineID set to nil (explicitly omit or set to nil) into
the runs slice before calling runs.GetByLineID; this will exercise the nil-guard
inside RealizationRuns.GetByLineID and you should keep the same assertions
(finding "run-2" for line-1 and the "realization run not found" error for
"missing-line") to ensure the nil LineID does not cause a panic or change
behavior.

In `@openmeter/billing/charges/usagebased/realizationrun.go`:
- Around line 361-370: GetByLineID currently returns the first match found which
can silently pick between multiple runs for the same LineID; update
RealizationRuns.GetByLineID to collect all matches (e.g., via lo.Filter or
equivalent), then: if zero matches return the existing "not found" error, if
exactly one return it, and if more than one return an explicit error stating
multiple realization runs found for the LineID (so callers like
OnMutableStandardLinesDeleted must not silently operate on an arbitrary run);
reference RealizationRuns.GetByLineID, RealizationRun, OnStandardInvoiceCreated
and OnMutableStandardLinesDeleted when making this change (or alternatively add
a concise comment above GetByLineID documenting the one-run-per-line invariant
if you prefer to keep current behavior).

In `@openmeter/billing/charges/usagebased/service/lineengine.go`:
- Around line 343-353: The call to e.service.GetByIDs in lineengine.go is
over-fetching by including meta.ExpandDetailedLines even though the deletion
logic only uses charge.Realizations; remove meta.ExpandDetailedLines from the
Expands slice in the usagebased.GetByIDsInput so only meta.ExpandRealizations is
requested (keep the Namespace and IDs as-is) to avoid the extra per-realization
queries and large materialized rows during deletion.
- Around line 322-358: The function getChargesForMutableStandardLineDelete
currently builds both seenChargeIDs and a parallel chargeIDs slice; remove the
redundant chargeIDs accumulation and instead derive the ID list from
seenChargeIDs before calling e.service.GetByIDs (e.g., use
lo.Keys(seenChargeIDs) or an equivalent to produce the []string), keeping the
same Namespace and Expands passed to GetByIDs and preserving any ordering choice
if required; update references to chargeIDs accordingly so GetByIDs receives the
derived slice.
- Around line 234-290: The loop in OnMutableStandardLinesDeleted calls
clock.Now() twice causing AllocateAt and DeletedAt to differ; fix by capturing a
single timestamp (e.g., now := clock.Now()) at the start of each iteration (or
once before the loop) and use that single now value for
usagebasedrun.CorrectAllCredits's AllocateAt and for
markMutableStandardLineRunDeleted's DeletedAt, replacing both clock.Now() calls
so both operations share the same timestamp.

In `@test/credits/credit_then_invoice_test.go`:
- Around line 560-1033: Add a new test that covers a progressive multi-run
scenario where one realization run is finalized/approved (immutable) and another
run is in-progress/draft (mutable); use the same helpers as other tests
(createMockChargeIntent, MockStreamingConnector.AddSimpleEvent,
BillingService.InvoicePendingLines, AdvanceInvoice, ApproveInvoice) to produce
two runs for the same usage-based charge, then call mustRefundCharge to trigger
DeleteCharge; assert that the immutable run's line remains undeleted and
produces a ValidationIssue warning (as checked in
TestUsageBasedCreditThenInvoiceDeletePatchKeepsImmutableStandardLineAndLedgerBookings)
while the mutable run's line is soft-deleted and its realization run DeletedAt
is set (as in
TestUsageBasedCreditThenInvoiceDeletePatchDeletesMutableStandardLineAndCorrectsCredits),
and finally verify ledger snapshots only reverse the mutable run's credit
allocations using the existing snapshot/assert helpers.

In `@test/credits/suite_test.go`:
- Around line 68-99: Extract the repeated transactions.ResolverDependencies
literal into a local variable (e.g., resolverDeps) and use it when constructing
recognizer.NewService, ledgercollector.NewService, and the
ledgerchargeadapter.NewFlatFeeHandler / NewUsageBasedHandler calls; replace each
inline transactions.ResolverDependencies{AccountService: deps.ResolversService,
AccountCatalog: deps.AccountService, BalanceQuerier: deps.HistoricalLedger} with
resolverDeps so future signature changes are one-line and the calls in
recognizer.NewService, ledgercollector.NewService, and the ledgerchargeadapter
constructors are shorter and consistent.
🪄 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: 089c4330-7d36-46db-8bc3-71e8d768eec9

📥 Commits

Reviewing files that changed from the base of the PR and between 9f2e9e8 and 2291455.

📒 Files selected for processing (24)
  • app/common/charges.go
  • openmeter/billing/charges/flatfee/service.go
  • openmeter/billing/charges/flatfee/service/triggers.go
  • openmeter/billing/charges/invoiceupdater/invoiceupdate.go
  • openmeter/billing/charges/invoiceupdater/patch.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/service/base_test.go
  • openmeter/billing/charges/service/helpers.go
  • openmeter/billing/charges/service/patch.go
  • openmeter/billing/charges/service/service.go
  • openmeter/billing/charges/statemachine/machine.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/detailedline_test.go
  • openmeter/billing/charges/usagebased/adapter/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/triggers.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/sanity_test.go
  • test/credits/suite_test.go
💤 Files with no reviewable changes (1)
  • test/credits/sanity_test.go

Comment thread test/credits/suite_test.go Resolved
@turip
turip enabled auto-merge (squash) May 8, 2026 15:54

This branch was previously deployed

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

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants