Repository navigation
feat: subs sync charge create - #4024
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds charge-backed reconciliation to subscription-sync: persisted charge items, loader integration with charges.Service, charge patch collections/updater, reconciler routing for invoicing vs charges, test utilities and suites, plus supporting docs and test-wiring updates. All changes include new create-only charge intent paths and loader collision checks. Changes
Sequence DiagramsequenceDiagram
participant Sync as Sync Service
participant PersState as Persisted State
participant TargetState as Target Builder
participant Reconciler as Reconciler
participant Router as Patch Router
participant ChargeUpdater as Charge Updater
participant ChargeSvc as Charges Service
Sync->>PersState: LoadForSubscription(ctx, subs)
PersState->>ChargeSvc: ListCharges(subscriptionIDs...)
ChargeSvc-->>PersState: return charges
PersState-->>Sync: persisted items + loaded charges
Sync->>TargetState: Build target items from subscription
TargetState-->>Sync: target items
Sync->>Reconciler: Reconcile(persisted, target)
Reconciler->>Router: route items -> backend collections
alt invoicing backend
Router->>Router: apply semantic proration
Router->>Reconciler: collect invoice patches
else charges backend
Router->>Router: skip semantic proration
Router->>Reconciler: collect charge patches (create-only)
end
Reconciler-->>Sync: Plan(invoicePatches, chargePatches)
Sync->>Reconciler: Apply plan
Reconciler->>Reconciler: apply invoice patches
Reconciler->>ChargeUpdater: ApplyPatches(ctx, namespace, chargePatches)
ChargeUpdater->>ChargeSvc: Create(intents)
ChargeSvc-->>ChargeUpdater: created / error
ChargeUpdater-->>Reconciler: result
Reconciler-->>Sync: done
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly Related PRs
Suggested Reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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 |
cea6603 to
2284e6b
Compare
|
depends on #4026 |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
openmeter/subscription/workflow/service/addon_test.go (1)
554-566: Consider a helper here instead of rebuilding the wholePlanMeta.This literal already had to grow just to carry
SettlementMode, and the same thing will happen again the next timeproductcatalog.PlanMetagets a required field. A small builder mutator that only overrides the proration bits would make these tests a lot less brittle.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/subscription/workflow/service/addon_test.go` around lines 554 - 566, The test rebuilds an entire productcatalog.PlanMeta just to change proration and SettlementMode which is brittle; add a small helper/mutator (e.g., a method on subscriptiontestutils like WithProrationConfig or MutatePlanMeta) that accepts a base test plan from subscriptiontestutils.BuildTestPlanInput(t) and only overrides ProRatingConfig and SettlementMode, then call that helper instead of constructing a full PlanMeta in the test to keep future PlanMeta additions from breaking these tests (refer to subscriptiontestutils.BuildTestPlanInput, SetMeta, and productcatalog.PlanMeta when implementing the helper).openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go (1)
5-8: Optional: quick doc-comment polish for readability.Tiny wording tweaks would make this comment cleaner (
itsinstead ofit's, andpatches areinstead ofpatches is).✍️ Suggested wording
-// Updater acts as a facade for the charges service. This might be a temporary solution as charges will -// have it's own patching functionality in the future. +// Updater acts as a facade for the charges service. This might be a temporary solution as charges will +// have its own patching functionality in the future. // -// For now we are keeping this until charges patches is fully operational. +// For now we are keeping this until charge patches are fully operational.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go` around lines 5 - 8, Update the package comment for the Updater type to fix grammar and improve readability: change "it's" to "its" and "patches is" to "patches are", and consider rephrasing the sentences to be concise (reference: Updater and charges in the current comment) so the doc-comment reads cleanly and grammatically correct.openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go (1)
78-80: Consider removing unused IsEmpty method.The
IsEmpty()method onpatchesParseddoesn't appear to be used anywhere in the current code. If it's not needed for future planned functionality, you might want to remove it to keep the code tidy.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go` around lines 78 - 80, Remove the unused IsEmpty method from the patchesParsed type: delete the IsEmpty() bool method definition (func (p patchesParsed) IsEmpty() bool { return len(p.creates) == 0 }) since it isn’t referenced; after removal, run `go vet`/`go test`/`gofmt` to ensure no references remain and imports/builds are clean..agents/skills/subscriptionsync/SKILL.md (1)
24-53: Great architectural documentation!This SKILL.md file is a fantastic addition - it gives anyone working on subscriptionsync a clear mental model of the package structure, flow, and key design decisions. The routing rules and testing guidance sections are particularly helpful.
One small nit: the fenced code block for the package layout (line 24) is missing a language specifier, which triggers a markdownlint warning. You can add
textor just leave the triple backticks as-is - most renderers handle it fine either way.Optional fix for markdown lint
-``` +```text openmeter/billing/worker/subscriptionsync/🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In @.agents/skills/subscriptionsync/SKILL.md around lines 24 - 53, The fenced code block that documents the package layout in SKILL.md is missing a language specifier which triggers markdownlint; update the opening triple-backticks for that package layout block (the package layout code sample near the top of the file) to use a language tag like text (e.g., change ``` to ```text) so the linter stops warning while leaving the block contents unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 72-548: Add a test method to
CreditsOnlySubscriptionHandlerTestSuite (e.g.,
TestCreditsOnlyUnsupportedPriceFails) that creates a credits_only subscription
via createSubscriptionFromPlanAt whose phase contains a RateCard whose Price is
a variant not supported for credit-only (use a non-FlatPrice/non-UnitPrice
variant, e.g., PercentPrice), then call Service.SynchronizeSubscription(ctx,
subscriptionView, syncUntil) and assert it returns an error containing a clear
"unsupported price" message; use the existing helpers
(createSubscriptionFromPlanAt, clock.SetTime/ResetTime, and syncUntil pattern)
and mirror other tests' structure so this verifies the unsupported-price error
path in SynchronizeSubscription.
- Around line 634-655: The test currently uses s.Truef(found, ...) after lo.Find
which leaves execution continuing with a zero-value flatfee.Charge and can cause
panics when dereferencing charge.Intent.Subscription; change the lookup
assertion to a require-style check (e.g. s.Require().Truef(found, ...)) so the
test fails fast, and immediately after that add an explicit require non-nil
guard for charge.Intent.Subscription (e.g.
s.Require().NotNilf(charge.Intent.Subscription, "expected[%d] charge[%d]
subscription not nil", expectedIdx, periodIdx)) before accessing
SubscriptionID/PhaseID; apply the same replacements for the other identical
block referenced (lines ~694–714) where lo.Find is used.
In `@openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go`:
- Around line 98-101: The loader currently swallows missing chargeService in
Loader.loadChargesForSubscription by returning an empty map, which hides
persisted charges; change the nil-check in loadChargesForSubscription to return
a non-nil error (e.g., fmt.Errorf or a package-specific error) that clearly
states chargeService is not configured instead of returning map[string]Item{},
so callers can fail fast; update any callers or tests that expect the previous
behavior to handle the error.
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/patch.go`:
- Around line 108-124: ResolveDefaultCollection currently sends every non-flat
credit-only price to usageBasedChargeCollection; change it to explicitly match
the unit/usage price type and error for any other unsupported shapes. In
ResolveDefaultCollection (function name) add an explicit case for the unit/usage
price type (e.g. productcatalog.UnitPriceType) that returns
c.usageBasedChargeCollection, and replace the current default branch with a
fail-fast return error (use fmt.Errorf with the price.Type() value) so
unsupported credit-only price types do not silently route to the wrong backend.
Ensure the function still returns c.lineCollection for non-credit settlement
modes and preserves the existing nil-price check.
---
Nitpick comments:
In @.agents/skills/subscriptionsync/SKILL.md:
- Around line 24-53: The fenced code block that documents the package layout in
SKILL.md is missing a language specifier which triggers markdownlint; update the
opening triple-backticks for that package layout block (the package layout code
sample near the top of the file) to use a language tag like text (e.g., change
``` to ```text) so the linter stops warning while leaving the block contents
unchanged.
In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go`:
- Around line 78-80: Remove the unused IsEmpty method from the patchesParsed
type: delete the IsEmpty() bool method definition (func (p patchesParsed)
IsEmpty() bool { return len(p.creates) == 0 }) since it isn’t referenced; after
removal, run `go vet`/`go test`/`gofmt` to ensure no references remain and
imports/builds are clean.
In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go`:
- Around line 5-8: Update the package comment for the Updater type to fix
grammar and improve readability: change "it's" to "its" and "patches is" to
"patches are", and consider rephrasing the sentences to be concise (reference:
Updater and charges in the current comment) so the doc-comment reads cleanly and
grammatically correct.
In `@openmeter/subscription/workflow/service/addon_test.go`:
- Around line 554-566: The test rebuilds an entire productcatalog.PlanMeta just
to change proration and SettlementMode which is brittle; add a small
helper/mutator (e.g., a method on subscriptiontestutils like WithProrationConfig
or MutatePlanMeta) that accepts a base test plan from
subscriptiontestutils.BuildTestPlanInput(t) and only overrides ProRatingConfig
and SettlementMode, then call that helper instead of constructing a full
PlanMeta in the test to keep future PlanMeta additions from breaking these tests
(refer to subscriptiontestutils.BuildTestPlanInput, SetMeta, and
productcatalog.PlanMeta when implementing the helper).
🪄 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: f85ac2db-c634-4fd5-934d-ff26485aa95c
📒 Files selected for processing (37)
.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/service.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.goopenmeter/billing/worker/subscriptionsync/service/reconciler/prorate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_test.goopenmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.goopenmeter/productcatalog/addon/adapter/mapping.goopenmeter/productcatalog/plan/adapter/adapter_test.goopenmeter/productcatalog/plan/adapter/plan.goopenmeter/productcatalog/plan/assert.goopenmeter/productcatalog/plan/service/plan.goopenmeter/productcatalog/plan/service/service_test.goopenmeter/productcatalog/testutils/plan.goopenmeter/subscription/addon/diff/restore_test.goopenmeter/subscription/service/sync.goopenmeter/subscription/testutils/builder.goopenmeter/subscription/workflow/service/addon_test.goopenmeter/subscription/workflow/service/subscription_test.gotest/credits/sanity_test.go
💤 Files with no reviewable changes (1)
- openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (2)
644-656:⚠️ Potential issue | 🟡 MinorGuard
Intent.Subscriptionbefore dereferencing it.The lookup now fails fast, but both helpers still assume
charge.Intent.Subscriptionis always present. If a matching charge comes back without subscription linkage,SubscriptionID/PhaseIDturns this into a panic instead of a clean test failure. As.Require().NotNilf(charge.Intent.Subscription, ...)right before those assertions would make this much safer.Suggested fix
s.NotNilf(charge.Intent.UniqueReferenceID, "expected[%d] charge[%d] should have child unique reference id", expectedIdx, periodIdx) + s.Require().NotNilf(charge.Intent.Subscription, "expected[%d] charge[%d] should have subscription reference", expectedIdx, periodIdx) s.Equalf(childID, lo.FromPtr(charge.Intent.UniqueReferenceID), "expected[%d] charge[%d] child unique reference id", expectedIdx, periodIdx)Apply the same guard in both helper blocks.
Also applies to: 706-717
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go` around lines 644 - 656, Tests assume charge.Intent.Subscription is non-nil before accessing Subscription.SubscriptionID and Subscription.PhaseID; add a guard using s.Require().NotNilf(charge.Intent.Subscription, "expected[%d] charge[%d] intent subscription present", expectedIdx, periodIdx) immediately before the assertions that read charge.Intent.Subscription.SubscriptionID and charge.Intent.Subscription.PhaseID in both helper blocks (the blocks that currently assert SubscriptionID and PhaseID) so a missing subscription yields a clean test failure instead of a panic.
72-548:⚠️ Potential issue | 🟡 MinorPlease add the unsupported-price scenario too.
This suite covers flat-fee, usage-based, mixed, and delete-failure flows, but it still doesn’t pin the new fail-fast branch for any other credits-only price type. A small non-
FlatPrice/non-UnitPricecase here would keep regressions from silently falling back into the wrong reconciliation path. As per coding guidelines,**/*_test.go: Make sure the tests are comprehensive and cover the changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go` around lines 72 - 548, Add a new test that covers the unsupported-price fail-fast branch: create a credits_only subscription like the other tests but use a price type that is neither productcatalog.FlatPrice nor productcatalog.UnitPrice (e.g., a Tiered/other price struct used by the catalog) when building the RateCard in createSubscriptionFromPlanAt, call Service.SynchronizeSubscription(ctx, subscriptionView, syncUntil) and assert it returns an error matching the unsupported-price/fail-fast message (similar to the delete-failure test which checks Service.SynchronizeSubscription error). Name the test e.g. TestCreditsOnlyUnsupportedPriceFailsFast and mirror the setup pattern used in TestCreditsOnlyFlatFeeProvisioningAndReconciliation to ensure the new branch is exercised.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 726-736: Replace the non-fatal assertion s.Len(parts, 5, ...) with
a fatal assertion to prevent a panic when indexing parts: call
s.Require().Len(parts, 5, "invalid child unique reference id format")
immediately after splitting childID into parts; leave the following
s.Equal(subscriptionID, parts[0], ...) and subsequent calls to
s.SubscriptionService.GetView(...) and s.getPhaseByKey(...).SubscriptionPhase.ID
unchanged so the test stops early on malformed childID instead of potentially
panicking when accessing parts[1].
---
Duplicate comments:
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 644-656: Tests assume charge.Intent.Subscription is non-nil before
accessing Subscription.SubscriptionID and Subscription.PhaseID; add a guard
using s.Require().NotNilf(charge.Intent.Subscription, "expected[%d] charge[%d]
intent subscription present", expectedIdx, periodIdx) immediately before the
assertions that read charge.Intent.Subscription.SubscriptionID and
charge.Intent.Subscription.PhaseID in both helper blocks (the blocks that
currently assert SubscriptionID and PhaseID) so a missing subscription yields a
clean test failure instead of a panic.
- Around line 72-548: Add a new test that covers the unsupported-price fail-fast
branch: create a credits_only subscription like the other tests but use a price
type that is neither productcatalog.FlatPrice nor productcatalog.UnitPrice
(e.g., a Tiered/other price struct used by the catalog) when building the
RateCard in createSubscriptionFromPlanAt, call
Service.SynchronizeSubscription(ctx, subscriptionView, syncUntil) and assert it
returns an error matching the unsupported-price/fail-fast message (similar to
the delete-failure test which checks Service.SynchronizeSubscription error).
Name the test e.g. TestCreditsOnlyUnsupportedPriceFailsFast and mirror the setup
pattern used in TestCreditsOnlyFlatFeeProvisioningAndReconciliation to ensure
the new branch is exercised.
🪄 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: 1a60ae0c-4fb3-4590-94bd-fe94328c04c0
📒 Files selected for processing (1)
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
dbee34e to
f3df2f5
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go (1)
33-35: Tiny cleanup: useIsEmpty()(or remove it) to keep this tidyNice to keep one style here—either call
parsed.IsEmpty()at Line 33 or drop the helper if you prefer direct checks.Suggested small cleanup
- if len(parsed.creates) == 0 { + if parsed.IsEmpty() { return nil }Also applies to: 78-80
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go` around lines 33 - 35, Replace the direct slice-length checks with the parsed.IsEmpty() helper (or remove the helper and standardize on direct checks) to keep style consistent: update the early-return condition that currently uses len(parsed.creates) == 0 to call parsed.IsEmpty(), and make the same change for the other occurrence that checks parsed.creates/parsed.deletes (the block around the later check that currently uses len(...) comparisons). Ensure you reference the parsed.IsEmpty() method and the parsed.creates/parsed.deletes fields in chargeupdate.go when making the change so both locations use the same approach.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.agents/skills/subscriptionsync/SKILL.md:
- Line 24: The fenced code block in SKILL.md is missing a language tag causing
markdownlint MD040; update the opening fence from ``` to a typed fence such as
```text (or another appropriate language) so the block reads ```text ... ``` to
satisfy the linter and keep the docs lint-clean.
---
Nitpick comments:
In
`@openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go`:
- Around line 33-35: Replace the direct slice-length checks with the
parsed.IsEmpty() helper (or remove the helper and standardize on direct checks)
to keep style consistent: update the early-return condition that currently uses
len(parsed.creates) == 0 to call parsed.IsEmpty(), and make the same change for
the other occurrence that checks parsed.creates/parsed.deletes (the block around
the later check that currently uses len(...) comparisons). Ensure you reference
the parsed.IsEmpty() method and the parsed.creates/parsed.deletes fields in
chargeupdate.go when making the change so both locations use the same approach.
🪄 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: 805a6041-1ed2-4738-9a3a-6ca761d7d170
📒 Files selected for processing (25)
.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/service.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.goopenmeter/billing/worker/subscriptionsync/service/reconciler/prorate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_test.goopenmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.gotest/credits/sanity_test.go
💤 Files with no reviewable changes (1)
- openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
✅ Files skipped from review due to trivial changes (3)
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
- test/credits/sanity_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
- openmeter/billing/charges/adapter/search.go
- openmeter/billing/worker/subscriptionsync/service/service.go
- openmeter/billing/charges/service.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
- openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
f3df2f5 to
9c5e7d8
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (1)
726-736:⚠️ Potential issue | 🟡 MinorUse
s.Require().Len()to fail fast on malformed child IDs.
s.Len(parts, 5, ...)is non-fatal — if the format check fails, the test continues and may panic when accessingparts[1]on line 736. Switching tos.Require().Len()stops execution immediately, which is the safer pattern (and matches what you do elsewhere in the codebase).Suggested fix
parts := strings.Split(childID, "/") - s.Len(parts, 5, "invalid child unique reference id format") + s.Require().Len(parts, 5, "invalid child unique reference id format") s.Equal(subscriptionID, parts[0], "child unique reference id subscription id")🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go` around lines 726 - 736, The test uses a non-fatal assertion for the childID format which can lead to a panic when parts[1] is accessed; replace the non-fatal check s.Len(parts, 5, ...) with a fatal assertion s.Require().Len(parts, 5, ...) so the test stops immediately on malformed child IDs before calling SubscriptionService.GetView and getPhaseByKey.
🧹 Nitpick comments (2)
openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go (1)
206-213: Minor: redundant nil check forpatchCollections.Lines 211-213 check if
patchCollections == nil, butnewPatchCollectionRouter(line 206) should never return a nil router whenerr == nil. If it could, that would be a bug in the router constructor. This check is defensive but likely unnecessary.Not a blocker — just a small observation.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go` around lines 206 - 213, The nil-check for patchCollections after calling newPatchCollectionRouter is redundant because newPatchCollectionRouter should either return a valid router or an error; remove the defensive block that returns fmt.Errorf("patch patchCollectionRouter is nil") or alternatively update newPatchCollectionRouter to guarantee it never returns (nil, nil) and instead returns an error when it cannot construct the router; reference patchCollections and newPatchCollectionRouter in reconciler.go and choose one approach (remove check here or enforce non-nil in the constructor) so the code path never silently handles a nil router.openmeter/billing/worker/subscriptionsync/service/service.go (1)
62-62: Minor:chargesServicefield appears unused onServicestruct.The
chargesServiceis stored onService(line 62) and assigned (line 85), but the actual charges handling goes through the reconciler which receives it viareconciler.Config. If there's no planned direct usage onService, consider removing this field to reduce confusion.That said, if you're planning to use it for other methods later, keeping it is totally fine — just wanted to flag it.
Also applies to: 85-85
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/service.go` at line 62, The chargesService field on the Service struct is unused — remove the chargesService field declaration from the Service struct and stop assigning it in NewService (or any constructor) if you don't use it elsewhere; instead rely on reconciler.Config.ChargesService where the reconciler expects it (or keep the field only if you plan to add methods on Service that use chargesService later). Update Service (remove chargesService), NewService (remove assignment), and any tests or callers that pass chargesService into Service to use reconciler.Config or the reconciler constructor consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go`:
- Around line 726-736: The test uses a non-fatal assertion for the childID
format which can lead to a panic when parts[1] is accessed; replace the
non-fatal check s.Len(parts, 5, ...) with a fatal assertion
s.Require().Len(parts, 5, ...) so the test stops immediately on malformed child
IDs before calling SubscriptionService.GetView and getPhaseByKey.
---
Nitpick comments:
In `@openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go`:
- Around line 206-213: The nil-check for patchCollections after calling
newPatchCollectionRouter is redundant because newPatchCollectionRouter should
either return a valid router or an error; remove the defensive block that
returns fmt.Errorf("patch patchCollectionRouter is nil") or alternatively update
newPatchCollectionRouter to guarantee it never returns (nil, nil) and instead
returns an error when it cannot construct the router; reference patchCollections
and newPatchCollectionRouter in reconciler.go and choose one approach (remove
check here or enforce non-nil in the constructor) so the code path never
silently handles a nil router.
In `@openmeter/billing/worker/subscriptionsync/service/service.go`:
- Line 62: The chargesService field on the Service struct is unused — remove the
chargesService field declaration from the Service struct and stop assigning it
in NewService (or any constructor) if you don't use it elsewhere; instead rely
on reconciler.Config.ChargesService where the reconciler expects it (or keep the
field only if you plan to add methods on Service that use chargesService later).
Update Service (remove chargesService), NewService (remove assignment), and any
tests or callers that pass chargesService into Service to use reconciler.Config
or the reconciler constructor consistently.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 72d44201-dc9b-4fa6-9b18-e0e0391322e7
📒 Files selected for processing (25)
.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/charges/adapter/search.goopenmeter/billing/charges/service.goopenmeter/billing/charges/testutils/handlers.goopenmeter/billing/charges/testutils/service.goopenmeter/billing/worker/subscriptionsync/service/base_test.goopenmeter/billing/worker/subscriptionsync/service/creditsonly_test.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/persistedstate/loader.goopenmeter/billing/worker/subscriptionsync/service/reconcile.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeusagebased.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.goopenmeter/billing/worker/subscriptionsync/service/reconciler/prorate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/service.goopenmeter/billing/worker/subscriptionsync/service/sync_test.goopenmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.gotest/credits/sanity_test.go
💤 Files with no reviewable changes (1)
- openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
✅ Files skipped from review due to trivial changes (6)
- test/credits/sanity_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchchargeflatfee.go
- openmeter/billing/charges/testutils/handlers.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
- openmeter/billing/worker/subscriptionsync/service/sync_test.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
🚧 Files skipped from review as they are similar to previous changes (8)
- openmeter/billing/charges/adapter/search.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
- openmeter/billing/worker/subscriptionsync/service/reconcile.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
- openmeter/billing/charges/service.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/patch.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/billing/worker/subscriptionsync/service/service.go (1)
25-26: Tighten theChargesServicecontract wording.At Line 25, “required” reads stronger than the current behavior (nil is intentionally tolerated in staged rollout paths). I’d tweak the comment so callers don’t assume constructor-level hard requirement.
✏️ Suggested wording tweak
- // ChargesService is required for credit-only sync and charge-based provisioning. + // ChargesService enables credit-only sync and charge-based provisioning. + // If nil, charge-backed sync paths are skipped (staged rollout behavior). ChargesService charges.ServiceBased on learnings: In
openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go, nilchargeServiceintentionally returns empty results to support staged rollout.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/billing/worker/subscriptionsync/service/service.go` around lines 25 - 26, The field comment for ChargesService is too strong—change the wording on the ChargesService field (ChargesService in service.go) to indicate it is optional / may be nil during staged rollouts rather than "required"; note that when nil the code (see persistedstate/loader.go) intentionally returns empty results to support staged rollout, so update the comment to say something like "optional; nil tolerated during staged rollout (nil causes empty-result behavior)" to avoid implying a constructor-level requirement.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/billing/worker/subscriptionsync/service/service.go`:
- Around line 25-26: The field comment for ChargesService is too strong—change
the wording on the ChargesService field (ChargesService in service.go) to
indicate it is optional / may be nil during staged rollouts rather than
"required"; note that when nil the code (see persistedstate/loader.go)
intentionally returns empty results to support staged rollout, so update the
comment to say something like "optional; nil tolerated during staged rollout
(nil causes empty-result behavior)" to avoid implying a constructor-level
requirement.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f5e2d9c9-d26d-4009-906e-8993af9fd5b0
📒 Files selected for processing (8)
.agents/skills/charges/SKILL.md.agents/skills/subscriptionsync/SKILL.mdopenmeter/billing/worker/subscriptionsync/service/persistedstate/item.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.goopenmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.goopenmeter/billing/worker/subscriptionsync/service/reconciler/patch.goopenmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.goopenmeter/billing/worker/subscriptionsync/service/service.go
✅ Files skipped from review due to trivial changes (3)
- .agents/skills/charges/SKILL.md
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
- .agents/skills/subscriptionsync/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
- openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
Overview
This refactor moves
subscriptionsyncfurther toward its intended role as the bridge between subscription state and billing state. It introduces a package-owned persisted-state abstraction, removes direct dependence on rawbilling.LineOrHierarchyvalues in the sync pipeline, and makes persisted items explicitly typed as invoice lines, split-line groups, flat-fee charges, or usage-based charges.Charges are now loaded into the same
ByUniqueIDreconciliation universe as invoice-backed artifacts, so existing charge-backed items participate in diffing instead of being invisible to sync. On top of that, the reconciler now routes patch planning by backend and persisted item type, with separate invoice and charge patch collections and a newchargeupdaterpath for provisioning charges.Credit-only routing is also now explicit and safer. Flat prices provision flat-fee charges, unit prices provision usage-based charges, and unsupported credit-only price types fail early instead of silently falling back to invoice logic. This change also fixes a real persistence bug where plan
SettlementModewas not being stored, which causedcredit_onlyplans to rehydrate ascredit_then_invoiceand misroute during sync.The test suite was expanded as part of the refactor.
subscriptionsync/servicenow has a reusable base suite plus dedicated credit-only scenarios covering flat-fee provisioning and reconciliation, usage-based provisioning and reconciliation, mixed-mode provisioning, and the current expected unsupported-delete behavior for charge-backed reconciliation.Notes for reviewer
Summary by CodeRabbit
New Features
Documentation
Tests