Module: SqlGenius::AiFeatures

Extended by:
ActiveSupport::Concern
Included in:
QueriesController
Defined in:
app/controllers/concerns/sql_genius/ai_features.rb

Instance Method Summary collapse

Instance Method Details

#anomaly_detectionObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 88

def anomaly_detection
  return ai_not_configured unless sql_genius_config.ai_enabled?
  return ai_unsupported_on_postgresql("Anomaly detection") if connected_to_postgresql?

  connection = ActiveRecord::Base.connection

  # Gather recent slow queries
  slow_data = []
  if sql_genius_config.redis_url
    redis = Redis.new(url: sql_genius_config.redis_url)
    raw = redis.lrange(SlowQueryMonitor.redis_key, 0, 99)
    slow_data = raw.map do |e|
      JSON.parse(e)
    rescue
      nil
    end.compact
  end

  # Gather top query stats
  stats = []
  begin
    results = connection.exec_query(<<~SQL)
      SELECT DIGEST_TEXT, COUNT_STAR AS calls,
        ROUND(SUM_TIMER_WAIT / 1000000000, 1) AS total_time_ms,
        ROUND(AVG_TIMER_WAIT / 1000000000, 1) AS avg_time_ms,
        SUM_ROWS_EXAMINED AS rows_examined, SUM_ROWS_SENT AS rows_sent,
        FIRST_SEEN, LAST_SEEN
      FROM performance_schema.events_statements_summary_by_digest
      WHERE SCHEMA_NAME = #{connection.quote(connection.current_database)}
        AND DIGEST_TEXT IS NOT NULL
      ORDER BY SUM_TIMER_WAIT DESC LIMIT 30
    SQL
    stats = results.rows.map { |r| { sql: r[0].to_s.truncate(200), calls: r[1], total_ms: r[2], avg_ms: r[3], rows_examined: r[4], rows_sent: r[5], first_seen: r[6], last_seen: r[7] } }
  rescue
    # performance_schema may not be available
  end

  slow_summary = slow_data.first(50).map { |q| "#{q["duration_ms"]}ms @ #{q["timestamp"]}: #{q["sql"].to_s.truncate(150)}" }.join("\n")
  stats_summary = stats.map { |q| "calls=#{q[:calls]} avg=#{q[:avg_ms]}ms total=#{q[:total_ms]}ms exam=#{q[:rows_examined]} sent=#{q[:rows_sent]}: #{q[:sql]}" }.join("\n")
  domain_ctx = sql_genius_config.ai_system_context.present? ? "\nDomain context:\n#{sql_genius_config.ai_system_context}" : ""

  messages = [
    { role: "system", content: <<~PROMPT },
      You are a MySQL query anomaly detector. Analyze the following query data and identify:
      1. Queries with degrading performance (high avg time relative to complexity)
      2. N+1 query patterns (same template called many times in short windows)
      3. Full table scans (rows_examined >> rows_sent)
      4. Sudden new query patterns that may indicate code changes
      5. Queries creating excessive temp tables or sorts
      #{domain_ctx}

      Respond with JSON: {"report": "markdown-formatted health report organized by severity. For each finding, explain the issue, affected query, and recommended fix."}
    PROMPT
    { role: "user", content: "Recent Slow Queries (last #{slow_data.size}):\n#{slow_summary.presence || "None captured"}\n\nTop Queries by Total Time:\n#{stats_summary.presence || "Not available"}" },
  ]

  result = ai_client.chat(messages: messages)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Anomaly detection failed: #{e.message}" }, status: :unprocessable_entity)
end

#connection_advisorObject



246
247
248
249
250
251
252
253
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 246

def connection_advisor
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::ConnectionAdvisor.new(ai_client, ai_config_for_core, rails_connection).call
  render(json: result)
rescue StandardError => e
  render(json: { error: "Connection advisor failed: #{e.message}" }, status: :unprocessable_entity)
end

#describe_queryObject



42
43
44
45
46
47
48
49
50
51
52
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 42

def describe_query
  return ai_not_configured unless sql_genius_config.ai_enabled?

  sql = params[:sql].to_s.strip
  return render(json: { error: "SQL is required." }, status: :unprocessable_entity) if sql.blank?

  result = SqlGenius::Core::Ai::DescribeQuery.new(ai_client, ai_config_for_core).call(sql)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Explanation failed: #{e.message}" }, status: :unprocessable_entity)
end

#index_advisorObject



75
76
77
78
79
80
81
82
83
84
85
86
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 75

def index_advisor
  return ai_not_configured unless sql_genius_config.ai_enabled?

  sql = params[:sql].to_s.strip
  explain_rows = Array(params[:explain_rows]).map { |row| row.respond_to?(:values) ? row.values : Array(row) }
  return render(json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity) if sql.blank? || explain_rows.blank?

  result = SqlGenius::Core::Ai::IndexAdvisor.new(ai_client, ai_config_for_core, rails_connection).call(sql, explain_rows)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Index advisor failed: #{e.message}" }, status: :unprocessable_entity)
end

#index_plannerObject



273
274
275
276
277
278
279
280
281
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 273

def index_planner
  return ai_not_configured unless sql_genius_config.ai_enabled?

  tables = params[:tables].present? ? Array(params[:tables]) : nil
  result = SqlGenius::Core::Ai::IndexPlanner.new(ai_client, ai_config_for_core, rails_connection).call(tables)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Index planner failed: #{e.message}" }, status: :unprocessable_entity)
end

#innodb_healthObject



264
265
266
267
268
269
270
271
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 264

def innodb_health
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::InnodbInterpreter.new(ai_client, ai_config_for_core, rails_connection).call
  render(json: result)
rescue StandardError => e
  render(json: { error: "InnoDB health analysis failed: #{e.message}" }, status: :unprocessable_entity)
end

#migration_riskObject



225
226
227
228
229
230
231
232
233
234
235
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 225

def migration_risk
  return ai_not_configured unless sql_genius_config.ai_enabled?

  migration_sql = params[:migration].to_s.strip
  return render(json: { error: "Migration SQL or Ruby code is required." }, status: :unprocessable_entity) if migration_sql.blank?

  result = SqlGenius::Core::Ai::MigrationRisk.new(ai_client, ai_config_for_core, rails_connection).call(migration_sql)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Migration risk assessment failed: #{e.message}" }, status: :unprocessable_entity)
end

#optimizeObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 23

def optimize
  unless sql_genius_config.ai_enabled?
    return render(json: { error: "AI features are not configured." }, status: :not_found)
  end

  sql = params[:sql].to_s.strip
  explain_rows = Array(params[:explain_rows]).map { |row| row.respond_to?(:values) ? row.values : Array(row) }

  if sql.blank? || explain_rows.blank?
    return render(json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity)
  end

  service = SqlGenius::Core::Ai::Optimization.new(rails_connection, ai_client, ai_config_for_core)
  result = service.call(sql, explain_rows, queryable_tables)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Optimization failed: #{e.message}" }, status: :unprocessable_entity)
end

#pattern_grouperObject



283
284
285
286
287
288
289
290
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 283

def pattern_grouper
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::PatternGrouper.new(rails_connection, ai_client, ai_config_for_core).call
  render(json: result)
rescue StandardError => e
  render(json: { error: "Pattern grouper failed: #{e.message}" }, status: :unprocessable_entity)
end

#rewrite_queryObject



63
64
65
66
67
68
69
70
71
72
73
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 63

def rewrite_query
  return ai_not_configured unless sql_genius_config.ai_enabled?

  sql = params[:sql].to_s.strip
  return render(json: { error: "SQL is required." }, status: :unprocessable_entity) if sql.blank?

  result = SqlGenius::Core::Ai::RewriteQuery.new(ai_client, ai_config_for_core, rails_connection).call(sql)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Rewrite failed: #{e.message}" }, status: :unprocessable_entity)
end

#root_causeObject



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 150

def root_cause
  return ai_not_configured unless sql_genius_config.ai_enabled?
  return ai_unsupported_on_postgresql("Root cause analysis") if connected_to_postgresql?

  connection = ActiveRecord::Base.connection

  # PROCESSLIST
  processlist = connection.exec_query("SHOW FULL PROCESSLIST")
  process_info = processlist.rows.map { |r| "ID=#{r[0]} User=#{r[1]} Host=#{r[2]} DB=#{r[3]} Command=#{r[4]} Time=#{r[5]}s State=#{r[6]} SQL=#{r[7].to_s.truncate(200)}" }.join("\n")

  # Key status variables
  status_rows = connection.exec_query("SHOW GLOBAL STATUS")
  status = {}
  status_rows.each { |r| status[(r["Variable_name"] || r["variable_name"]).to_s] = (r["Value"] || r["value"]).to_s }

  key_stats = [
    "Threads_connected",
    "Threads_running",
    "Innodb_row_lock_waits",
    "Innodb_row_lock_current_waits",
    "Innodb_buffer_pool_reads",
    "Innodb_buffer_pool_read_requests",
    "Slow_queries",
    "Created_tmp_disk_tables",
    "Connections",
    "Aborted_connects",
  ].map { |k| "#{k}=#{status[k]}" }.join(", ")

  # InnoDB status (truncated)
  innodb_status = ""
  begin
    result = connection.exec_query("SHOW ENGINE INNODB STATUS")
    innodb_status = result.rows.first&.last.to_s.truncate(3000)
  rescue ActiveRecord::StatementInvalid
    # InnoDB status may be unavailable depending on MySQL user privileges
  end

  # Recent slow queries
  slow_summary = ""
  if sql_genius_config.redis_url
    redis = Redis.new(url: sql_genius_config.redis_url)
    raw = redis.lrange(SlowQueryMonitor.redis_key, 0, 19)
    slows = raw.map do |e|
      JSON.parse(e)
    rescue
      nil
    end.compact
    slow_summary = slows.map { |q| "#{q["duration_ms"]}ms: #{q["sql"].to_s.truncate(150)}" }.join("\n")
  end

  domain_ctx = sql_genius_config.ai_system_context.present? ? "\nDomain context:\n#{sql_genius_config.ai_system_context}" : ""

  messages = [
    { role: "system", content: <<~PROMPT },
      You are a MySQL incident responder. The user is asking "why is the database slow right now?" Analyze the provided data and give a root cause diagnosis. Consider:
      - Lock contention (row locks, metadata locks, table locks)
      - Long-running queries blocking others
      - Connection exhaustion
      - Buffer pool thrashing (low hit rate)
      - Disk I/O saturation
      - Replication lag
      - Unusual query patterns
      #{domain_ctx}

      Respond with JSON: {"diagnosis": "markdown-formatted root cause analysis. Start with a 1-2 sentence summary, then detailed findings. Include specific actionable steps to resolve the issue."}
    PROMPT
    { role: "user", content: "PROCESSLIST:\n#{process_info}\n\nKey Status:\n#{key_stats}\n\nInnoDB Status (excerpt):\n#{innodb_status.presence || "Not available"}\n\nRecent Slow Queries:\n#{slow_summary.presence || "None captured"}" },
  ]

  result = ai_client.chat(messages: messages)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Root cause analysis failed: #{e.message}" }, status: :unprocessable_entity)
end

#schema_reviewObject



54
55
56
57
58
59
60
61
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 54

def schema_review
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::SchemaReview.new(ai_client, ai_config_for_core, rails_connection).call(params[:table].to_s.strip.presence)
  render(json: result)
rescue StandardError => e
  render(json: { error: "Schema review failed: #{e.message}" }, status: :unprocessable_entity)
end

#suggestObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 7

def suggest
  unless sql_genius_config.ai_enabled?
    return render(json: { error: "AI features are not configured." }, status: :not_found)
  end

  prompt = params[:prompt].to_s.strip
  return render(json: { error: "Please describe what you want to query." }, status: :unprocessable_entity) if prompt.blank?

  service = SqlGenius::Core::Ai::Suggestion.new(rails_connection, ai_client, ai_config_for_core)
  result = service.call(prompt, queryable_tables)
  sql = sanitize_ai_sql(result["sql"].to_s)
  render(json: { sql: sql, explanation: result["explanation"] })
rescue StandardError => e
  render(json: { error: "AI suggestion failed: #{e.message}" }, status: :unprocessable_entity)
end

#variable_reviewObject



237
238
239
240
241
242
243
244
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 237

def variable_review
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::VariableReviewer.new(ai_client, ai_config_for_core, rails_connection).call
  render(json: result)
rescue StandardError => e
  render(json: { error: "Variable review failed: #{e.message}" }, status: :unprocessable_entity)
end

#workload_digestObject



255
256
257
258
259
260
261
262
# File 'app/controllers/concerns/sql_genius/ai_features.rb', line 255

def workload_digest
  return ai_not_configured unless sql_genius_config.ai_enabled?

  result = SqlGenius::Core::Ai::WorkloadDigest.new(rails_connection, ai_client, ai_config_for_core).call
  render(json: result)
rescue StandardError => e
  render(json: { error: "Workload digest failed: #{e.message}" }, status: :unprocessable_entity)
end