Skip to content

fix: preserve invoice backend for zero-amount artifacts - #4863

Merged
turip merged 3 commits into
mainfrom
agent/reproduce-zero-amount-engine-migration
Aug 6, 2026
Merged

turip merged 3 commits into
mainfrom
agent/reproduce-zero-amount-engine-migration

Conversation

@turip

@turip turip commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

What changed

Subscription reconciliation now determines zero-amount filtering from the backend that already owns the persisted artifact. A target backed by a legacy invoice line must still pass invoice-line realization; when proration rounds that target to zero, it behaves as absent and the legacy artifact is retired instead of being implicitly migrated to a charge.

Default charge routing remains unchanged for genuinely new subscription-sync identities.

Root cause

filterInScopeLines resolved every target through the current default backend before diff planning. If charge provisioning became available after an invoice-backed artifact had already been created, the target was classified as charge-backed and bypassed invoice-line realization. A prorated amount that rounded to zero could therefore survive filtering, causing reconciliation to delete the legacy line and create a zero-amount charge for the same identity.

Regression coverage

The integration test reproduces the transition with the production billing, subscription, charge, ledger, and PostgreSQL fixture stack:

  1. synchronize a credit-then-invoice subscription while only invoice-backed persistence is available;
  2. replace the flat-fee item shortly afterward so the old version prorates to zero;
  3. synchronize with charge provisioning enabled;
  4. verify the legacy invoice line is retired, no charge takes its identity, and the new item version is provisioned through charges.

Impact

This preserves stable backend ownership for existing subscription-sync artifacts and prevents an implicit invoice-to-charge migration when a legacy artifact recalculates to zero.

Validation

  • make test-nocache: 6791 tests passed, 9 skipped
  • reconciler package tests
  • focused credit-then-invoice regression
  • git diff --check

No Jira ticket: maintenance/reliability fix.

Summary by CodeRabbit

  • Bug Fixes
    • Preserved existing backend assignments during subscription reconciliation.
    • Correctly applied expected-line filtering to invoice-backed items.
    • Removed obsolete zero-value prorated invoice lines without creating unintended charges.
    • Ensured replacement subscription versions are provisioned with the correct flat-fee charge.

Greptile Summary

Subscription reconciliation now selects the backend already associated with a persisted artifact while retaining default routing for new identities.

  • Resolves existing targets through their persisted patch collection before zero-amount filtering.
  • Retires a zero-valued legacy invoice line without migrating its identity to a charge.
  • Adds integration coverage for replacing an invoice-backed flat-fee item after charge provisioning becomes available.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go Preserves persisted backend ownership during target filtering and uses default routing only for new reconciliation identities.
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go Adds end-to-end coverage for retiring a prorated legacy invoice line without creating a charge under the same identity.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  T[Subscription target] --> P{Persisted artifact exists?}
  P -->|Yes| E[Use persisted backend]
  P -->|No| D[Resolve default backend]
  E --> B{Backend type}
  D --> B
  B -->|Invoice| R[Realize expected invoice line]
  B -->|Charge| C[Keep billable target]
  R -->|Zero or absent| X[Treat target as absent and retire legacy line]
  R -->|Present| I[Reconcile invoice line]
  C --> Q[Reconcile charge]
Loading

Reviews (4): Last reviewed commit: "test: require dependent subscription syn..." | Re-trigger Greptile

Context used:

@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The reconciliation planner now passes persisted items to scope filtering. Existing targets use their persisted backend collection, while new targets resolve the default collection. An integration test covers zero-proration invoice-line retirement during migration to charge-backed provisioning.

Changes

Subscription reconciliation

Layer / File(s) Summary
Preserve persisted backend assignments
openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
Plan passes persisted items to filterInScopeLines. Existing targets use their persisted collection, while new targets resolve the default collection.
Validate zero-proration migration
openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go
The integration test verifies that a zero-valued legacy line is retired without charge migration and that the replacement creates a flat-fee charge.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • openmeterio/openmeter#4059: Modifies subscription synchronization to preserve the correct billing backend for invoice-pending lines and charge provisioning.
  • openmeterio/openmeter#4364: Extends zero-proration subscription-sync fixes and tests in the same synchronization area.
  • openmeterio/openmeter#4663: Adds subscription-sync integration coverage for invoice-line deletion and backend reconciliation.

Suggested reviewers: tothandras

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
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 the invoice backend for zero-amount artifacts.
✨ 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 agent/reproduce-zero-amount-engine-migration

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 force-pushed the agent/reproduce-zero-amount-engine-migration branch 3 times, most recently from 4c8fb94 to b1985e6 Compare August 6, 2026 13:02
@turip turip changed the title test: reproduce zero-amount invoice-to-charge migration fix: preserve invoice backend for zero-amount artifacts Aug 6, 2026
@turip turip added area/billing release-note/bug-fix Release note: Bug Fixes labels Aug 6, 2026
@turip
turip marked this pull request as ready for review August 6, 2026 13:03
@turip
turip requested a review from a team as a code owner August 6, 2026 13:03

@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/sync_credittheninvoice_test.go (1)

2479-2489: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Small robustness nit: use s.Require() where a failure cascades into a panic. Line 2489 uses s.NoError(err), which only marks the test failed. Execution continues to line 2530 and calls a method on invoiceBackedService. The same applies at line 2562: if EditRunning returns an error, editedSubView is a zero value, and editedSubView.Phases[0] at line 2564 panics with an index-out-of-range instead of reporting the real cause.

🧰 Suggested tightening
-	s.NoError(err)
+	s.Require().NoError(err)
 
 	subView := s.createSubscriptionFromPlan(plan.CreatePlanInput{
 	}, s.timingImmediate())
-	s.NoError(err)
+	s.Require().NoError(err)
 
 	usersVersions := editedSubView.Phases[0].ItemsByKey["users"]

Also applies to: 2547-2567

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

In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`
around lines 2479 - 2489, Replace the non-fatal assertions in this test with
required assertions wherever execution depends on success: use s.Require() for
the New(...) error before calling methods on invoiceBackedService, and for the
EditRunning result before indexing editedSubView.Phases. Preserve the existing
test flow while ensuring failures stop before dependent operations can panic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go`:
- Around line 2479-2489: Replace the non-fatal assertions in this test with
required assertions wherever execution depends on success: use s.Require() for
the New(...) error before calling methods on invoiceBackedService, and for the
EditRunning result before indexing editedSubView.Phases. Preserve the existing
test flow while ensuring failures stop before dependent operations can panic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 01c8dac5-d38d-4644-bc05-81c123a85a57

📥 Commits

Reviewing files that changed from the base of the PR and between ad57700 and b1985e6.

📒 Files selected for processing (2)
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/sync_credittheninvoice_test.go

@turip
turip force-pushed the agent/reproduce-zero-amount-engine-migration branch from b1985e6 to fb76334 Compare August 6, 2026 13:30
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@turip

turip commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

Addressed the CodeRabbit robustness feedback in fb76334: service construction and subscription edit failures now use fatal assertions before dependent calls/indexing. The focused subscription-sync regression and reconciler tests pass after rebasing onto the latest origin/main.

@turip
turip enabled auto-merge (squash) August 6, 2026 13:35
@turip
turip merged commit a0f015f into main Aug 6, 2026
27 checks passed
@turip
turip deleted the agent/reproduce-zero-amount-engine-migration branch August 6, 2026 13:38
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