Repository navigation
fix(db): drop the 9-column recommendations natural key index (#806) #821
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
internal/database/postgres/migrations/000119_drop_recommendations_9col_natural_key.down.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| -- Rollback of 000119: recreate the 9-column unique index exactly as defined by | ||
| -- 000109. | ||
| -- | ||
| -- Only safe together with a code rollback to the pre-PR-C upsert (9-column | ||
| -- ON CONFLICT). PR-C code needs the 11-column arbiter, so rolling PR-C back | ||
| -- requires this down migration first, otherwise the old code runs without a | ||
| -- 9-column arbiter. The recommendations table is a regenerable cache, so rows | ||
| -- that differ only by platform or tenancy (allowed while the 9-column index is | ||
| -- absent) are collapsed to the most recently collected one before the index is | ||
| -- rebuilt; the next collection cycle repopulates the rest. Only duplicates | ||
| -- under the 9-column key are deleted. | ||
| DELETE FROM recommendations | ||
| WHERE id IN ( | ||
| SELECT id FROM ( | ||
| SELECT id, ROW_NUMBER() OVER ( | ||
| PARTITION BY account_key, provider, service, region, resource_type, engine, term, payment_option, availability_zone | ||
| ORDER BY collected_at DESC, id DESC | ||
| ) AS rn | ||
| FROM recommendations | ||
| ) ranked | ||
| WHERE rn > 1 | ||
| ); | ||
|
|
||
| CREATE UNIQUE INDEX IF NOT EXISTS recommendations_natural_key_az_idx | ||
| ON recommendations (account_key, provider, service, region, resource_type, engine, term, payment_option, availability_zone); |
19 changes: 19 additions & 0 deletions
19
internal/database/postgres/migrations/000119_drop_recommendations_9col_natural_key.up.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| -- Migration 000119: drop the 9-column recommendations_natural_key_az_idx | ||
| -- (#806, PR-E of the platform/tenancy identity work). | ||
| -- | ||
| -- Migration 000111 added the generated platform and tenancy columns and the | ||
| -- 11-column recommendations_natural_key_az_tp_idx, and kept the 9-column index | ||
| -- so the pre-PR-C upsert (ON CONFLICT on the 9 columns) kept working. The store | ||
| -- now upserts on the 11-column index (PR-C), so the 9-column index only does | ||
| -- harm: it rejects two EC2 rows that differ only by platform or tenancy, which | ||
| -- aborts the whole collection write. Dropping it lets those rows coexist. | ||
| -- | ||
| -- DEPLOY ORDER: apply this only after the code that upserts on the 11-column | ||
| -- index (PR-C) is live everywhere. Applying it while older code still runs | ||
| -- breaks every collection, because ON CONFLICT on the 9 columns needs that | ||
| -- index. database-migration.yml applies ALL pending migrations when `steps` is | ||
| -- 0 or empty, so never dispatch it with the default before PR-C is released. | ||
| -- | ||
| -- The 11-column index is strictly finer than the 9-column one, so no existing | ||
| -- row can violate it and nothing needs backfilling. | ||
| DROP INDEX IF EXISTS recommendations_natural_key_az_idx; | ||
114 changes: 114 additions & 0 deletions
114
internal/database/postgres/migrations/000119_drop_recommendations_9col_natural_key_test.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| //go:build integration | ||
| // +build integration | ||
|
|
||
| package migrations_test | ||
|
|
||
| import ( | ||
| "context" | ||
| "testing" | ||
|
|
||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/migrations" | ||
| "github.com/LeanerCloud/cloud-commitments-platform/internal/database/postgres/testhelpers" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| const insertRecForMigration119 = ` | ||
| INSERT INTO recommendations | ||
| (collected_at, provider, service, region, resource_type, engine, payload, | ||
| upfront_cost, monthly_savings, term, payment_option) | ||
| VALUES ($1::timestamptz, 'aws', 'ec2', 'us-east-1', $2, '', $3::jsonb, 0, 0, 1, 'all-upfront') | ||
| ` | ||
|
|
||
| // TestMigration_DropRecommendations9ColNaturalKey locks down migration 000119 | ||
| // (issue #806, PR-E): rows that differ only by platform or tenancy coexist once | ||
| // the 9-column index is gone, the 11-column index still dedupes, and the | ||
| // rollback recreates the 9-column index after collapsing those duplicates. | ||
| func TestMigration_DropRecommendations9ColNaturalKey(t *testing.T) { | ||
| ctx := context.Background() | ||
| migrationsPath := getMigrationsPath() | ||
|
|
||
| container, err := testhelpers.SetupPostgresContainer(ctx, t) | ||
| require.NoError(t, err) | ||
| defer container.Cleanup(ctx) | ||
| pool := container.DB.Pool() | ||
|
|
||
| indexExists := func(name string) bool { | ||
| var exists bool | ||
| require.NoError(t, pool.QueryRow(ctx, | ||
| `SELECT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'recommendations' AND indexname = $1)`, name).Scan(&exists)) | ||
| return exists | ||
| } | ||
| count := func(resourceType string) int { | ||
| var n int | ||
| require.NoError(t, pool.QueryRow(ctx, `SELECT COUNT(*) FROM recommendations WHERE resource_type = $1`, resourceType).Scan(&n)) | ||
| return n | ||
| } | ||
| const ( | ||
| linux = `{"availability_zone":"us-east-1a","details":{"platform":"Linux/UNIX","tenancy":"default"}}` | ||
| windows = `{"availability_zone":"us-east-1a","details":{"platform":"Windows","tenancy":"default"}}` | ||
| rhel = `{"availability_zone":"us-east-1a","details":{"platform":"Linux/UNIX","tenancy":"dedicated"}}` | ||
| other = `{"availability_zone":"us-east-1b","details":{"platform":"Linux/UNIX","tenancy":"default"}}` | ||
| ) | ||
|
|
||
| require.NoError(t, migrations.MigrateToVersion(ctx, pool, migrationsPath, previousMigrationVersion(t, 119))) | ||
| require.True(t, indexExists("recommendations_natural_key_az_idx")) | ||
| require.True(t, indexExists("recommendations_natural_key_az_tp_idx")) | ||
|
|
||
| // A regional row and one EC2 row exist before the migration. | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-01T00:00:00Z", "regional", `{"details":{"scope":"Region"}}`) | ||
| require.NoError(t, err) | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-01T00:00:00Z", "ec2", linux) | ||
| require.NoError(t, err) | ||
|
|
||
| require.NoError(t, migrations.MigrateToVersion(ctx, pool, migrationsPath, 119)) | ||
| assert.False(t, indexExists("recommendations_natural_key_az_idx"), "9-column index must be dropped") | ||
| assert.True(t, indexExists("recommendations_natural_key_az_tp_idx"), "11-column index must remain") | ||
|
|
||
| // Rows differing only by platform or tenancy now coexist; an exact | ||
| // duplicate and a duplicate regional row are still rejected by the | ||
| // 11-column index. | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-02T00:00:00Z", "ec2", windows) | ||
| require.NoError(t, err) | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-03T00:00:00Z", "ec2", rhel) | ||
| require.NoError(t, err) | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-03T00:00:00Z", "ec2", other) | ||
| require.NoError(t, err, "a different AZ is a different row under both indexes") | ||
| assert.Equal(t, 4, count("ec2")) | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-03T00:00:00Z", "ec2", linux) | ||
| require.Error(t, err, "same platform and tenancy must still violate the 11-column index") | ||
| _, err = pool.Exec(ctx, insertRecForMigration119, "2026-01-03T00:00:00Z", "regional", `{"details":{"scope":"Region"}}`) | ||
| require.Error(t, err, "regional duplicate must still violate the 11-column index") | ||
|
|
||
| // Rollback: platform/tenancy-only duplicates collapse to the newest, the | ||
| // other-AZ row and the regional row are untouched, and the 9-column index | ||
| // is recreated with its original shape. | ||
| require.NoError(t, migrations.MigrateToVersion(ctx, pool, migrationsPath, previousMigrationVersion(t, 119))) | ||
| assert.Equal(t, 2, count("ec2"), "only duplicates under the 9-column key may be deleted") | ||
| assert.Equal(t, 1, count("regional")) | ||
| rows, err := pool.Query(ctx, `SELECT availability_zone, platform, tenancy FROM recommendations WHERE resource_type = 'ec2' ORDER BY availability_zone`) | ||
| require.NoError(t, err) | ||
| type kept struct{ az, platform, tenancy string } | ||
| var got []kept | ||
| for rows.Next() { | ||
| var k kept | ||
| require.NoError(t, rows.Scan(&k.az, &k.platform, &k.tenancy)) | ||
| got = append(got, k) | ||
| } | ||
| require.NoError(t, rows.Err()) | ||
| assert.Equal(t, []kept{ | ||
| {"us-east-1a", "Linux/UNIX", "dedicated"}, // newest of the us-east-1a group | ||
| {"us-east-1b", "Linux/UNIX", "default"}, | ||
| }, got) | ||
|
|
||
| var indexDef string | ||
| require.NoError(t, pool.QueryRow(ctx, | ||
| `SELECT indexdef FROM pg_indexes WHERE indexname = 'recommendations_natural_key_az_idx'`).Scan(&indexDef)) | ||
| assert.Contains(t, indexDef, "UNIQUE INDEX") | ||
| assert.Contains(t, indexDef, "(account_key, provider, service, region, resource_type, engine, term, payment_option, availability_zone)") | ||
| assert.True(t, indexExists("recommendations_natural_key_az_tp_idx")) | ||
|
|
||
| // Re-applying the up migration after a rollback works. | ||
| require.NoError(t, migrations.MigrateToVersion(ctx, pool, migrationsPath, 119)) | ||
| assert.False(t, indexExists("recommendations_natural_key_az_idx")) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.