Skip to content

feat: adopt legacy Ent databases into Atlas migrations - #4705

Merged
turip merged 2 commits into
mainfrom
feat/atlas-migration-adoption
Jul 14, 2026
Merged

turip merged 2 commits into
mainfrom
feat/atlas-migration-adoption

Conversation

@turip

@turip turip commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Summary

  • remove runtime Ent automigration support and make versioned Atlas migrations the default
  • add openmeter-jobs migrate adopt-ent as a one-time bridge for databases previously managed with postgres.autoMigrate: ent
  • freeze the Ent schema at commit 12ab7b082035f2f93972c7f98973c5502107c157, reconcile Atlas-only data and database objects, and record baseline 20260709134422
  • keep normal openmeter-jobs migrate behavior unchanged except for rejecting Ent mode
  • document the two-step upgrade, target-version independence, and the recommendation to stop OpenMeter during the upgrade

Why

Ent automigration only synchronizes table schema. The Atlas migration history also contains data backfills, functions, triggers, views, singleton state, and canonical object names. Supporting both paths allows Ent-managed databases to diverge from databases upgraded through Atlas.

The adoption command deliberately stops at the frozen baseline. Operators then run the normal migration command to reach the version embedded in their target OpenMeter release.

Upgrade flow

  1. Stop OpenMeter servers and workers.
  2. Run openmeter-jobs migrate adopt-ent.
  3. Run openmeter-jobs migrate.
  4. Restart OpenMeter after the normal migration succeeds.

Validation

  • POSTGRES_HOST=127.0.0.1 go test -tags=dynamic -count=1 ./tools/migrate/...
  • nix develop --impure .#ci -c go vet -tags=dynamic ./app/config ./app/common ./cmd/jobs/migrate ./tools/migrate/...
  • go mod tidy -diff
  • make migrate-check-validate

The migration parity test compares a from-scratch Atlas database with the frozen Ent adoption path, including relational schema, views, functions, triggers, extensions, and migration-owned seed state.

Summary by CodeRabbit

  • New Features
    • Added a one-time adopt-ent migration job for databases previously managed by Ent.
    • Added support for postgres.autoMigrate modes: migration, migration-job, and false.
  • Configuration
    • Changed the default postgres.autoMigrate from ent to migration.
    • Removed support for postgres.autoMigrate: ent and now prompts to run adopt-ent first.
  • Documentation
    • Updated migration and upgrade sequencing guidance to match the new workflow and compatibility rules.

Greptile Summary

This PR moves legacy Ent-managed databases onto Atlas migrations. The main changes are:

  • Default PostgreSQL migration mode now uses versioned migrations.
  • Runtime Ent automigration is rejected with upgrade guidance.
  • A one-time openmeter-jobs migrate adopt-ent command adopts legacy Ent databases.
  • Frozen Ent schema descriptors and reconciliation SQL establish the Atlas baseline.
  • Documentation explains the two-step adoption and migration flow.

Confidence Score: 5/5

This looks safe to merge.

  • No blocking issues found in the changed code.
  • The legacy adoption path no longer runs the historical usage reset backfill during reconciliation.
  • The migration flow records the frozen baseline before the normal migration command continues.

Important Files Changed

Filename Overview
tools/migrate/legacy_ent.go Adds the adoption flow that detects legacy Ent databases, applies reconciliation, and records the Atlas baseline.
tools/migrate/legacyent/legacyent.go Runs the frozen Ent schema migration and ordered reconciliation scripts for adoption.
tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql Defines the usage-period database functions needed at the frozen baseline without running the historical row backfill.
app/common/database.go Removes runtime Ent schema creation and routes migrations through the Atlas migrator.
docs/database-migration.md Documents supported migration modes and the legacy Ent adoption procedure.

Reviews (2): Last reviewed commit: "fix: avoid replaying legacy adoption bac..." | Re-trigger Greptile

Context used (3)

  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)
  • Context used - api/spec/AGENTS.md (source)

@turip
turip requested a review from a team as a code owner July 14, 2026 11:44
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c52d7bfa-cbb5-4f64-b1d5-89393379dc61

📥 Commits

Reviewing files that changed from the base of the PR and between 27f2de8 and 659b6f4.

📒 Files selected for processing (2)
  • app/config/postgres.go
  • tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql
 _____________________________
< Lint today, shine tomorrow. >
 -----------------------------
  \
   \   \
        \ /\
        ( )
      .( o ).
📝 Walkthrough

Walkthrough

The PR changes PostgreSQL migration defaults from runtime Ent migrations to versioned migrations, adds an adopt-ent compatibility command, introduces a frozen Ent baseline with reconciliation scripts, and adds orchestration and PostgreSQL integration tests for adoption and schema parity.

Changes

Migration modes and adoption entrypoint

Layer / File(s) Summary
Migration modes and adoption entrypoint
AGENTS.md, app/config/*, cmd/jobs/migrate/migrate.go, config.example.yaml, deploy/charts/openmeter/templates/configmap.yaml, docs/database-migration.md
Configuration now defaults to versioned migrations, rejects ent, and documents the adopt-ent workflow. The migration CLI registers the adoption command and updates supported mode guidance. Deployment examples use migration.
Legacy database adoption orchestration
app/common/database.go, tools/migrate/legacy_ent.go, tools/migrate/migrate.go
The migrator exposes legacy Ent adoption, classifies database state, applies and reconciles the frozen baseline, records its version, and reports migration strategy at info level.
Frozen Ent baseline and reconciliation
tools/migrate/legacyent/*, tools/migrate/legacyent/reconciliation/*
A frozen Ent schema and ordered SQL reconciliation scripts establish baseline tables, functions, triggers, views, schema state, canonical object names, and verification checks.
Adoption and schema parity validation
tools/migrate/legacy_ent_test.go, tools/migrate/legacy_ent_parity_test.go
Integration tests cover rerunnable reconciliation, adoption and migration continuation, invalid database states, Atlas versions, relational schemas, programmable objects, and billing schema state.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested labels: release-note/feature, kind/refactor

Suggested reviewers: tothandras

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant MigrateCommand
  participant Migrator
  participant LegacyEntBaseline
  participant AtlasMigrations

  Operator->>MigrateCommand: Run adopt-ent
  MigrateCommand->>Migrator: AdoptLegacyEnt
  Migrator->>Migrator: Inspect state and lock database
  Migrator->>LegacyEntBaseline: Apply frozen schema and reconciliation
  LegacyEntBaseline-->>Migrator: Baseline ready
  Migrator->>AtlasMigrations: Force baseline version
  AtlasMigrations-->>Operator: Adoption completed
  Operator->>MigrateCommand: Run normal migrate
  MigrateCommand->>AtlasMigrations: Apply versioned migrations
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 summarizes the main change: adopting legacy Ent databases into Atlas migrations.
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
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/atlas-migration-adoption

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/deprecation Release note: Deprecations release-note/breaking-change Release note: Breaking Changes labels Jul 14, 2026
Comment thread tools/migrate/legacy_ent.go Resolved

@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 (3)
app/config/postgres.go (1)

81-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add punctuation for better readability in the error message.

The error message looks great and is super helpful! Just a tiny nitpick: adding a period or some parentheses before "see" will make it even clearer to read.

📝 Proposed tweak
 	case "ent":
-		return errors.New("ent auto-migration is no longer supported; run 'openmeter-jobs migrate adopt-ent' once, then run the normal migration see docs/database-migration.md")
+		return errors.New("ent auto-migration is no longer supported; run 'openmeter-jobs migrate adopt-ent' once, then run the normal migration (see docs/database-migration.md)")
 	default:
🤖 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 `@app/config/postgres.go` around lines 81 - 84, Update the error message
returned by the "ent" case in the migration configuration switch to add
punctuation before the documentation reference, separating the migration
instruction from “see docs/database-migration.md” for clearer readability.
tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql (1)

456-456: 🚀 Performance & Scalability | 🔵 Trivial

Heads up: the whole historical backfill runs inside one big transaction.

om_func_update_usage_period_durations_batch batches internally (2000 entitlements at a time, with progress RAISE NOTICEs), but the outer call is wrapped in the single transaction that covers this entire script (per Reconcile's per-file transaction design). For installs with a very large number of metered entitlements, that means no durable progress until the whole thing commits, and a long-held transaction/lock for the duration. Retries are safe (idempotent), so this isn't a defect — just worth knowing before running against a big production dataset.

🤖 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 `@tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql` at
line 456, Document that the call to om_func_update_usage_period_durations_batch
runs within the migration’s single transaction, so internal batching does not
provide durable progress until the script commits. Preserve the existing
idempotent backfill invocation and make the transaction and
large-production-dataset considerations clear near this call.
tools/migrate/legacy_ent_parity_test.go (1)

19-103: 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift

Nice schema-parity test — but consider covering the actual data backfill too.

Both canonicalDB and adoptedDB start empty, so this suite verifies schema/object/seed-row parity but never exercises 001_usage_period_functions.sql's historical usage_resets backfill (om_func_update_usage_period_durations_batch) against pre-existing legacy rows — that's the most complex, highest-risk piece of the whole reconciliation bundle. Worth adding a test that seeds representative entitlements/usage_resets/billing_invoice_lines rows on a legacy-shaped schema before Reconcile, then asserts the computed usage_period_interval/anchor values and the billing.subscription.sync.ignore annotation backfill are correct. Given how critical (and one-shot/irreversible) this adoption path is for real deployments, an e2e run of the actual openmeter-jobs migrate adopt-ent CLI against a seeded legacy-like database would also be a valuable addition, if not already covered elsewhere in the stack.

🤖 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 `@tools/migrate/legacy_ent_parity_test.go` around lines 19 - 103, Extend
TestLegacyEntAdoptionSchemaParity to seed representative legacy-shaped
entitlements, usage_resets, and billing_invoice_lines rows before calling
legacyent.Reconcile. Assert that the reconciliation/backfill computes the
expected usage_period_interval and anchor values through
om_func_update_usage_period_durations_batch, and verifies the
billing.subscription.sync.ignore annotation backfill. Keep the existing schema,
programmable-object, and seed-state parity assertions intact.

Source: Path instructions

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

Inline comments:
In `@tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql`:
- Line 2: Move the intervalstyle override from the function body into the
affected function definition’s SET clause, using SET intervalstyle = 'iso_8601'.
Remove the body-level override while preserving the function’s existing interval
handling.

---

Nitpick comments:
In `@app/config/postgres.go`:
- Around line 81-84: Update the error message returned by the "ent" case in the
migration configuration switch to add punctuation before the documentation
reference, separating the migration instruction from “see
docs/database-migration.md” for clearer readability.

In `@tools/migrate/legacy_ent_parity_test.go`:
- Around line 19-103: Extend TestLegacyEntAdoptionSchemaParity to seed
representative legacy-shaped entitlements, usage_resets, and
billing_invoice_lines rows before calling legacyent.Reconcile. Assert that the
reconciliation/backfill computes the expected usage_period_interval and anchor
values through om_func_update_usage_period_durations_batch, and verifies the
billing.subscription.sync.ignore annotation backfill. Keep the existing schema,
programmable-object, and seed-state parity assertions intact.

In `@tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql`:
- Line 456: Document that the call to
om_func_update_usage_period_durations_batch runs within the migration’s single
transaction, so internal batching does not provide durable progress until the
script commits. Preserve the existing idempotent backfill invocation and make
the transaction and large-production-dataset considerations clear near this
call.
🪄 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: fa5477d9-37b2-487c-b420-52bfe5935046

📥 Commits

Reviewing files that changed from the base of the PR and between 1d51ec7 and 27f2de8.

⛔ Files ignored due to path filters (1)
  • go.mod is excluded by !**/*.mod
📒 Files selected for processing (22)
  • AGENTS.md
  • app/common/database.go
  • app/config/config.go
  • app/config/config_test.go
  • app/config/postgres.go
  • cmd/jobs/migrate/migrate.go
  • config.example.yaml
  • deploy/charts/openmeter/templates/configmap.yaml
  • docs/database-migration.md
  • tools/migrate/legacy_ent.go
  • tools/migrate/legacy_ent_parity_test.go
  • tools/migrate/legacy_ent_test.go
  • tools/migrate/legacyent/README.md
  • tools/migrate/legacyent/legacyent.go
  • tools/migrate/legacyent/reconciliation/001_usage_period_functions.sql
  • tools/migrate/legacyent/reconciliation/002_subscription_trigger.sql
  • tools/migrate/legacyent/reconciliation/003_billing_schema_level.sql
  • tools/migrate/legacyent/reconciliation/004_charges_search_view.sql
  • tools/migrate/legacyent/reconciliation/005_canonical_object_names.sql
  • tools/migrate/legacyent/reconciliation/999_verify.sql
  • tools/migrate/legacyent/schema.go
  • tools/migrate/migrate.go

@turip
turip merged commit 9d0d3a4 into main Jul 14, 2026
27 checks passed
@turip
turip deleted the feat/atlas-migration-adoption branch July 14, 2026 13:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/breaking-change Release note: Breaking Changes release-note/deprecation Release note: Deprecations

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants