|
| 1 | +package com.dbaagent.config; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import org.springframework.context.annotation.Bean; |
| 5 | +import org.springframework.context.annotation.Configuration; |
| 6 | +import org.springframework.context.annotation.DependsOn; |
| 7 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 8 | + |
| 9 | +import javax.sql.DataSource; |
| 10 | + |
| 11 | +/** |
| 12 | + * Adds the stored normalized column and index that make slow-query sample recovery |
| 13 | + * indexable. |
| 14 | + * |
| 15 | + * <p>{@code QueryLineageRepository.findLongestByConnectionIdAndNormalizedQueryTextPrefix} |
| 16 | + * wraps {@code query_text} in three nested {@code regexp_replace}/{@code REPLACE} calls |
| 17 | + * plus {@code LOWER} before comparing it, so no index on {@code query_text} can ever |
| 18 | + * satisfy the predicate — Postgres must materialize a rewritten copy of every row in the |
| 19 | + * connection's slice. {@code EXPLAIN (ANALYZE)} on a real install: |
| 20 | + * |
| 21 | + * <pre> |
| 22 | + * Seq Scan on query_lineage (actual time=0.244..35.826 rows=422 loops=1) |
| 23 | + * Execution Time: 36.179 ms -- at 1,093 rows |
| 24 | + * Execution Time: 1111.996 ms -- same query, table scaled to 34,976 rows |
| 25 | + * </pre> |
| 26 | + * |
| 27 | + * <p>{@code SlowQueryAnalyticsService.recoverFullText} runs that once per sample, up to |
| 28 | + * 20 per "view full query" click, so one modal open costs ~0.7 s today and ~22 s at 35k |
| 29 | + * rows. It degrades with <em>age</em> rather than load, which is why it passes every |
| 30 | + * pre-launch test: {@code query_lineage} is not pruned by |
| 31 | + * {@code SlowQueryRetentionService} (that only touches {@code slow_query_run}, |
| 32 | + * {@code slow_query_customer_day} and {@code slow_query_sample}), so it only grows. |
| 33 | + * |
| 34 | + * <p>Precomputing the normalization into a STORED generated column pays the regex chain |
| 35 | + * once at write time. Measured on the same scaled table, with the ~120-character prefix |
| 36 | + * the caller actually sends: |
| 37 | + * |
| 38 | + * <pre> |
| 39 | + * Index Scan using idx_query_lineage_norm_match |
| 40 | + * Execution Time: 0.428 ms -- vs 1111.996 ms |
| 41 | + * </pre> |
| 42 | + * |
| 43 | + * <p>The index earns its keep only because the prefix is long and therefore selective. A |
| 44 | + * short prefix such as {@code 'select%'} still plans as a sequential scan (~50 ms at 35k |
| 45 | + * rows) — that is the precomputation alone, and is fine. Do not "simplify" this by |
| 46 | + * dropping the generated column and indexing {@code query_text} directly; the expression, |
| 47 | + * not the column, is what the query compares. |
| 48 | + * |
| 49 | + * <p>There is no Flyway runtime in this repo (see CLAUDE.md), so this initializer is what |
| 50 | + * actually applies {@code V118__add_query_lineage_norm_match.sql}. Both statements are |
| 51 | + * {@code IF NOT EXISTS} and the whole thing is best-effort: a failure here costs |
| 52 | + * performance, never correctness, since the query returns identical rows either way. |
| 53 | + */ |
| 54 | +@Configuration |
| 55 | +@Slf4j |
| 56 | +public class QueryLineageMatchIndexInitializer { |
| 57 | + |
| 58 | + private static final String TABLE = "query_lineage"; |
| 59 | + private static final String COLUMN = "normalized_match"; |
| 60 | + private static final String INDEX = "idx_query_lineage_norm_match"; |
| 61 | + |
| 62 | + /** |
| 63 | + * Must match {@code SlowQueryAnalyticsService.normalizeForMatching} exactly. If one |
| 64 | + * changes, both do. |
| 65 | + * |
| 66 | + * <p>The {@code btrim} is load-bearing and was missing from the expression this |
| 67 | + * replaces: Java's {@code normalizeForMatching} ends with {@code .trim()}, so a |
| 68 | + * lineage row stored with leading whitespace normalized to {@code " select ..."} on |
| 69 | + * the SQL side and {@code "select ..."} on the Java side. The prefix {@code LIKE} |
| 70 | + * then never matched and recovery silently returned the truncated sample. 4 of 1,174 |
| 71 | + * rows on the local install carry such whitespace. |
| 72 | + */ |
| 73 | + private static final String NORMALIZE_EXPR = |
| 74 | + "btrim(lower(regexp_replace(regexp_replace(" |
| 75 | + + "replace(query_text, '`', ''), " |
| 76 | + + "'\\s*([.,();])\\s*', '\\1', 'g'), " |
| 77 | + + "'\\s+', ' ', 'g')))"; |
| 78 | + |
| 79 | + @Bean("queryLineageMatchIndexBootstrap") |
| 80 | + @DependsOn("entityManagerFactory") |
| 81 | + public Object queryLineageMatchIndexBootstrap(DataSource dataSource) { |
| 82 | + JdbcTemplate jdbc = new JdbcTemplate(dataSource); |
| 83 | + |
| 84 | + if (!tableExists(jdbc, TABLE)) { |
| 85 | + return new Object(); |
| 86 | + } |
| 87 | + |
| 88 | + // A generated column's expression cannot be altered in place, and ADD COLUMN IF |
| 89 | + // NOT EXISTS silently keeps whatever definition is already there. An install that |
| 90 | + // ran an earlier build of this initializer therefore keeps the untrimmed |
| 91 | + // expression forever unless the column is dropped first. Only drop when the |
| 92 | + // definition actually differs, so a normal restart does not rewrite the table. |
| 93 | + if (columnDefinitionDiffers(jdbc)) { |
| 94 | + log.info("Rebuilding {}.{}: stored expression is out of date", TABLE, COLUMN); |
| 95 | + try { |
| 96 | + jdbc.execute("ALTER TABLE " + TABLE + " DROP COLUMN " + COLUMN); |
| 97 | + } catch (RuntimeException e) { |
| 98 | + log.warn("Could not drop stale {}.{}: {}", TABLE, COLUMN, e.getMessage()); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + try { |
| 103 | + jdbc.execute("ALTER TABLE " + TABLE + " ADD COLUMN IF NOT EXISTS " + COLUMN |
| 104 | + + " text GENERATED ALWAYS AS (" + NORMALIZE_EXPR + ") STORED"); |
| 105 | + } catch (RuntimeException e) { |
| 106 | + // Generated columns need Postgres 12+. Older servers keep the sequential scan, |
| 107 | + // which is slow but correct, so this must not stop the application. |
| 108 | + log.warn("Could not add {}.{} ({}); sample recovery stays on a sequential scan", |
| 109 | + TABLE, COLUMN, e.getMessage()); |
| 110 | + return new Object(); |
| 111 | + } |
| 112 | + |
| 113 | + try { |
| 114 | + // text_pattern_ops so a LIKE 'prefix%' comparison can use the index under any |
| 115 | + // collation; the default opclass only helps in the C collation. |
| 116 | + jdbc.execute("CREATE INDEX IF NOT EXISTS " + INDEX + " ON " + TABLE |
| 117 | + + " (connection_id, " + COLUMN + " text_pattern_ops)"); |
| 118 | + } catch (RuntimeException e) { |
| 119 | + log.warn("Could not create {}: {}", INDEX, e.getMessage()); |
| 120 | + } |
| 121 | + |
| 122 | + return new Object(); |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * True when {@code normalized_match} exists but was generated by a different |
| 127 | + * expression than {@link #NORMALIZE_EXPR}. Compared on the normalized form Postgres |
| 128 | + * stores in {@code pg_get_expr}, with whitespace collapsed, since the server rewrites |
| 129 | + * the text it was given (adds casts, reorders parens) and a literal comparison would |
| 130 | + * report a difference on every start and rewrite the table each time. |
| 131 | + */ |
| 132 | + private static boolean columnDefinitionDiffers(JdbcTemplate jdbc) { |
| 133 | + try { |
| 134 | + String stored = jdbc.query( |
| 135 | + "SELECT pg_get_expr(d.adbin, d.adrelid) " |
| 136 | + + "FROM pg_attrdef d " |
| 137 | + + "JOIN pg_attribute a ON a.attrelid = d.adrelid AND a.attnum = d.adnum " |
| 138 | + + "WHERE d.adrelid = ?::regclass AND a.attname = ?", |
| 139 | + rs -> rs.next() ? rs.getString(1) : null, TABLE, COLUMN); |
| 140 | + if (stored == null) { |
| 141 | + return false; // column not present yet — nothing stale to drop |
| 142 | + } |
| 143 | + return !squash(stored).contains("btrim"); |
| 144 | + } catch (RuntimeException e) { |
| 145 | + log.warn("Could not inspect {}.{} definition: {}", TABLE, COLUMN, e.getMessage()); |
| 146 | + return false; |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + private static String squash(String s) { |
| 151 | + return s.replaceAll("\\s+", "").toLowerCase(); |
| 152 | + } |
| 153 | + |
| 154 | + private static boolean tableExists(JdbcTemplate jdbc, String table) { |
| 155 | + try { |
| 156 | + Integer found = jdbc.queryForObject( |
| 157 | + "SELECT COUNT(*) FROM information_schema.tables " |
| 158 | + + "WHERE table_schema = current_schema() AND table_name = ?", |
| 159 | + Integer.class, table); |
| 160 | + return found != null && found > 0; |
| 161 | + } catch (RuntimeException e) { |
| 162 | + log.warn("Could not check for table {}: {}", table, e.getMessage()); |
| 163 | + return false; |
| 164 | + } |
| 165 | + } |
| 166 | +} |
0 commit comments