Skip to content

feat(billing): add subscription sync v2 state persistence - #5514

Merged
turip merged 3 commits into
mainfrom
codex/subscription-sync-state-v2
Nov 13, 2026
Merged

turip merged 3 commits into
mainfrom
codex/subscription-sync-state-v2

Conversation

@turip

@turip turip commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Overview

Add a separate subscription sync v2 table to record the last successful reconciliation result and completion time, initially supporting subscription_deleted. A missing row means no successful v2 reconciliation has been recorded.

The Ent schema uses the shared subscriptionsync enum, namespace/subscription uniqueness, and a subscription foreign key with cascading hard deletion. TimeMixin supplies row timestamps; its deleted_at field is currently unused. Adapter reads return SyncStateV2Managed with row identity and timestamps, and transaction-aware upserts preserve created_at while refreshing updated_at.

Notes for reviewer

Builds on the merged #5512 and is rebased onto current main. This PR adds persistence only: the sync service and periodic reconciler do not yet use v2 state, and the deleted-subscription filter is unchanged.

Validation: PostgreSQL adapter tests cover managed metadata, repeated upserts, namespace isolation, rollback, foreign-key enforcement, and cascading deletion. Ent generation, Atlas migration validation, scoped go vet, make lint-go-fast, and git diff --check passed; the adapter test and fast lint were rerun after rebasing.

Summary by CodeRabbit

  • New Features
    • Added storage and retrieval for a second version of subscription sync results, recording the last successful result and completion time.
    • Results are associated with the correct subscription and namespace, and are removed when a subscription is permanently deleted.
    • The supported result includes subscription_deleted; no record means no successful v2 reconciliation has been recorded.
    • Existing sync services and periodic reconciliation do not yet use this state.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; no actionable issues remain in the reviewed changes.

Summary

Adds separate storage for the last successful v2 subscription reconciliation.

  • Callers can save completed subscription cleanup results as v2 sync state.

The latest changes preserve validation behavior and split persistence tests into focused subtests. No new actionable issues were found. Tests were not run during this review.

Reviews (3) · Last reviewed commit: "refactor(billing): address sync state v2..." · Reviewed by Greptile

@turip
turip requested a review from a team as a code owner November 13, 2026 15:07
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

This change adds a v2 subscription sync-state contract and a separate database table. The adapter can retrieve and transactionally upsert v2 states. The sync service and periodic reconciler do not yet use v2 state.

Changes: Subscription Sync State V2

Layer / File(s) Summary
Define the v2 sync-state contract
openmeter/billing/worker/subscriptionsync/syncstatev2.go, openmeter/billing/worker/subscriptionsync/adapter.go
Defines subscription_deleted, v2 state records, validation, and the adapter interface. Adapter now embeds the v2 interface.
Define v2 sync-state storage
openmeter/ent/schema/subscriptionsyncstatev2.go, openmeter/ent/schema/subscription.go, tools/migrate/migrations/20261113145833_subscription_sync_state_v2.*.sql
Adds the v2 sync-state schema and subscription relationship. The migrations create and remove the table and its indexes.
Implement and test v2 adapter operations
openmeter/billing/worker/subscriptionsync/adapter/syncstatev2.go, openmeter/billing/worker/subscriptionsync/adapter/syncstatev2_test.go, openmeter/billing/worker/subscriptionsync/README.md
Adds namespaced state retrieval and transactional upsert operations. Integration tests cover persistence, timestamp handling, namespace matching, rollback, and deletion. The README describes v2 state behavior and current service usage.

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

Change: Feature

Suggested reviewers: galexihu

Merge Risk: Minimal · up to bf213

This change adds persistence for subscription sync state v2 without changing current sync behavior. No concrete merge-blocking risk was identified.

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 "feat(billing): add subscription sync v2 state persistence" matches the main change. The PR adds a separate v2 sync-state table, Ent schema, migration, and adapter methods for reading and up…
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 "feat(billing): add subscription sync v2 state persistence" matches the main change. The PR adds a separate v2 sync-state table, Ent schema, migration, and adapter methods for reading and upserting that state. The title is specific and concise. It does not mention that the sync service and reconciler still ignore v2 state, but the PR objectives say that is expected for this persistence-only change.

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 39fb382 and bf21379.

Files selected for processing: 2

  • openmeter/billing/worker/subscriptionsync/adapter/syncstatev2_test.go
  • openmeter/billing/worker/subscriptionsync/syncstatev2.go

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

@turip turip added the kind/feature New feature or request label Nov 13, 2026 — with ChatGPT Codex Connector

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

No blockers from my side. A few things worth considering before the sync service starts building on this.

func (SubscriptionSyncStateV2) Fields() []ent.Field {
return []ent.Field{
field.String("subscription_id").NotEmpty().Immutable().Unique().SchemaType(map[string]string{dialect.Postgres: "char(26)"}),
field.Enum("last_success_state").GoType(subscriptionsync.SyncStateV2State("")),

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.

This makes ent/schema import the root subscriptionsync package. Since ent/db imports ent/schema, that root package can now never (transitively) import anything that reaches ent/db — and openmeter/subscription does. It works today only because the root package imports just pkg/models and pkg/framework/entutils, but it also holds service.go, so it seems likely to want subscription types at some point.

Could we move the enum to a leaf package to avoid the trap?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Keeping this in the root domain package follows the existing repository pattern: Ent schemas already use enums from root packages such as billing and ledger. The root package holds contracts and domain types, while the service implementation lives in the service subpackage. The dependency restriction is real, but it is consistent with that layering, so I would keep the enum here.

}

func (SubscriptionSyncStateV2) Mixin() []ent.Mixin {
return []ent.Mixin{entutils.IDMixin{}, entutils.NamespaceMixin{}, entutils.TimeMixin{}}

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.

TimeMixin adds a deleted_at column that is never used, and the FK cascade hard-deletes rows anyway. updated_at also nearly duplicates last_success_at.

Would explicit created_at/updated_at fields (or no row timestamps at all) be enough here, rather than shipping a dead column?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Using the standard TimeMixin is intentional for consistency with the other persisted models, including keeping deleted_at available if we introduce soft deletion later. updated_at and last_success_at have different meanings: the former records the row write, while the latter records reconciliation completion, so a delayed write or retry can make them differ. Keeping the mixin as-is.

// SyncStateV2Managed includes the sync-state row's identity and timestamps.
type SyncStateV2Managed struct {
SyncStateV2
models.NamespacedID

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.

Embedding models.NamespacedID (the row ID) next to SubscriptionID models.NamespacedID means state.ID / state.NamespacedID are the row's, not the subscription's — easy to pass by mistake where a subscription ID is expected.

Nothing consumes the row ID yet. Could we drop it until something needs it and return SyncStateV2 plus the timestamps?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I would keep the row identity in SyncStateV2Managed alongside its timestamps, consistent with our managed-model convention. SubscriptionID explicitly identifies the parent, while the embedded NamespacedID identifies the state row. The schema's existing ULID IDMixin is also intentional and stays in place. That schema decision is separate from whether we expose the row ID in the returned Go type; omitting it there would not change ID generation.

}

func (s SyncStateV2State) Validate() error {
if s != SyncStateV2StateSubscriptionDeleted {

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.

nit: this hardcodes the single value that Values() already lists, so the next state has to be added in two places. slices.Contains(s.Values(), string(s)) would keep them in sync.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in bf21379: validation now uses slices.Contains(s.Values(), string(s)), so Values() is the single source of supported states.

"github.com/openmeterio/openmeter/pkg/models"
)

func TestSyncStateV2Persistence(t *testing.T) {

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.

nit: this covers six scenarios in one function with three FreezeTime calls sharing state. Splitting into subtests would localize failures.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in bf21379: split this into six independent subtests, each with its own database fixture and scoped clock reset. The existing persistence, timestamp, namespace, rollback, foreign-key, and cascade coverage is preserved. All six PostgreSQL subtests and scoped formatting/fast lint passed.

tothandras
tothandras previously approved these changes Nov 13, 2026
@turip
turip merged commit 30e9947 into main Nov 13, 2026
32 checks passed
@turip
turip deleted the codex/subscription-sync-state-v2 branch November 13, 2026 16:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants