Skip to content

feat: subs sync charge create - #4024

Merged
turip merged 14 commits into
mainfrom
feat/subs-sync-charge-create
Mar 31, 2026
Merged

turip merged 14 commits into
mainfrom
feat/subs-sync-charge-create

Conversation

@turip

@turip turip commented Mar 28, 2026 •

Copy link
Copy Markdown
Member

Overview

This refactor moves subscriptionsync further 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 raw billing.LineOrHierarchy values 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 ByUniqueID reconciliation 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 new chargeupdater path 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 SettlementMode was not being stored, which caused credit_only plans to rehydrate as credit_then_invoice and misroute during sync.

The test suite was expanded as part of the refactor. subscriptionsync/service now 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

    • Support for creating and reconciling flat-fee and usage-based charges as part of subscription synchronization; charge patches can be routed and applied to a charge backend.
    • Charges list API supports filtering by subscription ID and charge type.
  • Documentation

    • Added a comprehensive developer guide describing subscription→billing reconciliation semantics, routing rules, and testing guidance.
  • Tests

    • New test utilities and extensive credit-only and reconciliation test suites added.

@coderabbitai

coderabbitai Bot commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
Charges API & Adapter
openmeter/billing/charges/service.go, openmeter/billing/charges/adapter/search.go
Added optional SubscriptionIDs and ChargeTypes filters to ListCharges input/validation and applied corresponding adapter query constraints.
Charges Test Utilities
openmeter/billing/charges/testutils/service.go, openmeter/billing/charges/testutils/handlers.go
New test wiring: chargestestutils.NewServices to construct a charges test stack and MockHandlers providing deterministic mock charge handlers for tests.
Persisted-state: items & loader
openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go, .../loader.go
Introduced ItemType enum and charge-backed Item implementations; Loader optionally loads charges via charges.Service, converts charges to persisted Items, merges into persisted state, and enforces unique-ID collision rules.
Reconciler core & wiring
openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go, .../reconcile.go, .../service.go
Wired ChargesService into reconciler/service Config, added charge updater (disabled by default), collected/apply charge patches alongside invoice patches, and adjusted in-scope filtering/proration to be backend-aware.
Patch model & routing
openmeter/billing/worker/subscriptionsync/service/reconciler/patch.go, .../patchinvoice.go, .../prorate.go
Added BackendType (invoicing vs charges), charge patch interfaces/collections, routing for persisted item types, and limited semantic proration to invoicing backend.
Charge patch collections
.../patchcharge.go, .../patchchargeflatfee.go, .../patchchargeusagebased.go
New charge patch collections (generic, flat-fee, usage-based) that build create-only charge intents from target state and reject unsupported ops (delete/shrink/extend/prorate).
Charge updater & patch model
.../chargeupdater/service.go, .../patch.go, .../chargeupdate.go, .../disabled.go
New chargeupdater.Updater interface, Patch model (create-only), concrete updater that calls charges.Service.Create, and a disabled updater that errors when patches are present.
Charge intent helpers
openmeter/billing/worker/subscriptionsync/service/reconciler/patchcharge.go
Helpers to build charge intent base from target state and concrete generic ChargePatch implementations used by charge collections.
Reconciler prorate semantics
openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
Switched proration branching to use persisted-state item types and updated error messaging accordingly.
Tests: base & suites
openmeter/billing/worker/subscriptionsync/service/base_test.go, .../creditsonly_test.go, .../sync_test.go, .../syncbillinganchor_test.go, test/credits/sanity_test.go
Refactored test base to include Charges service and context helpers, added heavy CreditsOnlySubscriptionHandlerTestSuite with multiple scenarios, removed several lifecycle overrides, and switched tests to use consolidated charges test wiring.
Documentation / Skills
.agents/skills/subscriptionsync/SKILL.md, .agents/skills/charges/SKILL.md
Added detailed subscriptionsync SKILL documenting contract, control flow, gating rules, and tests; updated charges SKILL to clarify charge-backed proration guidance.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly Related PRs

Suggested Reviewers

  • tothandras
  • GAlexIHU
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: subs sync charge create' directly reflects the main change: adding charge creation support to the subscription synchronization pipeline.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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/subs-sync-charge-create

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 and usage tips.

@turip

turip commented Mar 29, 2026

Copy link
Copy Markdown
Member Author

depends on #4026

@turip turip added release-note/feature Release note: Exciting New Features area/billing area/subscriptions labels Mar 30, 2026
@turip
turip marked this pull request as ready for review March 30, 2026 07:41
@turip
turip requested a review from a team as a code owner March 30, 2026 07:41

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

🧹 Nitpick comments (4)
openmeter/subscription/workflow/service/addon_test.go (1)

554-566: Consider a helper here instead of rebuilding the whole PlanMeta.

This literal already had to grow just to carry SettlementMode, and the same thing will happen again the next time productcatalog.PlanMeta gets 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 (its instead of it's, and patches are instead of patches 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 on patchesParsed doesn'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 text or 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

📥 Commits

Reviewing files that changed from the base of the PR and between 155027e and 1da9a47.

📒 Files selected for processing (37)
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go
  • openmeter/billing/worker/subscriptionsync/service/reconcile.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch.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
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
  • openmeter/productcatalog/addon/adapter/mapping.go
  • openmeter/productcatalog/plan/adapter/adapter_test.go
  • openmeter/productcatalog/plan/adapter/plan.go
  • openmeter/productcatalog/plan/assert.go
  • openmeter/productcatalog/plan/service/plan.go
  • openmeter/productcatalog/plan/service/service_test.go
  • openmeter/productcatalog/testutils/plan.go
  • openmeter/subscription/addon/diff/restore_test.go
  • openmeter/subscription/service/sync.go
  • openmeter/subscription/testutils/builder.go
  • openmeter/subscription/workflow/service/addon_test.go
  • openmeter/subscription/workflow/service/subscription_test.go
  • test/credits/sanity_test.go
💤 Files with no reviewable changes (1)
  • openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go

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

♻️ Duplicate comments (2)
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (2)

644-656: ⚠️ Potential issue | 🟡 Minor

Guard Intent.Subscription before dereferencing it.

The lookup now fails fast, but both helpers still assume charge.Intent.Subscription is always present. If a matching charge comes back without subscription linkage, SubscriptionID / PhaseID turns this into a panic instead of a clean test failure. A s.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 | 🟡 Minor

Please 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-UnitPrice case 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1da9a47 and dbee34e.

📒 Files selected for processing (1)
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go

@turip
turip force-pushed the feat/subs-sync-charge-create branch from dbee34e to f3df2f5 Compare March 30, 2026 11:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go (1)

33-35: Tiny cleanup: use IsEmpty() (or remove it) to keep this tidy

Nice 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

📥 Commits

Reviewing files that changed from the base of the PR and between dbee34e and f3df2f5.

📒 Files selected for processing (25)
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go
  • openmeter/billing/worker/subscriptionsync/service/reconcile.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch.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
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
  • test/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

@turip
turip requested review from GAlexIHU and tothandras March 30, 2026 15:26
@turip
turip force-pushed the feat/subs-sync-charge-create branch from f3df2f5 to 9c5e7d8 Compare March 30, 2026 15:42

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

♻️ Duplicate comments (1)
openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go (1)

726-736: ⚠️ Potential issue | 🟡 Minor

Use 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 accessing parts[1] on line 736. Switching to s.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 for patchCollections.

Lines 211-213 check if patchCollections == nil, but newPatchCollectionRouter (line 206) should never return a nil router when err == 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: chargesService field appears unused on Service struct.

The chargesService is stored on Service (line 62) and assigned (line 85), but the actual charges handling goes through the reconciler which receives it via reconciler.Config. If there's no planned direct usage on Service, 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

📥 Commits

Reviewing files that changed from the base of the PR and between f3df2f5 and 9c5e7d8.

📒 Files selected for processing (25)
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/charges/adapter/search.go
  • openmeter/billing/charges/service.go
  • openmeter/billing/charges/testutils/handlers.go
  • openmeter/billing/charges/testutils/service.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/creditsonly_test.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go
  • openmeter/billing/worker/subscriptionsync/service/reconcile.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/disabled.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/patch.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch.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
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patchinvoice.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/prorate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/service.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/billing/worker/subscriptionsync/service/syncbillinganchor_test.go
  • test/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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
openmeter/billing/worker/subscriptionsync/service/service.go (1)

25-26: Tighten the ChargesService contract 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.Service

Based on learnings: In openmeter/billing/worker/subscriptionsync/service/persistedstate/loader.go, nil chargeService intentionally 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c5e7d8 and 305ea21.

📒 Files selected for processing (8)
  • .agents/skills/charges/SKILL.md
  • .agents/skills/subscriptionsync/SKILL.md
  • openmeter/billing/worker/subscriptionsync/service/persistedstate/item.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/chargeupdate.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/chargeupdater/service.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/patch.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/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

@turip
turip merged commit 3a223c3 into main Mar 31, 2026
34 of 36 checks passed
@turip
turip deleted the feat/subs-sync-charge-create branch March 31, 2026 08:25

This branch was previously deployed

1 inactive deployment
dev — 305ea219 Deployed Mar 31, 2026 by turip via Migration Checks #13018
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