Skip to content

fix(migrations): repair partially-applied 058-067 schema (idempotent re-assert) - #1127

Merged
cristim merged 2 commits into
feat/multicloud-web-frontendfrom
fix/migration-repair-058-067
Jun 9, 2026
Merged

cristim merged 2 commits into
feat/multicloud-web-frontendfrom
fix/migration-repair-058-067

Conversation

@cristim

@cristim cristim commented Jun 9, 2026 •

Copy link
Copy Markdown
Member

Root cause

A prior emergency Force(67) on a dev/QA database marked migrations 058-067 as
applied without running their SQL. Several genuinely-unapplied schema
changes from that range are therefore missing in the affected DB. The most
visible symptom is live 500s on planned/pending/stuck purchase-execution
queries:

column idempotency_key does not exist

(purchase_executions.idempotency_key, added by migration 000066). Confirmed
also missing: groups.system_managed (000059), and the rest of the 058-067
schema (058 audit columns/index, 063 nullable monthly_cost, 065 min-one-admin
triggers, 067 analytics-snapshot corrections).

The 058-067 range cannot simply be re-run: migration 000059 carries a
RAISE EXCEPTION seed-guard that conflicts with the Purchaser group already
relocated by 000064, so re-applying it aborts.

Fix

New migration 000074_repair_partial_migration_058_067 re-asserts only the
schema
from 058-067 in fully idempotent form, so any partially-migrated
(or fully-migrated) DB self-heals to the correct schema on the next deploy. It
intentionally omits the conflicting data seeds (059 Purchaser INSERT + admin
backfill, 060 universal-plans DELETE, 064 relocate); those rows already exist or
were deliberately relocated on any affected DB.

Schema re-asserted (by source migration)

Source Object Idempotent form
058 purchase_executions.executed_by_user_id, .executed_at, .pre_approval_skip_reason ADD COLUMN IF NOT EXISTS
058 index idx_executions_direct_execute CREATE INDEX IF NOT EXISTS
059 groups.system_managed ADD COLUMN IF NOT EXISTS
063 purchase_history.monthly_cost nullable DROP NOT NULL (no-op when already applied)
065 function check_min_one_admin() CREATE OR REPLACE FUNCTION
065 triggers trg_min_one_admin_delete, trg_min_one_admin_update DROP TRIGGER IF EXISTS + CREATE TRIGGER
066 purchase_executions.idempotency_key ADD COLUMN IF NOT EXISTS
067 savings_snapshots.account_id widened to VARCHAR(255) guarded DO block
067 savings_snapshots.total_usage / .coverage_percentage nullable DROP NOT NULL + DROP DEFAULT
067 matviews monthly_savings_summary, daily_savings_trend, provider_savings_summary (+ unique indexes) DROP MATERIALIZED VIEW IF EXISTS ... CASCADE then CREATE
067 function drop_old_savings_partitions() CREATE OR REPLACE FUNCTION

One deliberate ordering change vs source 067

The materialized views are dropped before the account_id type widening.
On the corrupted DB the views still exist from migration 000003 selecting
savings_snapshots.account_id, which blocks ALTER COLUMN account_id TYPE
with cannot alter type of a column used by a view or rule. Dropping the
dependent views first lets the repair converge from the view-present state, then
recreates them with the corrected cloud_account_id-carrying definitions.

Transactional + idempotent

  • No CONCURRENTLY anywhere, so golang-migrate applies the whole file in a
    single transaction (atomic; partial application impossible).
  • Re-applying the migration is a clean no-op (verified), so it is safe on
    already-correct DBs and safe to re-run.
  • .down.sql is a documented no-op: this repair does not own the objects
    (the source migrations do), so dropping them on rollback would corrupt a
    correctly-migrated DB.

Verification

Against a Postgres 16 container:

  1. Reproduced the corrupted baseline: applied 001-057, skipped 058-067,
    applied 070-073. Confirmed every listed object was missing
    (idempotency_key absent, system_managed absent, account_id = 20,
    monthly_cost NOT NULL, 0 admin triggers, old views).
  2. Applied 000074 -> every object converged (idempotency_key present,
    account_id = 255, both triggers + function present, all three matviews
    recreated carrying cloud_account_id with their unique indexes).
  3. Re-applied 000074 -> clean no-op, state unchanged.
  4. Ran the file with psql -1 (single transaction) -> succeeds atomically.

go build ./... succeeds, the migration unit-test suite passes (175 tests),
gofmt clean.

🤖 Generated with claude-flow

Summary by CodeRabbit

  • Bug Fixes
    • Fixed database schema inconsistencies where certain system updates were incorrectly marked as applied without execution.
    • Restored administrative access controls and system safeguards to ensure proper governance.
    • Corrected data model definitions across analytics and core system tables.

…re-assert)

A prior emergency Force(67) on a dev/QA database marked migrations 058-067
as applied without running their SQL, leaving genuinely-unapplied schema
changes missing. The most visible symptom is live 500s on
planned/pending/stuck purchase-execution queries:
"column idempotency_key does not exist" (purchase_executions.idempotency_key
from 066). groups.system_managed (059) and other 058-067 schema are missing
too. The 058-067 range cannot simply be re-run: migration 059 has a
RAISE EXCEPTION seed-guard that conflicts with the Purchaser group already
relocated by 064.

Add migration 000074, which re-asserts ONLY the schema from 058-067 in fully
idempotent form so any partially-migrated (or fully-migrated) DB converges to
the correct schema. It intentionally omits the conflicting data seeds
(059 Purchaser INSERT + admin backfill, 060 universal-plans DELETE, 064
relocate); those rows already exist or were deliberately relocated on any
affected DB.

Schema re-asserted, by source migration:
- 058: purchase_executions.executed_by_user_id, .executed_at,
  .pre_approval_skip_reason; index idx_executions_direct_execute
- 059: groups.system_managed
- 063: purchase_history.monthly_cost DROP NOT NULL
- 065: function check_min_one_admin(); constraint triggers
  trg_min_one_admin_delete, trg_min_one_admin_update
- 066: purchase_executions.idempotency_key
- 067: savings_snapshots.account_id widened to VARCHAR(255);
  total_usage / coverage_percentage made NULLABLE (DROP NOT NULL + DROP
  DEFAULT); materialized views monthly_savings_summary, daily_savings_trend,
  provider_savings_summary recreated carrying cloud_account_id (+ unique
  indexes); function drop_old_savings_partitions()

Ordering differs from source 067 in one place: the materialized views are
dropped BEFORE the account_id type widening. On the corrupted DB the views
still exist from migration 000003 selecting account_id, which blocks
ALTER COLUMN account_id TYPE. Dropping the dependent views first lets the
repair converge from the view-present state.

The migration is fully transactional (no CONCURRENTLY), so golang-migrate
applies it atomically, and it is idempotent (re-applying is a clean no-op).
The .down.sql is a documented no-op: this repair does not own the objects
(the source migrations do), so dropping them on rollback would corrupt a
correctly-migrated DB.

Verified against a Postgres 16 container: reproduced the corrupted baseline
(001-057 applied, 058-067 skipped, 070-073 applied), confirmed all listed
objects were missing, applied 074, and confirmed every object converged;
re-applied 074 and confirmed it is a clean no-op; confirmed it runs inside a
single transaction. go build and migration unit tests green, gofmt clean.
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@cristim, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 16 minutes and 18 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1619de6d-7a1b-40a0-9ae6-328fdeebefa4

📥 Commits

Reviewing files that changed from the base of the PR and between eabf397 and 2f722ab.

📒 Files selected for processing (1)
  • internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql
📝 Walkthrough

Walkthrough

This PR adds migration 000074 to repair databases where migrations 058–067 were incorrectly marked applied without fully executing. The migration atomically re-asserts missing schema across purchase execution audit columns, admin enforcement triggers, and analytics snapshot definitions, with a no-op rollback script.

Changes

Migration repair for partial application

Layer / File(s) Summary
Migration rollback scaffold
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.down.sql
No-op down.sql that decrements migration version without schema changes, documenting that the repair is non-reversible.
Migration header and context
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql (header)
Detailed documentation of failure mode, repair scope (schema-only, no seed backfills), and convergence strategy for partial migration state.
Core schema re-assertion
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql (lines 45–75)
Re-adds missing columns and index from failed migrations 058, 059, 063, 066: audit columns and partial index on purchase_executions, system_managed on groups, nullable monthly_cost on purchase_history, and idempotency_key on purchase_executions.
Admin invariant enforcement
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql (lines 81–131)
Recreates check_min_one_admin() trigger function with advisory transaction lock and active membership counting, then defines constraint triggers on user delete and update to enforce minimum one active administrator invariant.
Analytics snapshot schema repair
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql (lines 139–272)
Repairs migration 067 by dropping dependent materialized views, conditionally widening savings_snapshots.account_id and making total_usage/coverage_percentage nullable, then recreating monthly_savings_summary, daily_savings_trend, and provider_savings_summary with updated definitions and indexes, and refreshing non-concurrently.
Partition cleanup function update
internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql (lines 273–307)
Redefines drop_old_savings_partitions() with improved error handling: safely parses partition dates, skips unparseable partitions, and drops only those older than configured retention window.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • LeanerCloud/CUDly#921: Both PRs touch the "min-one-admin" Postgres enforcement by (re)creating the check_min_one_admin() function and its constraint triggers in the migrations, which the auth service then relies on to map deferred trigger violations to ErrLastAdmin.
  • LeanerCloud/CUDly#1124: Main PR's 000074_repair_partial_migration_058_067.up.sql directly repairs/reshapes the same savings snapshot materialized views (provider_savings_summary, daily_savings_trend, monthly_savings_summary, via savings_snapshots changes) that retrieved PR #1124's 000067_analytics_snapshot_correctness.up.sql updates.
  • LeanerCloud/CUDly#943: The main PR's repair migration (000074) modifies the groups table schema (e.g., adding system_managed) and admin invariants, which directly overlaps with migration #943 (000064) that relocates/creates the Purchaser group as system-managed.

Suggested labels

urgency/now

Poem

🐰 A carrot of repairs, so swift and complete,
Migrations now gathered in one atomic beat,
Admin locks tight, analytics fixed,
No partial states leave the database mixed,
Hop forward with confidence, the schema's now neat!

🚥 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 clearly summarizes the main change: repairing partially-applied migrations 058-067 by re-asserting schema changes idempotently, which directly matches the PR's core objective.
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/migration-repair-058-067

Comment @coderabbitai help to get the list of available commands and usage tips.

@cristim cristim added type/bug Defect priority/p1 Next up; this sprint severity/high Significant harm impact/all-users Affects every user effort/m Days triaged Item has been triaged labels Jun 9, 2026
@cristim

cristim commented Jun 9, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 2

🤖 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
`@internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql`:
- Around line 183-271: The CREATE MATERIALIZED VIEW statements for
monthly_savings_summary, daily_savings_trend and provider_savings_summary
currently populate immediately and then the subsequent REFRESH MATERIALIZED VIEW
calls re-run the same work; fix by either adding WITH NO DATA to each CREATE
MATERIALIZED VIEW (monthly_savings_summary, daily_savings_trend,
provider_savings_summary) so they are created empty and the later REFRESH is the
single populate step, or remove the three REFRESH MATERIALIZED VIEW lines
entirely so creation does the single populate—choose one approach and apply it
consistently to those three view definitions and/or the REFRESH calls.
- Around line 283-303: The drop_old_savings_partitions function currently scans
public.pg_tables with tablename LIKE 'savings_snapshots_%' which can match
non-partition tables; change the partition enumeration to query
pg_inherits/pg_class to list only actual child partitions of the parent table
savings_snapshots (join pg_inherits.inhrelid -> pg_class.relname, filter parent
relname = 'savings_snapshots' and exclude the default partition name), then
parse the YYYY_MM from each child partition name as before and only EXECUTE DROP
for those child partitions older than cutoff_date; update references in the
function to use the pg_inherits-derived partition_record.tablename (or relname)
rather than pg_tables so non-child tables like savings_snapshots_backup_* are
never considered for drop.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: e0c2714e-6f7a-4a68-a836-942891df4763

📥 Commits

Reviewing files that changed from the base of the PR and between 0c10f1a and eabf397.

📒 Files selected for processing (2)
  • internal/database/postgres/migrations/000074_repair_partial_migration_058_067.down.sql
  • internal/database/postgres/migrations/000074_repair_partial_migration_058_067.up.sql

Two CodeRabbit findings on the idempotent 058-067 repair migration:

- Materialized views (monthly_savings_summary, daily_savings_trend,
  provider_savings_summary) were created without WITH NO DATA, so each
  populated immediately and the subsequent REFRESH re-ran the same
  aggregation, doubling work and lock time on savings_snapshots. Create
  the views WITH NO DATA so the single REFRESH is the only populate step.

- drop_old_savings_partitions enumerated partitions via pg_tables with
  tablename LIKE 'savings_snapshots_%', where the LIKE wildcard '_' could
  match unrelated tables (e.g. savings_snapshots_backup_2024_01) and risk
  dropping non-partition data. Enumerate real child partitions from the
  catalog (pg_inherits) scoped to the savings_snapshots parent instead.

Migration stays fully idempotent, transactional, and CONCURRENTLY-free;
no 059 data seed is reintroduced. go build ./... and
go test ./internal/database/... pass.
@cristim

cristim commented Jun 9, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@cristim
cristim merged commit 05e5561 into feat/multicloud-web-frontend Jun 9, 2026
4 checks passed
@cristim
cristim deleted the fix/migration-repair-058-067 branch July 27, 2026 11:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort/m Days impact/all-users Affects every user priority/p1 Next up; this sprint severity/high Significant harm triaged Item has been triaged type/bug Defect

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant