-
Notifications
You must be signed in to change notification settings - Fork 8
feat: VACUUM/ANALYZE - BED-8494 #97
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
5 commits
Select commit
Hold shift + click to select a range
2b785c9
initial
brandonshearin ac6d2a7
specify node and edge parent tables
brandonshearin 73d9899
gate the vacuum behind n_dead_tup
brandonshearin 80d8d47
unit test vacuum analyze
brandonshearin 25c7161
add slog to optimizeStorage; add dawgrun support
brandonshearin 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
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,80 @@ | ||
| package pg | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "log/slog" | ||
| "strings" | ||
|
|
||
| "github.com/jackc/pgx/v5" | ||
| "github.com/jackc/pgx/v5/pgconn" | ||
| ) | ||
|
|
||
| // deadTupleThreshold is the minimum fraction of dead tuples a partitioned | ||
| // parent must accumulate across its partitions before OptimizeStorage will | ||
| // vacuum it. | ||
| const deadTupleThreshold = 0.1 | ||
|
|
||
| // Sum n_dead_tup and n_live_tup across every leaf partition of the parent; | ||
| const optimizeStorageStatsQuery = ` | ||
| SELECT | ||
| COALESCE(SUM(stat.n_dead_tup), 0), | ||
| COALESCE(SUM(stat.n_live_tup), 0) | ||
| FROM pg_partition_tree($1::regclass) tree | ||
| LEFT JOIN pg_stat_user_tables stat ON stat.relid = tree.relid | ||
| WHERE tree.isleaf | ||
| ` | ||
|
|
||
| type optimizeStorageConn interface { | ||
| Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) | ||
| QueryRow(ctx context.Context, sql string, arguments ...any) pgx.Row | ||
| } | ||
|
|
||
| func optimizeStorage(ctx context.Context, conn optimizeStorageConn) error { | ||
| var targets []string | ||
| for _, table := range []string{"node", "edge"} { | ||
| var dead, live int64 | ||
| if err := conn.QueryRow(ctx, optimizeStorageStatsQuery, table).Scan(&dead, &live); err != nil { | ||
| return fmt.Errorf("query dead tuple stats for %s: %w", table, err) | ||
| } | ||
|
|
||
| total := dead + live | ||
| var deadTupleRatio float64 | ||
| if total > 0 { | ||
| deadTupleRatio = float64(dead) / float64(total) | ||
| } | ||
|
|
||
| slog.InfoContext(ctx, "Queried PostgreSQL table storage statistics", | ||
| slog.String("table", table), | ||
| slog.Int64("dead_tuples", dead), | ||
| slog.Int64("live_tuples", live), | ||
| slog.Int64("total_tuples", total), | ||
| slog.Float64("dead_tuple_ratio", deadTupleRatio), | ||
| slog.Float64("dead_tuple_threshold", deadTupleThreshold), | ||
| ) | ||
|
|
||
| if total == 0 { | ||
| continue | ||
| } | ||
| if deadTupleRatio >= deadTupleThreshold { | ||
| targets = append(targets, table) | ||
| } | ||
| } | ||
|
|
||
| if len(targets) == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| // Targeting the partitioned parents cascades to every partition. | ||
| stmt := "VACUUM (ANALYZE) " + strings.Join(targets, ", ") | ||
| slog.InfoContext(ctx, "Executing PostgreSQL storage optimization", | ||
| slog.Any("targets", targets), | ||
| slog.String("statement", stmt), | ||
| ) | ||
|
|
||
| if _, err := conn.Exec(ctx, stmt, pgx.QueryExecModeSimpleProtocol); err != nil { | ||
| return fmt.Errorf("%s: %w", stmt, err) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
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,96 @@ | ||
| package pg | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "testing" | ||
|
|
||
| "github.com/jackc/pgx/v5" | ||
| "github.com/pashagolub/pgxmock/v5" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| func TestOptimizeStorage(t *testing.T) { | ||
| t.Run("skips vacuum when dead tuple ratios are below threshold", func(t *testing.T) { | ||
| ctx := context.Background() | ||
| conn := newOptimizeStorageMockConn(t) | ||
|
|
||
| expectOptimizeStorageStats(conn, "node", 9, 91) | ||
| expectOptimizeStorageStats(conn, "edge", 0, 0) | ||
|
|
||
| require.NoError(t, optimizeStorage(ctx, conn)) | ||
| require.NoError(t, conn.ExpectationsWereMet()) | ||
| }) | ||
|
|
||
| t.Run("vacuums node only", func(t *testing.T) { | ||
| ctx := context.Background() | ||
| conn := newOptimizeStorageMockConn(t) | ||
|
|
||
| expectOptimizeStorageStats(conn, "node", 10, 90) | ||
| expectOptimizeStorageStats(conn, "edge", 9, 91) | ||
| expectOptimizeStorageVacuum(conn, "VACUUM (ANALYZE) node") | ||
|
|
||
| require.NoError(t, optimizeStorage(ctx, conn)) | ||
| require.NoError(t, conn.ExpectationsWereMet()) | ||
| }) | ||
|
|
||
| t.Run("vacuums edge only", func(t *testing.T) { | ||
| ctx := context.Background() | ||
| conn := newOptimizeStorageMockConn(t) | ||
|
|
||
| expectOptimizeStorageStats(conn, "node", 9, 91) | ||
| expectOptimizeStorageStats(conn, "edge", 10, 90) | ||
| expectOptimizeStorageVacuum(conn, "VACUUM (ANALYZE) edge") | ||
|
|
||
| require.NoError(t, optimizeStorage(ctx, conn)) | ||
| require.NoError(t, conn.ExpectationsWereMet()) | ||
| }) | ||
|
|
||
| t.Run("vacuums node and edge", func(t *testing.T) { | ||
| ctx := context.Background() | ||
| conn := newOptimizeStorageMockConn(t) | ||
|
|
||
| expectOptimizeStorageStats(conn, "node", 10, 90) | ||
| expectOptimizeStorageStats(conn, "edge", 10, 90) | ||
| expectOptimizeStorageVacuum(conn, "VACUUM (ANALYZE) node, edge") | ||
|
|
||
| require.NoError(t, optimizeStorage(ctx, conn)) | ||
| require.NoError(t, conn.ExpectationsWereMet()) | ||
| }) | ||
|
|
||
| t.Run("returns query error", func(t *testing.T) { | ||
| ctx := context.Background() | ||
| conn := newOptimizeStorageMockConn(t) | ||
| expectedErr := errors.New("stats unavailable") | ||
|
|
||
| conn.ExpectQuery(optimizeStorageStatsQuery). | ||
| WithArgs("node"). | ||
| WillReturnError(expectedErr) | ||
|
|
||
| err := optimizeStorage(ctx, conn) | ||
| require.ErrorIs(t, err, expectedErr) | ||
| require.ErrorContains(t, err, "query dead tuple stats for node") | ||
| require.NoError(t, conn.ExpectationsWereMet()) | ||
| }) | ||
| } | ||
|
|
||
| func newOptimizeStorageMockConn(t *testing.T) pgxmock.PgxConnIface { | ||
| t.Helper() | ||
|
|
||
| conn, err := pgxmock.NewConn(pgxmock.QueryMatcherOption(pgxmock.QueryMatcherEqual)) | ||
| require.NoError(t, err) | ||
|
|
||
| return conn | ||
| } | ||
|
|
||
| func expectOptimizeStorageStats(conn pgxmock.PgxConnIface, table string, dead, live int64) { | ||
| conn.ExpectQuery(optimizeStorageStatsQuery). | ||
| WithArgs(table). | ||
| WillReturnRows(pgxmock.NewRows([]string{"dead", "live"}).AddRow(dead, live)) | ||
| } | ||
|
|
||
| func expectOptimizeStorageVacuum(conn pgxmock.PgxConnIface, stmt string) { | ||
| conn.ExpectExec(stmt). | ||
| WithArgs(pgx.QueryExecModeSimpleProtocol). | ||
| WillReturnResult(pgxmock.NewResult("VACUUM", 0)) | ||
| } |
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
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
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be safe as the logic is currently written. The only ways around it are pretty complex for what we currently need, so as long as we don't allow targets to be modified by outside input (it remains strings we pull out of table queries), this should be safe enough.