|
1 | 1 | package pg |
2 | 2 |
|
3 | | -import "context" |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "log/slog" |
| 7 | +) |
4 | 8 |
|
5 | | -// Optimize satisfies the graph.Optimizer interface. The body is currently a |
6 | | -// no-op stub; the actual index maintenance logic (assessment via pgstattuple |
7 | | -// followed by REINDEX CONCURRENTLY of bloated indexes) is implemented in a |
8 | | -// later phase. |
| 9 | +const ( |
| 10 | + // bloatedIndexLeafDensityThreshold is the average leaf-page fill percentage |
| 11 | + // below which a btree index is considered dense enough that REINDEX would |
| 12 | + // reclaim significant space. Calibrated against seven production tenant |
| 13 | + // samples whose live indexes regularly fell to 21-55%, against a freshly |
| 14 | + // rebuilt baseline (edge_1_pkey on a recently restored tenant) of 73.8%. |
| 15 | + bloatedIndexLeafDensityThreshold = 60.0 |
| 16 | + |
| 17 | + // highIndexFragmentationThreshold is the leaf-page fragmentation percentage |
| 18 | + // at or above which a btree index has accumulated enough out-of-order page |
| 19 | + // splits to warrant a rebuild even when leaf density alone has not crossed |
| 20 | + // its threshold. |
| 21 | + highIndexFragmentationThreshold = 40.0 |
| 22 | +) |
| 23 | + |
| 24 | +const ( |
| 25 | + sqlPgstattupleInstalled = `select exists(select 1 from pg_extension where extname = 'pgstattuple')` |
| 26 | + |
| 27 | + sqlSelectGraphPartitionBtreeIndexes = ` |
| 28 | + select i.oid as index_oid, |
| 29 | + n.nspname as schema_name, |
| 30 | + c.relname as table_name, |
| 31 | + i.relname as index_name, |
| 32 | + pg_relation_size(i.oid) as index_size_bytes |
| 33 | + from pg_inherits inh |
| 34 | + join pg_class p on p.oid = inh.inhparent |
| 35 | + join pg_class c on c.oid = inh.inhrelid |
| 36 | + join pg_namespace n on n.oid = c.relnamespace |
| 37 | + join pg_index x on x.indrelid = c.oid |
| 38 | + join pg_class i on i.oid = x.indexrelid |
| 39 | + join pg_am a on a.oid = i.relam |
| 40 | + where p.relname in ('node', 'edge') |
| 41 | + and p.relnamespace = n.oid |
| 42 | + and a.amname = 'btree' |
| 43 | + order by c.relname, i.relname` |
| 44 | + |
| 45 | + sqlSelectIndexBloatMetrics = `select avg_leaf_density, leaf_fragmentation from pgstatindex($1::regclass)` |
| 46 | +) |
| 47 | + |
| 48 | +// indexRow is a candidate index discovered by the listing query, prior to |
| 49 | +// per-index pgstatindex assessment. |
| 50 | +type indexRow struct { |
| 51 | + oid uint32 |
| 52 | + schema string |
| 53 | + table string |
| 54 | + index string |
| 55 | + sizeBytes int64 |
| 56 | +} |
| 57 | + |
| 58 | +// indexCandidate is an index whose pgstatindex measurement caused it to be |
| 59 | +// flagged for rebuild by needsReindex. |
| 60 | +type indexCandidate struct { |
| 61 | + indexRow |
| 62 | + leafDensity float64 |
| 63 | + fragmentation float64 |
| 64 | + reason string |
| 65 | +} |
| 66 | + |
| 67 | +// Optimize satisfies the graph.Optimizer interface. The current phase performs |
| 68 | +// a read-only assessment: it identifies btree indexes on partitions of the |
| 69 | +// node and edge tables whose leaf density or fragmentation cross the rebuild |
| 70 | +// thresholds and logs the candidates. No DDL is executed in this phase. |
9 | 71 | func (s *Driver) Optimize(ctx context.Context) error { |
| 72 | + if installed, err := s.pgstattupleInstalled(ctx); err != nil { |
| 73 | + return fmt.Errorf("checking pgstattuple extension: %w", err) |
| 74 | + } else if !installed { |
| 75 | + slog.WarnContext(ctx, "Index optimization skipped: pgstattuple extension is not installed; verify the DAWGS schema bootstrap completed successfully") |
| 76 | + return nil |
| 77 | + } |
| 78 | + |
| 79 | + indexes, err := s.listGraphPartitionBtreeIndexes(ctx) |
| 80 | + if err != nil { |
| 81 | + return fmt.Errorf("listing graph partition btree indexes: %w", err) |
| 82 | + } |
| 83 | + |
| 84 | + slog.InfoContext(ctx, fmt.Sprintf("Index optimization assessment starting: %d btree index(es) under consideration", len(indexes))) |
| 85 | + |
| 86 | + var ( |
| 87 | + candidates []indexCandidate |
| 88 | + totalBytes int64 |
| 89 | + ) |
| 90 | + for _, idx := range indexes { |
| 91 | + density, fragmentation, err := s.measureIndexBloat(ctx, idx.oid) |
| 92 | + if err != nil { |
| 93 | + slog.WarnContext(ctx, fmt.Sprintf("Skipping bloat assessment for index %s.%s: %v", idx.schema, idx.index, err)) |
| 94 | + continue |
| 95 | + } |
| 96 | + |
| 97 | + candidate := indexCandidate{indexRow: idx, leafDensity: density, fragmentation: fragmentation} |
| 98 | + if reason, flagged := needsReindex(candidate); flagged { |
| 99 | + candidate.reason = reason |
| 100 | + candidates = append(candidates, candidate) |
| 101 | + totalBytes += candidate.sizeBytes |
| 102 | + slog.InfoContext(ctx, fmt.Sprintf( |
| 103 | + "Index optimization candidate: %s.%s on %s (size=%d bytes, leaf_density=%.1f%%, fragmentation=%.1f%%, reason=%s)", |
| 104 | + candidate.schema, candidate.index, candidate.table, |
| 105 | + candidate.sizeBytes, candidate.leafDensity, candidate.fragmentation, candidate.reason, |
| 106 | + )) |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + slog.InfoContext(ctx, fmt.Sprintf( |
| 111 | + "Index optimization assessment complete: %d candidate(s) totaling %d bytes", |
| 112 | + len(candidates), totalBytes, |
| 113 | + )) |
10 | 114 | return nil |
11 | 115 | } |
| 116 | + |
| 117 | +// needsReindex applies the rebuild thresholds to a measured index and returns |
| 118 | +// a short human-readable reason when the index is flagged. Pure function; |
| 119 | +// unit-tested in optimize_test.go. |
| 120 | +func needsReindex(c indexCandidate) (string, bool) { |
| 121 | + if c.leafDensity < bloatedIndexLeafDensityThreshold { |
| 122 | + return fmt.Sprintf("leaf density %.1f%% below %.1f%% threshold", c.leafDensity, bloatedIndexLeafDensityThreshold), true |
| 123 | + } |
| 124 | + if c.fragmentation >= highIndexFragmentationThreshold { |
| 125 | + return fmt.Sprintf("fragmentation %.1f%% at or above %.1f%% threshold", c.fragmentation, highIndexFragmentationThreshold), true |
| 126 | + } |
| 127 | + return "", false |
| 128 | +} |
| 129 | + |
| 130 | +func (s *Driver) pgstattupleInstalled(ctx context.Context) (bool, error) { |
| 131 | + var installed bool |
| 132 | + if err := s.pool.QueryRow(ctx, sqlPgstattupleInstalled).Scan(&installed); err != nil { |
| 133 | + return false, err |
| 134 | + } |
| 135 | + return installed, nil |
| 136 | +} |
| 137 | + |
| 138 | +func (s *Driver) listGraphPartitionBtreeIndexes(ctx context.Context) ([]indexRow, error) { |
| 139 | + rows, err := s.pool.Query(ctx, sqlSelectGraphPartitionBtreeIndexes) |
| 140 | + if err != nil { |
| 141 | + return nil, err |
| 142 | + } |
| 143 | + defer rows.Close() |
| 144 | + |
| 145 | + var out []indexRow |
| 146 | + for rows.Next() { |
| 147 | + var r indexRow |
| 148 | + if err := rows.Scan(&r.oid, &r.schema, &r.table, &r.index, &r.sizeBytes); err != nil { |
| 149 | + return nil, err |
| 150 | + } |
| 151 | + out = append(out, r) |
| 152 | + } |
| 153 | + return out, rows.Err() |
| 154 | +} |
| 155 | + |
| 156 | +func (s *Driver) measureIndexBloat(ctx context.Context, indexOID uint32) (float64, float64, error) { |
| 157 | + var density, fragmentation float64 |
| 158 | + if err := s.pool.QueryRow(ctx, sqlSelectIndexBloatMetrics, indexOID).Scan(&density, &fragmentation); err != nil { |
| 159 | + return 0, 0, err |
| 160 | + } |
| 161 | + return density, fragmentation, nil |
| 162 | +} |
0 commit comments