Skip to content

feat: support usage-based gathering line deletes - #4663

Merged
turip merged 1 commit into
mainfrom
feat/gathering-line-delete
Jul 8, 2026
Merged

turip merged 1 commit into
mainfrom
feat/gathering-line-delete

Conversation

@turip

@turip turip commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Summary

Add a usage-based shrink-to-realized-period patch for manual gathering line deletion.

Rules:

  • Deleting a gathering line belonging to a charge without any realization is treated as an override on the charge with the intent to delete the charge.
  • Deleteing a gathering line with a charge having realizations is treated as the service period is intended to be only covering the already billed items.

Summary by CodeRabbit

  • New Features

    • Added a “shrink to realized period” operation for charge service periods, including new trigger support and validation of intent timing.
    • Enhanced credit-then-invoice and usage-based credit-only flows to recognize and apply shrink-to-realized transitions.
  • Bug Fixes

    • Improved invoice line and charge edit lifecycle so validation runs before mutation and validation is non-mutating.
    • Fixed manual deletion behavior for gathering invoice lines to shrink charges or delete as appropriate while preserving billing history.
  • Tests / Docs

    • Added coverage for shrink behavior, gathering deletions, and realization selection; clarified RealizationRuns.Latest() semantics.

Greptile Summary

This PR adds usage-based gathering-line delete handling. The main changes are:

  • A new shrink-to-realized-period patch and trigger.
  • Gathering-line deletes mapped to charge delete or realized-period shrink.
  • Usage-based state-machine updates for preserving realized invoice history.
  • Intent mutation callbacks updated to return validation errors.

Confidence Score: 4/5

This is close, but the validation gap should be fixed before merging.

  • Gathering-line delete validation can still pass edits that the mutation path rejects.
  • The failure happens after the billing edit has moved past its preflight check.
  • The new shrink-to-realized-period state-machine path otherwise has focused checks for realized-run boundaries.

openmeter/billing/charges/usagebased/service/lineengine.go

Important Files Changed

Filename Overview
openmeter/billing/charges/usagebased/service/lineengine.go Adds usage-based gathering-line delete handling, but the validation hook still accepts edits that the mutation path can reject.
openmeter/billing/charges/usagebased/service/creditheninvoice.go Adds shrink-to-realized-period state-machine handling for realized usage history.
openmeter/billing/charges/meta/patchshrinktorealizedperiod.go Introduces the API-only shrink-to-realized-period patch type.

Fix All in Claude Code Fix All in Codex

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
openmeter/billing/charges/usagebased/service/lineengine.go:405-406
**Validation Still Bypassed**

This branch still accepts gathering-line deletes that the mutation path can reject. When the charge has existing realizations, the later callback fires `ShrinkToRealizedPeriod`, which rejects unsupported states such as `active.realization.issuing` and `deleted`, and also rejects when the deleted gathering line starts somewhere other than the latest non-voided run boundary. With no realizations, an already-deleted charge also cannot fire the delete trigger. Billing runs this validation before applying the edit, so callers can still pass the edit check and fail only during `OnMutableInvoiceLinesEditedViaAPI`. The validation hook needs to reject the same unsupported states and known boundary mismatches before mutation starts.

Reviews (3): Last reviewed commit: "feat(billing): support usage-based gathe..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used:

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a new API-facing shrink-to-realized-period patch for usage-based charges, makes intent mutations error-aware, wires the new behavior into credit-then-invoice and credits-only flows, updates gathering-line delete handling, and refreshes the related docs and tests.

Changes

Shrink-to-realized-period feature

Layer / File(s) Summary
Patch type and contract
openmeter/billing/charges/meta/patch.go, openmeter/billing/charges/meta/triggers.go, openmeter/billing/charges/meta/patchshrinktorealizedperiod.go, openmeter/billing/charges/meta/patch_target_test.go
Adds PatchTypeShrinkToRealizedPeriod, TriggerShrinkToRealizedPeriod, and the PatchShrinkToRealizedPeriod contract with validation and target-layer tests.
Error-aware intent mutation callbacks
openmeter/billing/charges/usagebased/charge.go, openmeter/billing/charges/usagebased/service/statemachine.go, openmeter/billing/charges/usagebased/adapter/charge.go, openmeter/billing/charges/usagebased/adapter/intentoverride_test.go, openmeter/billing/charges/usagebased/service/rating/service_test.go
Updates intent mutation callbacks to return errors and adjusts the main call sites and tests to use the new contract.
Credits-only shrink/delete flow update
openmeter/billing/charges/usagebased/service/creditsonly.go
Moves period-patch validation and mutation into the error-returning intent mutator for credits-only charges.
Credit-then-invoice state machine shrink handling
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditheninvoice_test.go, openmeter/billing/charges/usagebased/realizationrun.go, openmeter/billing/charges/usagebased/realizationrun_test.go
Adds shrink-to-realized-period handling, new state transitions, realization-run lookup helpers, and coverage for the latest-run selection behavior.
API gathering-line delete routing
openmeter/billing/charges/usagebased/service/lineengine.go
Routes gathering-line API deletes to either a shrink patch or a delete/refund patch based on realization history.
End-to-end subscription sync tests
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
Adds integration coverage for gathering-line deletion, shrink, and finalization flows during subscription sync.
Documentation
.agents/skills/charges/SKILL.md
Updates charge-engine guidance, shrink semantics, state naming, and realization-run notes.
Estimated code review effort: 4 (Complex) ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LineEngine
  participant CreditThenInvoiceStateMachine
  participant RealizationRuns
  participant IntentLayer

  LineEngine->>CreditThenInvoiceStateMachine: ShrinkToRealizedPeriod(patch)
  CreditThenInvoiceStateMachine->>RealizationRuns: WithoutVoidedBillingHistory().Latest()
  RealizationRuns-->>CreditThenInvoiceStateMachine: latest realization run
  CreditThenInvoiceStateMachine->>CreditThenInvoiceStateMachine: ValidateWith(intent)
  CreditThenInvoiceStateMachine->>IntentLayer: mutateIntentLayer(ctx, editFn)
  IntentLayer-->>CreditThenInvoiceStateMachine: updated ServicePeriod.To
  CreditThenInvoiceStateMachine-->>LineEngine: delete gathering line patch
Loading

Possibly related PRs

  • openmeterio/openmeter#4053: Shares the usage-based intent mutation callback changes used here in DeleteCharge and related mutation paths.
  • openmeterio/openmeter#4339: Covers the same credit-then-invoice shrink and realization-history flow that this PR extends with shrink-to-realized-period handling.
  • openmeterio/openmeter#4656: Related to the mutable invoice line validation and delete flow that this PR hooks into for gathering-line API deletes.

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

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding support for deleting usage-based gathering lines.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/gathering-line-delete

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.

@turip
turip force-pushed the feat/gathering-line-delete branch from 394cdb5 to 86c28df Compare July 8, 2026 10:55
@turip
turip changed the base branch from main to feat/usagebased-paid-trigger-cleanup July 8, 2026 10:55
@turip
turip marked this pull request as ready for review July 8, 2026 10:56
@turip
turip requested a review from a team as a code owner July 8, 2026 10:56
@turip

turip commented Jul 8, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Jul 8, 2026
Base automatically changed from feat/usagebased-paid-trigger-cleanup to main July 8, 2026 10:58
@turip turip changed the title Support usage-based gathering line deletes feat: support usage-based gathering line deletes Jul 8, 2026
@turip
turip force-pushed the feat/gathering-line-delete branch 2 times, most recently from 082dc88 to a40acdd Compare July 8, 2026 11:10
@turip
turip force-pushed the feat/gathering-line-delete branch from a40acdd to ee00c8e Compare July 8, 2026 11:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

147-149: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider wrapping the direct editFn error for consistency.

When editFn fails through the Mutate path (lines 134–135, 139–140), the error is wrapped with context like "mutating base intent". In the direct call path here, the error is returned unwrapped, so the same editFn failure produces different error messages depending on whether an override layer already exists.

♻️ Optional: wrap error for debuggability
 		overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields
 		if err := editFn(&overrideFields); err != nil {
-			return err
+			return fmt.Errorf("editing override intent: %w", err)
 		}
🤖 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/statemachine.go` around lines
147 - 149, The direct editFn call in the state machine path returns the raw
error, unlike the Mutate path where editFn failures are wrapped with context.
Update the editFn handling in the same statemachine.go flow to wrap this error
consistently with the existing mutating context used around override/base intent
mutations, so callers see the same error shape regardless of whether an override
layer already exists.
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go (1)

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

Consider extracting the shared progressive setup into a helper.

The "create progressive usage-based subscription" and "create paid progressive invoice and remaining gathering tail" subtests here are near-identical to the same-named subtests in TestUsageBasedProgressiveGatheringInvoiceManualDeleteFinalizesCharge (lines 7253–7351). The only differences are the sync target time (2024-03-01 vs 2024-02-01) and one extra Require().Len check in the third test. That's ~90 lines of duplicated setup.

Per the coding guidelines, duplicate setup paths should be parameterized into one helper. A helper returning the six values both tests need (subsView, progressiveInvoice, progressiveLine, chargeID, gatheringInvoice, remainingLine) parameterized by the sync time would eliminate the copy and keep the two tests in sync if the setup evolves.

Based on coding guidelines: "Avoid redundant test helpers and duplicate setup paths; parameterize one helper over near-identical helpers."

♻️ Suggested shared setup helper
+type progressiveUsageBasedSetup struct {
+	subsView           subscription.SubscriptionView
+	progressiveInvoice billing.StandardInvoice
+	progressiveLine    *billing.StandardLine
+	chargeID           chargesmeta.ChargeID
+	gatheringInvoice   billing.GatheringInvoice
+	remainingLine      billing.GatheringLine
+}
+
+func (s *CreditThenInvoiceTestSuite) setupPaidProgressiveWithGatheringTail(ctx context.Context, syncTo time.Time) progressiveUsageBasedSetup {
+	s.enableProgressiveBilling()
+	s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 0, s.mustParseTime("2023-01-01T00:00:00Z"))
+	s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 1, s.mustParseTime("2024-01-01T00:00:00Z"))
+	s.MockStreamingConnector.AddSimpleEvent(*s.APIRequestsTotalFeature.MeterSlug, 1, s.mustParseTime("2024-01-12T09:30:00Z"))
+
+	subsView := s.createSubscriptionFromPlan(plan.CreatePlanInput{
+		// ... same plan config ...
+	})
+
+	clock.FreezeTime(clock.Now().Add(time.Minute))
+	s.NoError(s.Service.SyncByView(ctx, subsView, syncTo))
+
+	clock.FreezeTime(s.mustParseTime("2024-01-15T00:00:00Z"))
+	draftInvoices, err := s.BillingService.InvoicePendingLines(ctx, billing.InvoicePendingLinesInput{
+		Customer: s.Customer.GetID(),
+		AsOf:     lo.ToPtr(s.mustParseTime("2024-01-15T00:00:00Z")),
+	})
+	s.NoError(err)
+	s.Require().Len(draftInvoices, 1)
+
+	progressiveInvoice := draftInvoices[0]
+	s.Require().Len(progressiveInvoice.Lines.OrEmpty(), 1)
+	progressiveLine := progressiveInvoice.Lines.OrEmpty()[0]
+	s.Require().NotNil(progressiveLine.ChargeID)
+	chargeID := chargesmeta.ChargeID{Namespace: progressiveLine.Namespace, ID: *progressiveLine.ChargeID}
+	s.Require().NotNil(progressiveInvoice.CollectionAt)
+
+	clock.FreezeTime(progressiveInvoice.CollectionAt.Add(time.Minute))
+	progressiveInvoice, err = s.BillingService.AdvanceInvoice(ctx, progressiveInvoice.GetInvoiceID())
+	s.NoError(err)
+	s.Equal(billing.StandardInvoiceStatusDraftWaitingAutoApproval, progressiveInvoice.Status)
+
+	progressiveInvoice, err = s.BillingService.ApproveInvoice(ctx, progressiveInvoice.GetInvoiceID())
+	s.NoError(err)
+	s.Equal(billing.StandardInvoiceStatusPaid, progressiveInvoice.Status)
+
+	gatheringInvoice := s.gatheringInvoice(ctx, s.Namespace, s.Customer.ID)
+	s.populateChildIDsFromParents(&gatheringInvoice)
+	s.DebugDumpInvoice("gathering invoice before manual delete", gatheringInvoice)
+	s.Require().Len(gatheringInvoice.Lines.OrEmpty(), 1)
+
+	remainingLine, found := lo.Find(gatheringInvoice.Lines.OrEmpty(), func(line billing.GatheringLine) bool {
+		return line.ChargeID != nil && *line.ChargeID == chargeID.ID
+	})
+	s.Require().True(found, "remaining gathering line should exist before manual delete")
+	s.Equal(progressiveLine.GetServicePeriod().To, remainingLine.ServicePeriod.From)
+
+	return progressiveUsageBasedSetup{
+		subsView:           subsView,
+		progressiveInvoice: progressiveInvoice,
+		progressiveLine:    progressiveLine,
+		chargeID:           chargeID,
+		gatheringInvoice:   gatheringInvoice,
+		remainingLine:      remainingLine,
+	}
+}

Then each test's setup subtest becomes:

 s.Run("create progressive usage-based subscription", func() {
-	// given: ...
-	s.enableProgressiveBilling()
-	s.MockStreamingConnector.AddSimpleEvent(...)
-	subsView = s.createSubscriptionFromPlan(...)
-	clock.FreezeTime(clock.Now().Add(time.Minute))
-	s.NoError(s.Service.SyncByView(ctx, subsView, s.mustParseTime("2024-03-01T00:00:00Z")))
+	// given: progressive billing enabled, usage exists, sync owns credit-then-invoice charge
+	setup := s.setupPaidProgressiveWithGatheringTail(ctx, s.mustParseTime("2024-03-01T00:00:00Z"))
+	subsView = setup.subsView
+	progressiveInvoice = setup.progressiveInvoice
+	progressiveLine = setup.progressiveLine
+	chargeID = setup.chargeID
+	gatheringInvoice = setup.gatheringInvoice
+	remainingLine = setup.remainingLine
 })
🤖 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/worker/subscriptionsync/service/sync_credittheninvoice_test.go`
around lines 7062 - 7159, The two progressive setup subtests in this test file
duplicate the same invoice creation and payment flow, so factor that shared
logic into a single helper instead of keeping near-identical blocks in both
places. Create a parameterized helper around the common setup in the progressive
test flow, using the existing symbols like s.enableProgressiveBilling,
s.createSubscriptionFromPlan, s.BillingService.InvoicePendingLines,
s.BillingService.AdvanceInvoice, s.BillingService.ApproveInvoice, and
s.gatheringInvoice, and have it return the shared values the tests need. Keep
only the differing sync target time and any extra assertion at the call sites so
both tests stay aligned as the setup evolves.

Source: Coding guidelines

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

Nitpick comments:
In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 147-149: The direct editFn call in the state machine path returns
the raw error, unlike the Mutate path where editFn failures are wrapped with
context. Update the editFn handling in the same statemachine.go flow to wrap
this error consistently with the existing mutating context used around
override/base intent mutations, so callers see the same error shape regardless
of whether an override layer already exists.

In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 7062-7159: The two progressive setup subtests in this test file
duplicate the same invoice creation and payment flow, so factor that shared
logic into a single helper instead of keeping near-identical blocks in both
places. Create a parameterized helper around the common setup in the progressive
test flow, using the existing symbols like s.enableProgressiveBilling,
s.createSubscriptionFromPlan, s.BillingService.InvoicePendingLines,
s.BillingService.AdvanceInvoice, s.BillingService.ApproveInvoice, and
s.gatheringInvoice, and have it return the shared values the tests need. Keep
only the differing sync target time and any extra assertion at the call sites so
both tests stay aligned as the setup evolves.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: da0be41a-10f3-4dec-9c7b-0a1180fdd5d9

📥 Commits

Reviewing files that changed from the base of the PR and between b746d1f and 86c28df.

📒 Files selected for processing (17)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/patch_target_test.go
  • openmeter/billing/charges/meta/patchshrinktorealizedperiod.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/usagebased/adapter/charge.go
  • openmeter/billing/charges/usagebased/adapter/intentoverride_test.go
  • openmeter/billing/charges/usagebased/charge.go
  • openmeter/billing/charges/usagebased/realizationrun.go
  • openmeter/billing/charges/usagebased/realizationrun_test.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice.go
  • openmeter/billing/charges/usagebased/service/creditheninvoice_test.go
  • openmeter/billing/charges/usagebased/service/creditsonly.go
  • openmeter/billing/charges/usagebased/service/lineengine.go
  • openmeter/billing/charges/usagebased/service/rating/service_test.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

@turip
turip requested a review from tothandras July 8, 2026 11:53
@turip
turip merged commit 8eb475e into main Jul 8, 2026
26 checks passed
@turip
turip deleted the feat/gathering-line-delete branch July 8, 2026 13:05
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