Skip to content

refactor(subscriptionsync): simplify reconciliation scheduling - #5561

Merged
turip merged 1 commit into
feat/subscription-sync-active-reconciliationfrom
refactor/subscription-sync-simplify-reconciliation
Nov 17, 2026
Merged

turip merged 1 commit into
feat/subscription-sync-active-reconciliationfrom
refactor/subscription-sync-simplify-reconciliation

Conversation

@turip

@turip turip commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Stacked on #5555. Simplifies how a successful sync decides its recorded state and next reconciliation deadline, without changing the v2 outcomes that PR introduces.

What changes

  • One scheduling function. nextReconciliationAt(period, billingEndsAt, fraction) in sync.go replaces calculateNextBillingPeriod and getNextReconciliationAt, together with their input structs and Validate methods. If the period reaches the effective billing end, the deadline is exactly that end; otherwise it is a point 80–95% through the period.
  • State and deadline decided together. A single switch after the dry-run return picks ended, no_billables, or active plus its deadline.
  • NextBillingPeriod removed from targetstate.State and reconciler.Plan. Sync resolves the billing period at the generation limit itself; only BillingEndsAt still flows from the target. A nil period no longer has three meanings.
  • Shared validation. SyncStateV2.Validate and RecordSyncResultV2Input.Validate call one validateNextReconciliationAt method. Error messages are unchanged.

Behavior change

The "jitter point already passed, use the period end" fallback is gone, along with the past-deadline warning. The fallback only applied when AsOf lags the worker clock, and every production caller passes the current time or the future ActiveTo. A sync with a stale AsOf now leaves a deadline in the past, which keeps the subscription due until a sync with a current AsOf catches up. This is the same behavior the README already documents for a historical AsOf.

Tests

  • TestNextReconciliationAt is a pure table on the new function and absorbs the cases from TestNextBillingPeriodForMidPeriodCustomerDeletion.
  • sync_state_test.go shrinks from 1,054 to 766 lines through forEachBackend, useNewCustomer, requireUnscheduled, and a merged requireFees.
  • TestCustomerDeletionReconciliation keeps 5 of 8 cases per backend. The three removed cases checked how the worker clock and AsOf decide between active and ended, which TestEndedSubscriptionSyncResult already covers for ActiveTo through the same BillingEndsAt value.
  • Removed TestNilPlanPreservesPreviousSyncResult (the nil-plan guard stays) and TestNextReconciliationAtRequiresPeriodOrEnd (the period is no longer optional).
  • createSubscriptionForRevisionChange moves back to sync_test.go, and the adapter's per-state "clears the deadline" loop becomes one case because the upsert does not branch on state.

Validation

Before trimming any tests, the original integration matrix from #5555 ran unchanged against the simplified code and passed. PostgreSQL-backed ./openmeter/billing/worker/subscriptionsync/... tests pass, the root module builds, and golangci-lint reports no issues for the package.

🤖 Generated with Claude Code

RetriggerView in GreptileConfidence Score: 5/5

This PR appears safe to merge; no actionable issues were found.

Summary

Simplifies how subscription sync records its result and next deadline.

  • Subscription sync now chooses its outcome and deadline together.
  • Both sync-state checks now use one rule for reconciliation deadlines.

Past deadlines after historical syncs: turip explicitly describes removing the fallback as intentional so historical work stays due.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Apply billing changes] --> B{Dry run?}
  B -->|Yes| C[Return without saving sync state]
  B -->|No| D[Update legacy scheduling]
  D --> E{Choose result}
  E -->|Deletion cleanup| F[Keep cleanup result]
  E -->|Clock and horizon reach billing end| G[Record ended]
  E -->|No billables| H[Record no_billables]
  E -->|Otherwise| I[Resolve billing period]
  I --> J{Period reaches billing end?}
  J -->|Yes| K[Use exact billing end]
  J -->|No| L[Choose deadline 80–95% through period]
  K --> M[Record active with deadline]
  L --> M
Loading

Reviews (1) · Last reviewed commit: "refactor(subscriptionsync): simplify rec..." · Reviewed by Greptile

Summary by CodeRabbit

  • Behavior Updates
    • Active subscription sync results now receive a reconciliation deadline based on the billing period: at the billing end when the period reaches it, or at a point 80–95% through the period otherwise.
    • Ended and other non-active results do not retain an active reconciliation deadline. Historical sync timestamps may result in deadlines in the past.
  • Documentation
    • Updated subscription sync documentation to describe deadline selection and the continued use of legacy scheduling for periodic candidate selection.

Decide the recorded state and the next reconciliation deadline in one
place in sync, and compute the deadline with a single pure function
instead of two helpers split across the target state and sync.

- Remove NextBillingPeriod from the target state and the plan; sync
  resolves the billing period at the generation limit itself. Only
  BillingEndsAt still flows from the target.
- Drop the "jitter point already passed, use the period end" fallback.
  It only applied when AsOf lags the worker clock; such a sync now
  leaves a past deadline that stays due, like any historical AsOf.
- Drop the past-deadline warning and validation of values sync
  produces itself.
- Share the deadline rule between SyncStateV2 and
  RecordSyncResultV2Input validation.
- Trim the sync state tests with shared helpers and remove cases that
  duplicate TestEndedSubscriptionSyncResult.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@turip
turip requested a review from a team as a code owner November 17, 2026 15:30
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Subscription sync no longer carries a precomputed next billing period. It selects the result state after reconciliation and schedules active results from the aligned billing period, with billing-end handling and 80–95% jitter. Tests cover the updated behavior across legacy billing and charges.

Changes: Subscription sync reconciliation

Layer / File(s) Summary
Remove precomputed billing-period scheduling
openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.go, openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go, openmeter/billing/worker/subscriptionsync/service/sync.go
The target state and reconciler no longer carry a precomputed next billing period. The sync service calculates a deadline from the aligned billing period and billing end, using an 80–95% point when the billing end does not fall within or before the period end.
Select sync result state and deadline
openmeter/billing/worker/subscriptionsync/service/sync.go, openmeter/billing/worker/subscriptionsync/syncstatev2.go, openmeter/billing/worker/subscriptionsync/README.md
After reconciliation, the sync service selects the result state and schedules active results. Shared validation requires a non-zero deadline for active results and no deadline for other states. The README describes the scheduling and state rules.
Test state and deadline behavior
openmeter/billing/worker/subscriptionsync/service/sync_state_test.go, openmeter/billing/worker/subscriptionsync/service/sync_test.go, openmeter/billing/worker/subscriptionsync/service/base_test.go, openmeter/billing/worker/subscriptionsync/adapter/syncstatev2_test.go
Tests cover deadline selection, result states, retries, and fee periods across legacy billing and charges. Subscription fixtures and shared test helpers are updated. The adapter test checks that an ended result clears the existing deadline.

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant SyncService
  participant Reconciler
  participant SyncStateV2
  SyncService->>Reconciler: Reconcile subscription
  Reconciler-->>SyncService: Return billing plan
  SyncService->>SyncService: Select result state and deadline
  SyncService->>SyncStateV2: Record state and deadline
Loading

Possibly related PRs

  • openmeterio/openmeter#5555: This PR is stacked on #5555 and replaces its scheduling functions and updates the related deadline validation and state selection.

Suggested reviewers: galexihu, borosr, chrisgacsal

Merge Risk: Minimal · up to 9bcf1

No actionable scheduling defect was established. The change is mergeable after normal checks and adding the required release-note or change-kind label.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the refactor type and the scope, and it matches the main change. The PR replaces the separate next-billing-period and reconciliation-time helpers with one pure nextReconciliationAt fun…
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.
Full details: Title check

Explanation

The title names the refactor type and the scope, and it matches the main change. The PR replaces the separate next-billing-period and reconciliation-time helpers with one pure nextReconciliationAt function. It also moves state and deadline selection into sync and removes NextBillingPeriod from targetstate.State and reconciler.Plan. The title is short, specific, and free of noise. It does not name the removed NextBillingPeriod field or the behavior change for stale AsOf values, but it does not need to cover every detail.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3aefde4 and 9bcf1e8.

Files selected for processing: 9

  • openmeter/billing/worker/subscriptionsync/README.md
  • openmeter/billing/worker/subscriptionsync/adapter/syncstatev2_test.go
  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/sync.go
  • openmeter/billing/worker/subscriptionsync/service/sync_state_test.go
  • openmeter/billing/worker/subscriptionsync/service/sync_test.go
  • openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.go
  • openmeter/billing/worker/subscriptionsync/syncstatev2.go
Files with no reviewable changes: 3

  • openmeter/billing/worker/subscriptionsync/service/base_test.go
  • openmeter/billing/worker/subscriptionsync/service/reconciler/reconciler.go
  • openmeter/billing/worker/subscriptionsync/service/targetstate/targetstate.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.

@turip turip added the kind/refactor Code refactor, cleanup or minor improvement label Nov 17, 2026
@turip
turip merged commit 857ab68 into feat/subscription-sync-active-reconciliation Nov 17, 2026
31 of 32 checks passed
@turip
turip deleted the refactor/subscription-sync-simplify-reconciliation branch November 17, 2026 15:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/refactor Code refactor, cleanup or minor improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant