Skip to content

feat: refactor charge patch source routing - #4607

Merged
turip merged 2 commits into
mainfrom
feat/charge-patch-source-routing
Jun 30, 2026
Merged

turip merged 2 commits into
mainfrom
feat/charge-patch-source-routing

Conversation

@turip

@turip turip commented Jun 30, 2026 •

Copy link
Copy Markdown
Member

Summary

  • route charge patches from ChangeSource instead of explicit patch target fields
  • add layer-aware intent mutation helpers for flat-fee and usage-based state machines
  • ensure manually managed charges keep targeting their base intent instead of receiving an override layer on manual API edits
  • rename manual edit patches to line manual edits and validate state-machine patch arguments consistently

Summary by CodeRabbit

  • New Features

    • Added support for line-scoped manual edits and clearer handling of patch targets across billing changes.
    • Improved patch validation so edits and deletes are applied to the correct billing layer automatically.
  • Bug Fixes

    • Fixed patch operations to use change source information consistently, reducing incorrect update/delete behavior.
    • Improved error messages for unsupported edits, invalid change sources, and edge cases around managed lines.
  • Tests

    • Expanded test coverage for patch targeting, validation, and trigger handling.

@turip
turip requested a review from a team as a code owner June 30, 2026 09:03
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 43e5b374-a5c6-4973-ba41-9b934c545435

📥 Commits

Reviewing files that changed from the base of the PR and between 403c906 and 3933624.

📒 Files selected for processing (7)
  • openmeter/billing/change_source_test.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/meta/patch_target_test.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/meta/patchshrink_test.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • openmeter/billing/change_source_test.go
  • openmeter/billing/charges/usagebased/service/statemachine.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/meta/patch_target_test.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go

📝 Walkthrough

Walkthrough

Replaces explicit ChangeTarget fields in charge patch types with billing.ChangeSource, adds layer-aware target resolution, introduces PatchLineManualEdit and TriggerLineManualEdit for API invoice-line edits, and updates flat-fee and usage-based state machines plus their callsites and tests to use the new patch model.

Changes

Patch targeting and LineManualEdit refactor

Layer / File(s) Summary
Core patch contracts
openmeter/billing/lineengine.go, openmeter/billing/change_source_test.go, openmeter/billing/charges/meta/patch.go, openmeter/billing/charges/meta/triggers.go, openmeter/billing/charges/flatfee/charge.go, openmeter/billing/charges/usagebased/charge.go
Adds ChangeSource.Require, introduces LayeredIntentReader and apiPatchTargetLayer, renames the manual-edit patch and trigger identifiers, removes Patch.GetTarget, and adds GetBaseManagedBy() on both intent types.
Patch type rewrites
openmeter/billing/charges/meta/patchextend.go, openmeter/billing/charges/meta/patchshrink.go, openmeter/billing/charges/meta/patchdelete.go, openmeter/billing/charges/meta/patchlinemanualedit.go
Reworks PatchExtend, PatchShrink, and PatchDelete to carry ChangeSource and adds PatchLineManualEdit with API-only change-source enforcement and layer targeting.
State machine validation and intent mutation
openmeter/billing/charges/statemachine/machine.go, openmeter/billing/charges/statemachine/machine_test.go, openmeter/billing/charges/flatfee/service/statemachine.go, openmeter/billing/charges/usagebased/service/statemachine.go
Changes FireAndActivate to validate typed trigger arguments and adds mutateIntentLayer helpers for base/override intent mutation, including override creation when needed.
Flat-fee flow
openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/creditsonly.go, openmeter/billing/charges/flatfee/service/manualedit.go, openmeter/billing/charges/flatfee/service/lineengine.go
Routes flat-fee API edits through PatchLineManualEdit and TriggerLineManualEdit, updates unsupported-edit handling, resolves patch targets by intent layer, and mutates the resolved layer for period patches and deletes.
Usage-based flow
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditsonly.go, openmeter/billing/charges/usagebased/service/lineengine.go
Updates usage-based period patches and deletes to resolve target layers, mutates the resolved intent layer, and tightens line-engine trigger payload typing and managed-line errors.
Callsites, tests, and docs
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge*.go, test/credits/*, openmeter/billing/charges/*_test.go, .agents/skills/charges/SKILL.md
Updates reconciler patch construction, billing and credit tests, target-layer tests, and the charges skill documentation to use ChangeSource and the new line-manual-edit flow.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • openmeterio/openmeter#4580: Introduces the flat-fee manual line edit flow that this PR reshapes into PatchLineManualEdit and TriggerLineManualEdit.
  • openmeterio/openmeter#4577: Changes nearby charge patch/trigger plumbing and trigger argument handling that this PR extends with typed validation.
  • openmeterio/openmeter#4571: Establishes the intent layering and patch targeting model that this PR uses for ChangeSource-based target resolution.

Suggested labels

release-note/feature, area/billing, kind/feature

Suggested reviewers

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

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: refactoring charge patch routing to use change-source-based targeting.
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.
✨ 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/charge-patch-source-routing

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.

@greptile-apps

greptile-apps Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR refactors charge patch routing to derive intent layers from the change source. The main changes are:

  • Source-aware patch types for extend, shrink, delete, and line manual edits.
  • Layer-aware mutation helpers for flat-fee and usage-based charge state machines.
  • Manual API edits that keep manually managed charges on the base intent.
  • Subscription sync patches marked as system-sourced changes.
  • Updated tests and charge guidance for the new routing rules.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.
  • The source-to-layer routing matches the intended base and override behavior.
  • The latest changes add validation before creating new override layers.

Important Files Changed

Filename Overview
openmeter/billing/charges/meta/patch.go Adds the shared source-to-layer routing helper and updates the patch interface.
openmeter/billing/charges/meta/patchdelete.go Moves delete patches from explicit targets to source-derived target layers.
openmeter/billing/charges/meta/patchextend.go Restricts extend patches to system changes and routes them to the base layer.
openmeter/billing/charges/meta/patchshrink.go Restricts shrink patches to system changes and aggregates validation errors.
openmeter/billing/charges/meta/patchlinemanualedit.go Adds an API-only patch type for line manual edits.
openmeter/billing/charges/flatfee/service/creditheninvoice.go Applies derived target layers in flat-fee delete, period patch, and line edit flows.
openmeter/billing/charges/flatfee/service/statemachine.go Adds a helper for mutating base or override flat-fee intent layers.
openmeter/billing/charges/usagebased/service/statemachine.go Adds a helper for mutating base or override usage-based intent layers.
openmeter/billing/charges/flatfee/service/lineengine.go Routes flat-fee manual line edits and deletes through source-aware patch payloads.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go Marks subscription-sync delete and replacement patches as system-sourced changes.

Reviews (2): Last reviewed commit: "fix(billing): address charge patch revie..." | Re-trigger Greptile

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
openmeter/billing/charges/meta/patchshrink.go (1)

35-56: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Collect all shrink validation errors instead of failing fast.

Line 35 and Line 114 still return on the first invalid field, so callers only see one validation problem at a time. Please aggregate into errs like ValidateWith already does. As per coding guidelines, “For Go Validate() error methods, collect all validation issues into var errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)) instead of failing fast.”

Suggested patch
 func (i NewPatchShrinkInput) Validate() error {
+	var errs []error
+
 	if err := i.ChangeSource.Require(billing.ChangeSourceSystem); err != nil {
-		return fmt.Errorf("change source: %w", err)
+		errs = append(errs, fmt.Errorf("change source: %w", err))
 	}
 
 	if i.NewServicePeriodTo.IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new service period to is required"))
+		errs = append(errs, fmt.Errorf("new service period to is required"))
 	}
 
 	if i.NewFullServicePeriodTo.IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new full service period to is required"))
+		errs = append(errs, fmt.Errorf("new full service period to is required"))
 	}
 
 	if i.NewBillingPeriodTo.IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new billing period to is required"))
+		errs = append(errs, fmt.Errorf("new billing period to is required"))
 	}
 
 	if i.NewInvoiceAt.IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new invoice at is required"))
+		errs = append(errs, fmt.Errorf("new invoice at is required"))
 	}
 
-	return nil
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }
 
 func (p PatchShrink) Validate() error {
+	var errs []error
+
 	if err := p.GetChangeSource().Require(billing.ChangeSourceSystem); err != nil {
-		return fmt.Errorf("change source: %w", err)
+		errs = append(errs, fmt.Errorf("change source: %w", err))
 	}
 
 	if p.GetNewServicePeriodTo().IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new service period to is required"))
+		errs = append(errs, fmt.Errorf("new service period to is required"))
 	}
 
 	if p.GetNewFullServicePeriodTo().IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new full service period to is required"))
+		errs = append(errs, fmt.Errorf("new full service period to is required"))
 	}
 
 	if p.GetNewBillingPeriodTo().IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new billing period to is required"))
+		errs = append(errs, fmt.Errorf("new billing period to is required"))
 	}
 
 	if p.GetNewInvoiceAt().IsZero() {
-		return models.NewGenericValidationError(fmt.Errorf("new invoice at is required"))
+		errs = append(errs, fmt.Errorf("new invoice at is required"))
 	}
 
-	return nil
+	return models.NewNillableGenericValidationError(errors.Join(errs...))
 }

Also applies to: 114-135

🤖 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/meta/patchshrink.go` around lines 35 - 56, The
Validate methods in NewPatchShrinkInput and the related shrink validation path
still fail fast on the first bad field. Update NewPatchShrinkInput.Validate and
the other Validate block referenced in the diff to collect all field validation
errors into errs instead of returning immediately, following the same pattern
used by ValidateWith. Finish by returning
models.NewNillableGenericValidationError(errors.Join(errs...)) so callers
receive every shrink validation issue at once.

Source: Coding guidelines

openmeter/billing/charges/meta/patchshrink_test.go (1)

13-157: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add one routing test for PatchShrink.GetTargetLayer.

This refactor moved PatchShrink onto ChangeSource too, but this suite only exercises ValidateWith and missing-source construction. Unlike PatchExtend, nothing here proves that system-sourced shrink targets base or that API-sourced shrink is rejected, so a routing regression can sneak through. As per path instructions, "**/*_test.go: Make sure the tests are comprehensive and cover the changes."

Also applies to: 159-169

🤖 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/meta/patchshrink_test.go` around lines 13 - 157,
Add a focused routing test for PatchShrink.GetTargetLayer in the PatchShrink
test suite, since the current tests only cover ValidateWith and construction.
Verify that a system ChangeSource routes to the base layer and that an API
ChangeSource is rejected or handled as expected, using PatchShrink and
GetTargetLayer to locate the code path. Keep the existing validation tests
intact and add the new case alongside them so routing regressions are covered.

Source: Path instructions

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

143-146: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Keep the new override path on the same validation boundary.

The other mutation paths use OverridableIntent.Mutate, which normalizes and validates edited fields. Here the new override fields are edited and passed directly to CreateChargeOverride, so this branch can diverge from the domain invariants unless the adapter duplicates that work.

Suggested tweak
 		overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields
 		editFn(&overrideFields)
+		overrideFields = overrideFields.Normalized()
+		if err := overrideFields.Validate(); err != nil {
+			return fmt.Errorf("validating override intent: %w", err)
+		}
 
 		base, err := s.Adapter.CreateChargeOverride(ctx, s.Charge.ChargeBase, overrideFields)
🤖 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
143 - 146, The new override branch bypasses the same normalization/validation
that other mutation paths get through OverridableIntent.Mutate. Update the
override flow in the state machine to apply the same boundary before calling
CreateChargeOverride, using the existing intent mutation/validation logic around
s.Charge.Intent.GetEffectiveIntent() and editFn so the adapter receives
already-normalized fields.
openmeter/billing/charges/flatfee/service/statemachine.go (1)

113-116: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Mirror the intent normalization/validation before creating a new override.

The base and existing-override paths go through OverridableIntent.Mutate, which normalizes and validates edited fields. This new missing-override branch applies editFn and sends the result straight to CreateChargeOverride, so it can hand off unnormalized/invalid fields unless the adapter happens to catch them.

Suggested tweak
-		overrideFields := s.Charge.Intent.GetEffectiveIntent().IntentMutableFields
+		effectiveIntent := s.Charge.Intent.GetEffectiveIntent()
+		overrideFields := effectiveIntent.IntentMutableFields
 		editFn(&overrideFields)
+		overrideFields = overrideFields.Normalized(effectiveIntent.Currency)
+		if err := overrideFields.Validate(); err != nil {
+			return fmt.Errorf("validating override intent: %w", err)
+		}
 
 		base, err := s.Adapter.CreateChargeOverride(ctx, s.Charge.ChargeBase, overrideFields)
🤖 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/flatfee/service/statemachine.go` around lines 113 -
116, The missing-override path in statemachine.go bypasses the same
normalization/validation used by OverridableIntent.Mutate before creating a
charge override. Update the branch around editFn and CreateChargeOverride so the
edited intent fields are passed through the same mutate/normalize/validate flow
as the base and existing-override paths, using the relevant charge intent
helpers from s.Charge.Intent.GetEffectiveIntent() before calling
s.Adapter.CreateChargeOverride.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@openmeter/billing/change_source_test.go`:
- Around line 9-14: Add the missing happy-path assertion in
TestChangeSourceRequire so it also verifies
ChangeSourceAPIRequest.Require(ChangeSourceAPIRequest) succeeds. Keep the
existing failure checks, but include an explicit no-error assertion for the
APIRequest case to cover the new manual-edit flow that relies on
ChangeSourceAPIRequest.Require, using the ChangeSourceAPIRequest and Require
symbols as the reference points.

In `@openmeter/billing/charges/flatfee/service/creditheninvoice.go`:
- Around line 259-293: The current line-type check in creditheninvoice.go treats
every non-gathering line as standard, which can persist a manual-edit intent
before unsupported types are rejected. Update the branch around the charge
update validation to handle only billing.InvoiceLineTypeStandard explicitly in
addition to billing.InvoiceLineTypeGathering, and add a default case that
returns billing.ErrCannotUpdateChargeManagedLine before any intent mutation.
Keep the logic localized near the current lineType and currentRun checks so
unsupported line types fail fast in this handler.

In `@openmeter/billing/charges/meta/patch_target_test.go`:
- Around line 35-38: The test in TestPeriodPatchValidateRejectsAPIChange is not
isolating the change-source guard because PatchExtend.Validate also fails on
missing period timestamps. Seed the required period times on PatchExtend so
validation reaches the API-request check, then assert the returned error message
mentions change source to pin the rejection path and protect the routing
contract.

---

Outside diff comments:
In `@openmeter/billing/charges/meta/patchshrink_test.go`:
- Around line 13-157: Add a focused routing test for PatchShrink.GetTargetLayer
in the PatchShrink test suite, since the current tests only cover ValidateWith
and construction. Verify that a system ChangeSource routes to the base layer and
that an API ChangeSource is rejected or handled as expected, using PatchShrink
and GetTargetLayer to locate the code path. Keep the existing validation tests
intact and add the new case alongside them so routing regressions are covered.

In `@openmeter/billing/charges/meta/patchshrink.go`:
- Around line 35-56: The Validate methods in NewPatchShrinkInput and the related
shrink validation path still fail fast on the first bad field. Update
NewPatchShrinkInput.Validate and the other Validate block referenced in the diff
to collect all field validation errors into errs instead of returning
immediately, following the same pattern used by ValidateWith. Finish by
returning models.NewNillableGenericValidationError(errors.Join(errs...)) so
callers receive every shrink validation issue at once.

---

Nitpick comments:
In `@openmeter/billing/charges/flatfee/service/statemachine.go`:
- Around line 113-116: The missing-override path in statemachine.go bypasses the
same normalization/validation used by OverridableIntent.Mutate before creating a
charge override. Update the branch around editFn and CreateChargeOverride so the
edited intent fields are passed through the same mutate/normalize/validate flow
as the base and existing-override paths, using the relevant charge intent
helpers from s.Charge.Intent.GetEffectiveIntent() before calling
s.Adapter.CreateChargeOverride.

In `@openmeter/billing/charges/usagebased/service/statemachine.go`:
- Around line 143-146: The new override branch bypasses the same
normalization/validation that other mutation paths get through
OverridableIntent.Mutate. Update the override flow in the state machine to apply
the same boundary before calling CreateChargeOverride, using the existing intent
mutation/validation logic around s.Charge.Intent.GetEffectiveIntent() and editFn
so the adapter receives already-normalized fields.
🪄 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: f0e479b3-d66a-4c8d-b589-22385beeeb82

📥 Commits

Reviewing files that changed from the base of the PR and between 0c1243e and 403c906.

📒 Files selected for processing (34)
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/change_source_test.go
  • openmeter/billing/charges/flatfee/charge.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/flatfee/service/lineengine.go
  • openmeter/billing/charges/flatfee/service/manualedit.go
  • openmeter/billing/charges/flatfee/service/statemachine.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/patch_target_test.go
  • openmeter/billing/charges/meta/patchdelete.go
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchextend_test.go
  • openmeter/billing/charges/meta/patchlinemanualedit.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/meta/patchshrink_test.go
  • openmeter/billing/charges/meta/triggers.go
  • openmeter/billing/charges/service/invoicable_test.go
  • openmeter/billing/charges/statemachine/machine.go
  • openmeter/billing/charges/statemachine/machine_test.go
  • openmeter/billing/charges/usagebased/charge.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/statemachine.go
  • openmeter/billing/lineengine.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.go
  • test/credits/base.go
  • test/credits/credit_then_invoice_test.go
  • test/credits/sanity_lifecycle_test.go
  • test/credits/sanity_test.go

Comment thread openmeter/billing/change_source_test.go Resolved
@turip turip changed the title Refactor charge patch source routing feat: refactor charge patch source routing Jun 30, 2026
@turip turip added area/billing release-note/misc Miscellaneous changes labels Jun 30, 2026
@turip
turip merged commit 60126ca into main Jun 30, 2026
30 of 34 checks passed
@turip
turip deleted the feat/charge-patch-source-routing branch June 30, 2026 10:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants