Repository navigation
feat: subscription sync patch targeting - #4576
Conversation
|
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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughCharge 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. ChangesTargeted charge patch reconciliation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Greptile SummaryThis PR makes subscription charge patches target the correct intent layer. The main changes are:
Confidence Score: 4/5This is close, but the replacement path should be fixed before merging.
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go Important Files Changed
Prompt To Fix All With AIFix 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 |
There was a problem hiding this comment.
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 winAdd 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 enforcingTarget, because every case usesChangeTargetBase. A focused case aroundNewPatchExtendInput{Target: ""}orPatchExtend{}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 winCollect target validation with the rest of the field errors.
These
Validate()methods now return immediately on an invalidTarget, so callers only see the first issue. Since this method is being touched, it’d be better to append the target error intoerrs []errorand returnmodels.NewNillableGenericValidationError(errors.Join(errs...)), matching the repo’s validation style.As per coding guidelines, “For Go
Validate() errormethods, prefer collecting all validation issues intovar errs []errorand returningmodels.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
📒 Files selected for processing (25)
.agents/skills/billing/SKILL.md.agents/skills/charges/SKILL.mdopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/adapter/search_test.goopenmeter/billing/charges/flatfee/service/creditheninvoice.goopenmeter/billing/charges/flatfee/service/creditsonly.goopenmeter/billing/charges/meta/patch.goopenmeter/billing/charges/meta/patchdelete.goopenmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchextend_test.goopenmeter/billing/charges/meta/patchshrink.goopenmeter/billing/charges/meta/patchshrink_test.goopenmeter/billing/charges/service.goopenmeter/billing/charges/service/invoicable_test.goopenmeter/billing/charges/usagebased/service/creditheninvoice.goopenmeter/billing/charges/usagebased/service/creditheninvoice_test.goopenmeter/billing/charges/usagebased/service/creditsonly.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.gotest/credits/base.gotest/credits/credit_then_invoice_test.gotest/credits/sanity_lifecycle_test.gotest/credits/sanity_test.go
2545997 to
781739b
Compare
781739b to
77b8470
Compare
|
@coderabbitai What would be a good |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain⚙️ CodeRabbit configuration inspected Length of output: 9023
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:
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
|
There was a problem hiding this comment.
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 winAdd one override-target happy path here.
Right now every passing case uses
ChangeTargetBase, so a regression that rejects or mishandlesChangeTargetOverridewould 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
📒 Files selected for processing (3)
openmeter/billing/charges/meta/patchextend.goopenmeter/billing/charges/meta/patchextend_test.goopenmeter/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
| 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 { |
There was a problem hiding this comment.
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.There was a problem hiding this comment.
Known issue, will be handled later. This is credits only where overrides are unsupported for now.
What
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/creditsSVIX_HOST=localhost go test -tags=dynamic -count=1 ./test/notificationSummary by CodeRabbit