Skip to content

feat: subscription sync patch targeting - #4576

Merged
turip merged 3 commits into
mainfrom
feat/subssync-patch-targeting
Jun 26, 2026
Merged

turip merged 3 commits into
mainfrom
feat/subssync-patch-targeting

Conversation

@turip

@turip turip commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

What

  • Add explicit base-vs-override targets to charge patches.
  • Route subscription sync charge patches to the base intent layer.
  • Load persisted subscription-sync charges using base intent deletion state.
  • Keep effective invoice reconciliation unchanged when a base-layer patch is hidden by an active override.

Why

Subscription sync owns subscription-derived base charge state, while API/user overrides can own the effective customer-facing layer. Patch targeting makes that ownership explicit so sync can continue reconciling base state without accidentally mutating active overrides.

Validation

  • go test -tags=dynamic -count=1 ./test/credits
  • SVIX_HOST=localhost go test -tags=dynamic -count=1 ./test/notification

Summary by CodeRabbit

  • New Features
    • Charge listings can now filter deleted charges using either “effective” or “base-intent” deletion semantics.
    • Billing patches now require explicit charge target selection, with consistent behavior for extend, shrink, and delete operations.
  • Bug Fixes
    • Improved billing reconciliation so base/override invoice state is preserved correctly, especially when deleting charges.
    • Subscription sync reconciliation now uses base-intent deletion state to avoid hiding charges that still need reconciliation.
  • Documentation
    • Updated “Mutable Invoice Line Edits” and charge patch target rules to clarify reconciliation side effects and target semantics.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Ignoring CodeRabbit configuration file changes. For security, only the configuration from the base branch is applied for open source repositories.

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: 1ee8f3c4-3cc7-49eb-b6a1-f21805c9348a

📥 Commits

Reviewing files that changed from the base of the PR and between 77b8470 and 1d2c2ea.

📒 Files selected for processing (1)
  • .coderabbit.yaml

📝 Walkthrough

Walkthrough

Charge patches now carry explicit targets. Flat-fee and usage-based handlers use those targets for delete, extend, and shrink operations, and subscription sync now filters and builds patches from base-intent state. Tests and docs were updated to match.

Changes

Targeted charge patch reconciliation

Layer / File(s) Summary
Patch target contracts
.agents/skills/billing/SKILL.md, .agents/skills/charges/SKILL.md, openmeter/billing/charges/meta/patch.go, openmeter/billing/charges/meta/patchdelete.go, openmeter/billing/charges/meta/patchextend.go, openmeter/billing/charges/meta/patchshrink.go, openmeter/billing/charges/meta/patchextend_test.go, openmeter/billing/charges/meta/patchshrink_test.go, openmeter/billing/charges/service.go, openmeter/billing/charges/service/invoicable_test.go
Patch interfaces, constructors, validation, and charge listing now require explicit change targets, and the matching docs/tests now construct base-target patches and deleted-at filters.
Flat-fee delete and period handling
openmeter/billing/charges/flatfee/service/creditheninvoice.go, openmeter/billing/charges/flatfee/service/creditsonly.go, test/credits/credit_then_invoice_test.go, openmeter/billing/charges/service/invoicable_test.go
Flat-fee credit-then-invoice and credit-only handlers now delete as internal actions, mutate the requested target intent, and skip reconciliation for base-target patches under active overrides. Related tests now pass explicit base targets.
Usage-based delete and period handling
openmeter/billing/charges/usagebased/service/creditheninvoice.go, openmeter/billing/charges/usagebased/service/creditsonly.go, openmeter/billing/charges/usagebased/service/creditheninvoice_test.go, test/credits/base.go, test/credits/sanity_lifecycle_test.go, test/credits/sanity_test.go, test/credits/credit_then_invoice_test.go
Usage-based credit-then-invoice and credit-only handlers now delete as internal actions, mutate the requested target intent, and reuse shared period-patch application logic for extend and shrink. The refund-as-credits test helpers and scenarios now build base-target delete patches.
Base-intent listing and subscription sync
openmeter/billing/charges/adapter/search.go, openmeter/billing/charges/adapter/search_test.go, openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.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, .coderabbit.yaml
Charge listing now switches deleted-record filtering by deleted-at mode, subscription sync now loads base-intent charges, and its patch builders now create base-target extend, shrink, and delete patches. The review instructions add the matching persistence-path guidance.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

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 is concise and matches the main change: introducing explicit patch targeting for subscription sync.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/subssync-patch-targeting

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 26, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR makes subscription charge patches target the correct intent layer. The main changes are:

  • Explicit base-vs-override targets on charge patches.
  • Subscription-sync patches routed to the base intent layer.
  • Charge loading filtered by base intent deletion state.
  • Target-aware delete, extend, and shrink handling in charge state machines.

Confidence Score: 4/5

This is close, but the replacement path should be fixed before merging.

  • Base-target patching is wired through the constructors and state machines.
  • Base-intent charge loading matches the subscription-sync ownership model.
  • A credit-only replacement can still leave the old override-backed charge active while creating the replacement.

openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go

Important Files Changed

Filename Overview
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go Emulated replacement now uses a base-target delete, but it still creates the replacement even when an active override keeps the old charge effective.
openmeter/billing/charges/adapter/search.go Charge listing now supports base-intent deleted filtering for subscription-sync state loading.
openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go Subscription persisted-state loading now uses the base-intent deletion filter.
openmeter/billing/charges/meta/patchdelete.go Delete patches now require an explicit target and pass the full patch into state-machine handlers.

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/worker/subscriptionsync/service/reconciler/patchcharge.go:117-125
**Replacement keeps override**

This path still queues a base-target delete and then queues the replacement create. For credit-only period changes, a charge with an active override reaches this branch; the delete handler only marks the base intent deleted and returns because `HasOverrideLayer()` is true, leaving the effective override-backed charge active. The create then adds the replacement charge for the same subscription item, so both charges can keep allocating credits or invoicing for overlapping periods. Please add an enforceable guard here, such as rejecting replacement when the existing charge has an override, or avoid delete-plus-create for this case.

Reviews (3): Last reviewed commit: "chore: guide coderabbit charge state-mac..." | Re-trigger Greptile

@turip
turip marked this pull request as ready for review June 26, 2026 08:08
@turip
turip requested a review from a team as a code owner June 26, 2026 08:08
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Jun 26, 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: 3

Caution

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

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

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

Add one negative case for a missing or invalid target.

Nice update to pass the explicit base target. One small gap: these cases would still pass if PatchExtend.Validate() stopped enforcing Target, because every case uses ChangeTargetBase. A focused case around NewPatchExtendInput{Target: ""} or PatchExtend{} would lock in the new contract.

As per path instructions, “Make sure the tests are comprehensive and cover the changes.”

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

In `@openmeter/billing/charges/meta/patchextend_test.go` around lines 35 - 84, Add
a negative test in patchextend_test that verifies PatchExtend.Validate rejects a
missing or invalid target, since the current cases only cover ChangeTargetBase
and would miss a regression in target enforcement. Use the existing helpers and
symbols like mustNewPatchExtend, NewPatchExtendInput, PatchExtend.Validate, and
ChangeTargetBase to add a case with Target set to empty/invalid and assert
wantErr. Keep the new case alongside the existing table-driven tests so the
contract around Target stays covered.

Source: Path instructions

🧹 Nitpick comments (1)
openmeter/billing/charges/meta/patchextend.go (1)

34-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Collect target validation with the rest of the field errors.

These Validate() methods now return immediately on an invalid Target, so callers only see the first issue. Since this method is being touched, it’d be better to append the target error into errs []error and return models.NewNillableGenericValidationError(errors.Join(errs...)), matching the repo’s validation style.

As per coding guidelines, “For Go Validate() error methods, prefer collecting all validation issues into var errs []error and returning models.NewNillableGenericValidationError(errors.Join(errs...)) instead of returning on the first invalid field.”

Also applies to: 124-145

🤖 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/patchextend.go` around lines 34 - 55,
NewPatchExtendInput.Validate currently returns immediately on a bad Target, so
it does not follow the repo’s validation pattern of collecting all field errors.
Update this Validate method to accumulate the Target validation error together
with the existing NewServicePeriodTo, NewFullServicePeriodTo,
NewBillingPeriodTo, and NewInvoiceAt checks in a single errs slice, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of
early-returning. Apply the same pattern to the other Validate methods noted in
the diff so callers receive all validation issues at once.

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.

Inline comments:
In `@openmeter/billing/charges/usagebased/service/creditheninvoice.go`:
- Around line 257-269: Persist the base delete before returning from
CreditThenInvoiceStateMachine.DeleteCharge: the current override short-circuit
skips the adapter write/refetch path, so a base-target delete can remain only in
memory. Update DeleteCharge to ensure the mutated base intent is
written/refetched through the existing adapter flow before the
HasOverrideLayer() early return, so IntentDeletedAt is preserved for
subscription sync base-intent filtering.
- Around line 364-390: The base intent update in applyPeriodPatch is being
applied only in memory and then skipped when ShouldReconcile is false, which can
drop hidden base period changes. In
CreditThenInvoiceStateMachine.applyPeriodPatch, make sure the mutated base layer
is persisted or refetched before any early return tied to reconciliation
skipping, so the updated ServicePeriod, FullServicePeriod, BillingPeriod, and
InvoiceAt values are not lost. Keep the fix localized around the
patch.GetTarget() handling and the short-circuit path after
s.Charge.Intent.Mutate.

In `@openmeter/billing/charges/usagebased/service/creditsonly.go`:
- Around line 120-132: Persist the base delete before returning when
patch.GetTarget() is meta.ChangeTargetBase and
s.Charge.Intent.HasOverrideLayer() is true: the current early return in
CreditsOnlyStateMachine.DeleteCharge skips the adapter write after Mutate() only
updates the in-memory intent. Update the branch so the base IntentDeletedAt
change is still written out through the same persistence path used for deletes,
while still avoiding the customer-facing credit correction logic for
override-backed charges.

---

Outside diff comments:
In `@openmeter/billing/charges/meta/patchextend_test.go`:
- Around line 35-84: Add a negative test in patchextend_test that verifies
PatchExtend.Validate rejects a missing or invalid target, since the current
cases only cover ChangeTargetBase and would miss a regression in target
enforcement. Use the existing helpers and symbols like mustNewPatchExtend,
NewPatchExtendInput, PatchExtend.Validate, and ChangeTargetBase to add a case
with Target set to empty/invalid and assert wantErr. Keep the new case alongside
the existing table-driven tests so the contract around Target stays covered.

---

Nitpick comments:
In `@openmeter/billing/charges/meta/patchextend.go`:
- Around line 34-55: NewPatchExtendInput.Validate currently returns immediately
on a bad Target, so it does not follow the repo’s validation pattern of
collecting all field errors. Update this Validate method to accumulate the
Target validation error together with the existing NewServicePeriodTo,
NewFullServicePeriodTo, NewBillingPeriodTo, and NewInvoiceAt checks in a single
errs slice, then return
models.NewNillableGenericValidationError(errors.Join(errs...)) instead of
early-returning. Apply the same pattern to the other Validate methods noted in
the diff so callers receive all validation issues at once.
🪄 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: d30ff731-6f3d-4392-962d-0ffb67e81f28

📥 Commits

Reviewing files that changed from the base of the PR and between 3d4c7f0 and 2545997.

📒 Files selected for processing (25)
  • .agents/skills/billing/SKILL.md
  • .agents/skills/charges/SKILL.md
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/adapter/search_test.go
  • openmeter/billing/charges/flatfee/service/creditheninvoice.go
  • openmeter/billing/charges/flatfee/service/creditsonly.go
  • openmeter/billing/charges/meta/patch.go
  • openmeter/billing/charges/meta/patchdelete.go
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchextend_test.go
  • openmeter/billing/charges/meta/patchshrink.go
  • openmeter/billing/charges/meta/patchshrink_test.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/service/invoicable_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/worker/subscriptionsync/service/persistedstate/loader.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

@turip
turip force-pushed the feat/subssync-patch-targeting branch from 2545997 to 781739b Compare June 26, 2026 08:36
@turip
turip force-pushed the feat/subssync-patch-targeting branch from 781739b to 77b8470 Compare June 26, 2026 08:38
@turip

turip commented Jun 26, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai What would be a good .coderabbit.yaml rule to prevent this class of false positive from happening again? Specifically: for charge state-machine handlers under openmeter/billing/charges/**/service/*.go, mutations made inside handlers invoked through service.TriggerPatch -> stateMachine.FireAndActivate -> chargestatemachine.Machine.FireAndActivate are persisted after the handler returns via Persistence.UpdateBase(ctx, m.Charge.GetBase()). We want reviews to trace that call chain before claiming an in-memory mutation is not persisted. Please suggest the exact review-instruction text/config shape you would recommend.

@coderabbitai

coderabbitai Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

⚙️ CodeRabbit configuration inspected

Length of output: 9023



@turip Yep — given your current config, I’d add this as a new reviews.path_instructions entry.

reviews:
  path_instructions:
    - path: openmeter/billing/charges/**/service/*.go
      instructions: >
        For charge state-machine handlers in this path, do not claim that an
        in-memory mutation is not persisted until you trace the full patch
        execution and persistence flow in the current code.

        When a handler is invoked from `service.TriggerPatch`, follow this call
        chain before raising a persistence finding:
        `service.TriggerPatch -> stateMachine.FireAndActivate ->
        chargestatemachine.Machine.FireAndActivate`.

        In this flow, mutations made by the handler are persisted after the
        handler returns via `Persistence.UpdateBase(ctx, m.Charge.GetBase())`.

        Before reporting that a mutation is "only in memory" or "not saved",
        verify whether the handler mutates the base/intent state that
        `UpdateBase(...)` persists. If that persistence path exists in reachable
        current code, omit the finding. If you cannot verify a missing
        persistence path from the diff and reachable current code, omit the
        finding.

If you want, I’d put it near your existing Go-specific instruction so it stacks naturally with:

  • “re-verify the claim against the current code and domain model”
  • “if the evidence is not present in the diff or reachable current code, omit the finding”

If you want a slightly stronger/tighter version, this is the shorter variant I’d use:

reviews:
  path_instructions:
    - path: openmeter/billing/charges/**/service/*.go
      instructions: >
        In charge state-machine handler reviews, do not flag mutations as
        unpersisted without tracing the current call path from
        `service.TriggerPatch` through `stateMachine.FireAndActivate` and
        `chargestatemachine.Machine.FireAndActivate` to the post-handler
        persistence call `Persistence.UpdateBase(ctx, m.Charge.GetBase())`.

        Treat handler-local mutations to the persisted base/intent as persisted
        unless the current code shows they are not included in
        `UpdateBase(...)`. If that cannot be shown from the diff and reachable
        code, omit the finding.

I’d personally use the first version since it’s a bit more explicit and better at steering away from exactly this false positive class.


✏️ Learnings added
Learnt from: turip
URL: https://github.com/openmeterio/openmeter/pull/4576

Timestamp: 2026-06-26T08:41:03.960Z
Learning: In `openmeter/billing/charges/**/service/*.go`, charge state-machine handlers reached via `service.TriggerPatch -> stateMachine.FireAndActivate -> chargestatemachine.Machine.FireAndActivate` persist their mutations after the handler returns through `Persistence.UpdateBase(ctx, m.Charge.GetBase())`; reviews should trace that call chain before claiming an in-memory mutation is not persisted.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@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.

Caution

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

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

46-53: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add one override-target happy path here.

Right now every passing case uses ChangeTargetBase, so a regression that rejects or mishandles ChangeTargetOverride would still leave this file green even though explicit target selection is the contract change in this PR.

Suggested addition
 		{
 			name: "allows service period extension with unchanged full service and billing periods",
 			patch: mustNewPatchExtend(t, NewPatchExtendInput{
 				Target:                 ChangeTargetBase,
 				NewServicePeriodTo:     intent.ServicePeriod.To.Add(time.Hour),
 				NewFullServicePeriodTo: intent.FullServicePeriod.To,
 				NewBillingPeriodTo:     intent.BillingPeriod.To,
 				NewInvoiceAt:           intent.ServicePeriod.To.Add(time.Hour),
 			}),
 		},
+		{
+			name: "allows override-target service period extension",
+			patch: mustNewPatchExtend(t, NewPatchExtendInput{
+				Target:                 ChangeTargetOverride,
+				NewServicePeriodTo:     intent.ServicePeriod.To.Add(time.Hour),
+				NewFullServicePeriodTo: intent.FullServicePeriod.To,
+				NewBillingPeriodTo:     intent.BillingPeriod.To,
+				NewInvoiceAt:           intent.ServicePeriod.To.Add(time.Hour),
+			}),
+		},
🤖 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/patchextend_test.go` around lines 46 - 53, Add
a passing test case in patchextend_test.go that uses ChangeTargetOverride
instead of only ChangeTargetBase, so the PatchExtendInput/ mustNewPatchExtend
happy-path coverage exercises the new override-target contract. Reuse the
existing test pattern around NewPatchExtendInput and verify the extension still
succeeds with the override target while keeping the service, full service,
billing periods, and invoice timing consistent with the current happy path.

Source: Path instructions

🤖 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.

Outside diff comments:
In `@openmeter/billing/charges/meta/patchextend_test.go`:
- Around line 46-53: Add a passing test case in patchextend_test.go that uses
ChangeTargetOverride instead of only ChangeTargetBase, so the PatchExtendInput/
mustNewPatchExtend happy-path coverage exercises the new override-target
contract. Reuse the existing test pattern around NewPatchExtendInput and verify
the extension still succeeds with the override target while keeping the service,
full service, billing periods, and invoice timing consistent with the current
happy path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f0961262-b199-4804-be4d-6229841a2a06

📥 Commits

Reviewing files that changed from the base of the PR and between 2545997 and 77b8470.

📒 Files selected for processing (3)
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/charges/meta/patchextend_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • openmeter/billing/charges/meta/patchextend.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go

Comment on lines +117 to +125
deletePatch, err := chargesmeta.NewPatchDelete(chargesmeta.NewPatchDeleteInput{
Target: chargesmeta.ChangeTargetBase,
Policy: chargesmeta.RefundAsCreditsDeletePolicy,
})
if err != nil {
return fmt.Errorf("creating replacement delete patch: %w", err)
}

if err := c.addPatch(existing.ID().ID, deletePatch); err != nil {

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.

P1 Replacement keeps override

This path still queues a base-target delete and then queues the replacement create. For credit-only period changes, a charge with an active override reaches this branch; the delete handler only marks the base intent deleted and returns because HasOverrideLayer() is true, leaving the effective override-backed charge active. The create then adds the replacement charge for the same subscription item, so both charges can keep allocating credits or invoicing for overlapping periods. Please add an enforceable guard here, such as rejecting replacement when the existing charge has an override, or avoid delete-plus-create for this case.

Prompt To Fix With AI
This is a comment left during a code review.
Path: openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
Line: 117-125

Comment:
**Replacement keeps override**

This path still queues a base-target delete and then queues the replacement create. For credit-only period changes, a charge with an active override reaches this branch; the delete handler only marks the base intent deleted and returns because `HasOverrideLayer()` is true, leaving the effective override-backed charge active. The create then adds the replacement charge for the same subscription item, so both charges can keep allocating credits or invoicing for overlapping periods. Please add an enforceable guard here, such as rejecting replacement when the existing charge has an override, or avoid delete-plus-create for this case.

How can I resolve this? If you propose a fix, please make it concise.

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Known issue, will be handled later. This is credits only where overrides are unsupported for now.

@turip
turip merged commit c16cbe1 into main Jun 26, 2026
26 checks passed
@turip
turip deleted the feat/subssync-patch-targeting branch June 26, 2026 10:17
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