Skip to content

fix(billing): preserve charge history during subscription item changes - #5223

Merged
turip merged 3 commits into
mainfrom
fix/charge-recreation
Sep 30, 2026
Merged

turip merged 3 commits into
mainfrom
fix/charge-recreation

Conversation

@turip

@turip turip commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Overview

Subscription sync can see a new physical subscription item ID for an existing logical item. When its subscription-owned billing terms are equivalent, sync now repairs the charge reference and reconciles period changes in place. This preserves the charge and its invoice history across nonfinancial edits.

When changed terms or an incompatible service-period start require replacement, sync checks all charge realizations, including prior and deleted runs, against their invoices before planning the replacement. An immutable invoice, missing invoice, or failed lookup blocks replacement before any patches are applied. Cancellation deletes and ordinary period adjustments continue through their existing paths.

Notes for reviewer

  • Billing-term comparison runs only when the physical reference changes. Matching references continue through ordinary period reconciliation.
  • The service regression constructs a modified subscription view and verifies rejection before application. Charge IDs and references, invoice lines and totals, and invoice count remain unchanged. It does not exercise a persisted subscription edit or rollback after patch application.
  • Validation: make test-nocache passed before the final callback inlining (9,054 passed, 9 skipped); the scoped make lint-go-fast passed afterward with 0 issues.

Summary by CodeRabbit

  • Bug Fixes
    • Subscription reconciliation now replaces charges only when billing terms differ; equivalent terms allow reference repairs and period updates.
    • Replacement is blocked when prior invoices are immutable or invoice history cannot be verified.
    • Matched charges are checked for subscription ownership, and omitted flat-fee payment terms follow the catalog default for comparison and invoice timing.
    • Historical paid charges and invoice lines remain intact during cancellation-driven reconciliation.

RetriggerConfidence Score: 4/5

The PR does not appear ready to merge because existing and new periods can still receive different invoice schedules, and the new reconciliation subtests must satisfy the repository’s testing convention.

Fix All in Claude CodeFindings

  1. P1 Inconsistent invoice timing ▶
  2. P2 Missing subtest intent comments ▶
  3. P2 Persisted edits remain untested ▶
Fix with agent prompt
### Issue 1
openmeter/billing/worker/subscriptionsync/service/targetstate/phaseiterator.go:84-91
If an existing flat-fee subscription has an empty payment term, this change schedules new periods at their start. But when an existing charge has the same physical reference and service period, reconciliation leaves its previously stored end-of-period invoice time unchanged. The same subscription can therefore invoice existing and new periods under different schedules.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 2
openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare_test.go:1172
The new reconciliation subtests exercise non-trivial service behavior but start directly with setup. The repository requires these subtests to begin with concise `given`, `when`, and `then` intent comments. Add them before merging so the setup and expected outcome are clear; the usage and reference-repair subtests have the same issue.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

### Issue 3
openmeter/billing/worker/subscriptionsync/service/sync_regression_test.go:702-713
This test changes the item ID and price only in a fetched view, then checks that sync rejects it. It does not cover how a real saved subscription edit produces that view or what happens to the edit after rejection. A regression in either path could pass this test; a service-backed edit test would close that gap.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR changes subscription sync to preserve matched charges when physical item references change but billing terms remain equivalent. It also checks realization invoices before planning charge replacement.

  • Adds ownership validation and billing-term comparisons for flat-fee and usage-based charges.
  • Adds replacement guards and regression coverage for paid invoice history.
  • Applies the default payment term when scheduling flat-fee invoices.
Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Matched subscription item and charge] --> B{Physical reference changed?}
  B -- No --> P[Reconcile service period]
  B -- Yes --> C{Billing terms equivalent and period start compatible?}
  C -- Yes --> D[Repair reference]
  D --> P
  C -- No --> E[Check realization invoices]
  E -- All mutable --> F[Plan charge replacement]
  E -- Immutable, missing, or lookup failure --> G[Reject replacement]
Loading

Reviews (2) · Last reviewed commit: "style(billing): format charge replacemen..."

@turip
turip requested a review from a team as a code owner September 30, 2026 10:17
@coderabbitai

coderabbitai Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: openmeterio/openmeter/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 4dc2894b-e5a4-44ad-8306-a5594d2fdc29

📥 Commits

Reviewing files that changed from the base of the PR and between d6537cb and 0c66bc7.

📒 Files selected for processing (10)
  • openmeter/billing/worker/subscriptionsync/README.md
  • openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/charge_replacement_guard.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/charge_replacement_guard_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/sync_regression_test.go
  • openmeter/billing/worker/subscriptionsync/service/targetstate/phaseiterator.go
  • openmeter/billing/worker/subscriptionsync/service/targetstate/phaseiterator_test.go
  • test/billing/suite.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

Subscription sync now matches flat-fee and usage-based charges by selected billing terms. It validates matched-charge ownership and checks realization invoices before replacement. The change also updates default flat-fee invoice timing and adds reconciliation and sync regression coverage.

Changes

Subscription charge reconciliation

Layer / File(s) Summary
Billing-term comparison
openmeter/billing/worker/subscriptionsync/README.md, openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare.go, openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare_test.go
Flat-fee and usage-based charges are compared by selected billing terms. Tests cover compared fields, excluded fields, defaults, and reference-repair outcomes.
Reconciliation and replacement guards
openmeter/billing/worker/subscriptionsync/README.md, openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go, openmeter/billing/worker/subscriptionsync/service/reconciler/charge_replacement_guard.go, openmeter/billing/worker/subscriptionsync/service/reconciler/charge_compare_test.go, openmeter/billing/worker/subscriptionsync/service/reconciler/charge_replacement_guard_test.go
Matched-charge reconciliation validates ownership. Before replacement, it checks realization-linked invoices and returns errors for immutable invoices, incomplete invoice results, or lookup failures. Tests cover replacement, reference repair, and period changes.
Sync regressions and invoice timing
openmeter/billing/worker/subscriptionsync/service/sync_regression_test.go, openmeter/billing/worker/subscriptionsync/service/targetstate/phaseiterator.go, openmeter/billing/worker/subscriptionsync/service/targetstate/phaseiterator_test.go, test/billing/suite.go
Regression tests check retained paid history during cancellation and blocked replacement. Flat-fee invoice timing uses the catalog default when the payment term is empty. BaseSuite gains RequireRun for required subtests.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix

Suggested reviewers: chrisgacsal

Merge Risk: ⚪ Minimal · up to 0c66b

The change preserves charge history and blocks replacement when invoice history is immutable or incomplete. No concrete blocking issue remains; merge after normal checks pass.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0c66b

The change strengthens ownership checks and protects immutable invoice history before replacing charges. No expanded external access or demonstrated security regression was found. Risk remains limited but nonzero because recovery from interrupted updates and the complete rollback scope were not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected mutation path is bounded to the synchronized customer's charges and their linked invoices within a namespace. Subscription-edit inputs can influence reference and financial reconciliation decisions, but the changed flow does not itself grant cross-customer, cross-subscription, or cross-namespace authority.

Trust Boundaries and Controls

  • observed — The new matched-charge validator rejects manually managed charges, customer mismatches, absent subscription ownership, and root subscription reassignment. Downstream charge application additionally validates customer and namespace ownership.
  • observed — Replacement checks include current, prior, and deleted realization history and deleted invoices. Any returned immutable invoice rejects replacement before patch application.

Resilience and Maintainability Implications

  • observed — Both synchronization and the inspected invoice-advancement path use the customer-lock transaction helper. That helper holds an update lock while running its callback, providing concrete serialization counterevidence to the suspected guard-to-application race for this advancement path.

Hardening Proposals

  • proposed — Validate the complete combined reference-repair and period-update transition with injected failures after reference application and concurrent invoice advancement, checking rollback, retry convergence, and externally visible financial effects. This is assurance work, not an observed defect.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: preserving charge history when subscription items change.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@turip turip added release-note/bug-fix Release note: Bug Fixes area/billing labels Sep 30, 2026
@turip
turip enabled auto-merge (squash) September 30, 2026 11:05
@turip
turip merged commit 72c0e47 into main Sep 30, 2026
29 checks passed
@turip
turip deleted the fix/charge-recreation branch September 30, 2026 11:29
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