Skip to content

fix: repair rebased migrations - #4400

Merged
turip merged 1 commit into
mainfrom
fix/repair-rebased-migrations
May 20, 2026
Merged

turip merged 1 commit into
mainfrom
fix/repair-rebased-migrations

Conversation

@turip

@turip turip commented May 20, 2026 •

Copy link
Copy Markdown
Member

Summary

  • add a forward-only repair migration for rebased migration versions that may have been skipped on already-migrated databases
  • repair charge tax-code fields/view, flat-fee run immutability, ledger entry identity key, and credit expiration/breakage schema
  • intentionally exclude the LLM cost data normalization migration

Testing

  • atlas migrate --env local hash
  • make migrate-check-validate
  • go test ./tools/migrate

Summary by CodeRabbit

  • New Features

    • Added tax code and tax behavior tracking to charges
    • Implemented expiration tracking for credit purchases
    • Created ledger breakage records for improved financial tracking
  • Bug Fixes

    • Recovered database structure from previously missed migration steps
    • Added data integrity validation to prevent duplicate ledger entries

Review Change Stack

@turip
turip requested a review from a team as a code owner May 20, 2026 15:00
@turip turip added area/billing kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes labels May 20, 2026
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR adds a single repair migration that backfills schema changes across multiple tables: tax code columns for charges, identity keys for ledger deduplication, metadata flags for charge runs, and a new ledger breakage records table. The down migration is a documented no-op to prevent accidentally dropping valid schema in healthy environments.

Changes

Schema Backfill and Ledger Repair

Layer / File(s) Summary
Charge table tax code support
tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql (lines 1–62)
Adds tax_behavior and tax_code_id columns to three charge tables (charge_credit_purchases, charge_flat_fees, charge_usage_based) with conditional foreign keys to tax_codes(id) and supporting indexes. Updates charges_search_v1s view to project the new columns alongside the charge type discriminator.
Ledger entry deduplication and identity tracking
tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql (lines 72–96)
Adds identity_key to ledger_entries, backfills existing rows with empty string, and enforces a unique constraint on (transaction_id, sub_account_id, identity_key). Includes a DO block that detects and raises an exception if duplicates already exist before creating the unique index.
Charge metadata and expiration tracking
tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql (lines 63–98)
Adds immutable boolean column to charge_flat_fee_runs (backfilled to false) and expires_at timestamp to charge_credit_purchases to track charge lifecycle state.
Ledger breakage records table
tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql (lines 100–133)
Creates ledger_breakage_records table with required expires_at field and composite/GIN indexes supporting queries by namespace, customer, currency, credit priority, and source/plan identifiers.
Down migration no-op policy
tools/migrate/migrations/20260520130000_repair_rebased_migrations.down.sql (lines 1–6)
Defines rollback as a documented no-op to prevent dropping valid schema from original migrations in environments where the repair is applied to already-healthy databases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • openmeterio/openmeter#4237: Introduces the same tax_code_id/tax_behavior columns and charges_search_v1s view updates across charge tables that this repair migration backfills.

Suggested labels

release-note/feature, area/billing

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: repair rebased migrations' clearly and concisely describes the main change—adding a repair migration to handle previously-skipped migrations after rebasing.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/repair-rebased-migrations

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 and usage tips.

@turip
turip requested review from GAlexIHU and tothandras May 20, 2026 15:05

@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 (2)
tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql (2)

61-61: ⚡ Quick win

Consider formatting the view definition for readability.

The entire view definition is on a single line, which makes it tough to review and maintain. Breaking it into multiple lines would help future developers quickly spot which columns are being selected from each table.

📖 Example formatting
CREATE VIEW "charges_search_v1s" AS
SELECT 
  "id", "namespace", "metadata", "created_at", "updated_at", "deleted_at",
  "name", "description", "annotations", "customer_id",
  "service_period_from", "service_period_to",
  "billing_period_from", "billing_period_to",
  "full_service_period_from", "full_service_period_to",
  "status", "unique_reference_id", "currency", "managed_by",
  "subscription_id", "subscription_phase_id", "subscription_item_id",
  "advance_after", "tax_code_id", "tax_behavior",
  'credit_purchase' AS "type"
FROM "charge_credit_purchases"
UNION ALL
SELECT 
  "id", "namespace", "metadata", "created_at", "updated_at", "deleted_at",
  "name", "description", "annotations", "customer_id",
  "service_period_from", "service_period_to",
  "billing_period_from", "billing_period_to",
  "full_service_period_from", "full_service_period_to",
  "status", "unique_reference_id", "currency", "managed_by",
  "subscription_id", "subscription_phase_id", "subscription_item_id",
  "advance_after", "tax_code_id", "tax_behavior",
  'flat_fee' AS "type"
FROM "charge_flat_fees"
UNION ALL
SELECT 
  "id", "namespace", "metadata", "created_at", "updated_at", "deleted_at",
  "name", "description", "annotations", "customer_id",
  "service_period_from", "service_period_to",
  "billing_period_from", "billing_period_to",
  "full_service_period_from", "full_service_period_to",
  "status", "unique_reference_id", "currency", "managed_by",
  "subscription_id", "subscription_phase_id", "subscription_item_id",
  "advance_after", "tax_code_id", "tax_behavior",
  'usage_based' AS "type"
FROM "charge_usage_based";
🤖 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/migrations/20260520130000_repair_rebased_migrations.up.sql` at
line 61, The view definition is on one long line making it unreadable; reformat
the SQL in this migration by breaking the CREATE VIEW/SELECT statement into
multiple lines: put column lists each on their own lines, place the FROM clauses
on separate lines, and separate each UNION ALL block for the three SELECTs (the
SELECT from "charge_credit_purchases", the SELECT from "charge_flat_fees", and
the SELECT from "charge_usage_based"); preserve the exact column order and keep
the literal type aliases ('credit_purchase' AS "type", 'flat_fee' AS "type",
'usage_based' AS "type") unchanged so the view semantics remain identical.

127-127: ⚡ Quick win

Remove the redundant unique index on id.

The id column is already the PRIMARY KEY (line 123), which automatically creates a unique index. Creating an additional unique index here is redundant and wastes storage space.

🔧 Suggested fix
 CREATE INDEX IF NOT EXISTS "ledgerbreakagerecord_annotations" ON "ledger_breakage_records" USING gin ("annotations");
-CREATE UNIQUE INDEX IF NOT EXISTS "ledgerbreakagerecord_id" ON "ledger_breakage_records" ("id");
 CREATE INDEX IF NOT EXISTS "ledgerbreakagerecord_namespace" ON "ledger_breakage_records" ("namespace");
🤖 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/migrations/20260520130000_repair_rebased_migrations.up.sql` at
line 127, Remove the redundant unique index creation for the id column: delete
the CREATE UNIQUE INDEX statement that defines "ledgerbreakagerecord_id" on
"ledger_breakage_records" ("id"); the table already has id as PRIMARY KEY (see
the existing PRIMARY KEY declaration), so drop this extra index line to avoid
duplicate indexing and wasted storage.
🤖 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 `@tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql`:
- Line 61: The view definition is on one long line making it unreadable;
reformat the SQL in this migration by breaking the CREATE VIEW/SELECT statement
into multiple lines: put column lists each on their own lines, place the FROM
clauses on separate lines, and separate each UNION ALL block for the three
SELECTs (the SELECT from "charge_credit_purchases", the SELECT from
"charge_flat_fees", and the SELECT from "charge_usage_based"); preserve the
exact column order and keep the literal type aliases ('credit_purchase' AS
"type", 'flat_fee' AS "type", 'usage_based' AS "type") unchanged so the view
semantics remain identical.
- Line 127: Remove the redundant unique index creation for the id column: delete
the CREATE UNIQUE INDEX statement that defines "ledgerbreakagerecord_id" on
"ledger_breakage_records" ("id"); the table already has id as PRIMARY KEY (see
the existing PRIMARY KEY declaration), so drop this extra index line to avoid
duplicate indexing and wasted storage.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 27665dde-4fc2-40b8-8702-e7d658ba27c2

📥 Commits

Reviewing files that changed from the base of the PR and between 944c12d and d6b94af.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (2)
  • tools/migrate/migrations/20260520130000_repair_rebased_migrations.down.sql
  • tools/migrate/migrations/20260520130000_repair_rebased_migrations.up.sql

@GAlexIHU

Copy link
Copy Markdown
Contributor

thank you!

@turip
turip merged commit 31be845 into main May 20, 2026
31 of 33 checks passed
@turip
turip deleted the fix/repair-rebased-migrations branch May 20, 2026 15:15

This branch was previously deployed

1 inactive deployment
dev — d6b94afd Deployed May 20, 2026 by turip via Migration Checks #14536
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing kind/bug Something isn't working release-note/bug-fix Release note: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants