Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Procfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
web: bundle exec puma -C config/puma.rb
release: bundle exec rails db:migrate && bundle exec rake integration_tests:dispatch
worker: bundle exec good_job start --max-threads=8
worker: DB_POOL=${WORKER_DB_POOL:-25} bundle exec good_job start --max-threads=8
44 changes: 44 additions & 0 deletions app/controllers/api/ai_hints_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

module Api
class AiHintsController < ApiController
Comment thread
cocomarine marked this conversation as resolved.
Resolved
MAX_REQUEST_SIZE_KB = 100

before_action :authorize_user
before_action :check_feature_flag
before_action :check_request_size, only: :create
skip_authorization_check

def show
ai_hint = AiHint.find_by!(id: params.expect(:id), user_id: current_user.id)

render json: { status: ai_hint.status, hint: ai_hint.hint }.compact, status: :ok
end

def create
params.require(%i[message trace runtime code])

ai_hint = AiHint.create!(
user_id: current_user.id,
input: params.permit(:message, :trace, :runtime, :code).to_h
)
GenerateAiHintJob.perform_later(ai_hint_id: ai_hint.id)

render json: { id: ai_hint.id }, status: :accepted
end

private

def check_feature_flag
return if FeatureFlagHelpers.enabled_for_user?(:ai_friendly_errors, current_user, current_user&.schools&.first)

render json: {}, status: :unauthorized
end

def check_request_size
return if request.body.size <= MAX_REQUEST_SIZE_KB.kilobytes

render json: { error: "The request was over the max size of #{MAX_REQUEST_SIZE_KB} KB" }, status: :content_too_large
end
end
end
35 changes: 35 additions & 0 deletions app/jobs/generate_ai_hint_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

class GenerateAiHintJob < ApplicationJob
# How long editor-ui polls for a hint before giving up.
UI_POLL_TIMEOUT = 30.seconds

# A hint must leave enough time for inference to finish before editor-ui stops polling.
MAX_QUEUE_WAIT = UI_POLL_TIMEOUT - FriendlyErrorMessagesInferenceClient::TIMEOUT

queue_as :ai_hints

def perform(ai_hint_id:)
ai_hint = AiHint.find(ai_hint_id)
return unless ai_hint.pending?
return ai_hint.fail! if ai_hint.created_at < MAX_QUEUE_WAIT.ago

input = ai_hint.input
hint = FriendlyErrorMessagesInferenceClient.new.get_message(
input['message'],
input['trace'],
input['runtime'],
input['code']
)

ai_hint.complete!(hint)
rescue FriendlyErrorMessagesInferenceClient::Error => e
Sentry.capture_exception(e)
ai_hint.fail!
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
Comment thread
cocomarine marked this conversation as resolved.
Dismissed
rescue StandardError
# Don't leave the hint stuck in pending holding the input; re-raise so
# GoodJob records the failure and sentry-rails reports it.
ai_hint&.fail!
raise
end
end
11 changes: 11 additions & 0 deletions app/jobs/remove_old_ai_hints_job.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true

class RemoveOldAiHintsJob < ApplicationJob
MAX_AGE = 1.day

queue_as :default

def perform
AiHint.where(created_at: ...MAX_AGE.ago).in_batches.delete_all
end
end
15 changes: 15 additions & 0 deletions app/models/ai_hint.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

class AiHint < ApplicationRecord
enum :status, { pending: 'pending', completed: 'completed', failed: 'failed' }, default: :pending, validate: true

validates :user_id, presence: true

def complete!(hint)
update!(status: :completed, hint:, input: nil)
end

def fail!
update!(status: :failed, input: nil)
end
end
4 changes: 2 additions & 2 deletions config/database.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ default: &default
port: <%= ENV.fetch('POSTGRES_PORT', '5432') %>
username: <%= ENV.fetch('POSTGRES_USER', 'no_pg_user_set') %>
password: <%= ENV.fetch('POSTGRES_PASSWORD', '') %>
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
pool: <%= ENV.fetch('DB_POOL') { ENV.fetch('RAILS_MAX_THREADS', 5) } %>

salesforce_connect: &salesforce_connect
adapter: postgresql
Expand All @@ -14,7 +14,7 @@ salesforce_connect: &salesforce_connect
port: <%= ENV.fetch('SALESFORCE_CONNECT_PORT', ENV.fetch('POSTGRES_PORT', '5432')) %>
username: <%= ENV.fetch('SALESFORCE_CONNECT_USER', ENV.fetch('POSTGRES_USER', 'no_pg_user_set')) %>
password: <%= ENV.fetch('SALESFORCE_CONNECT_PASSWORD', ENV.fetch('POSTGRES_PASSWORD', '')) %>
pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
pool: <%= ENV.fetch('DB_POOL') { ENV.fetch('RAILS_MAX_THREADS', 5) } %>
database_tasks: false

development:
Expand Down
19 changes: 18 additions & 1 deletion config/initializers/good_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,22 @@ def authenticate_admin
# The create_students_job queue is a serial queue that allows only one job at a time.
# DO NOT change the value of create_students_job:1 without understanding the implications
# of processing more than one user creation job at once.
config.good_job.queues = 'create_students_job:1;import_schools_job:1;salesforce_sync:10;default:5'
#
# GOOD_JOB_QUEUES lets smaller environments (e.g. staging, with a 20-connection DB)
# run fewer threads. Keep the total thread count within the worker's DB pool
# (WORKER_DB_POOL in the Procfile), leaving a couple spare for GoodJob itself.
config.good_job.queues = ENV.fetch(
'GOOD_JOB_QUEUES',
'create_students_job:1;import_schools_job:1;salesforce_sync:10;default:5;ai_hints:5'
)
Comment thread
cocomarine marked this conversation as resolved.
Resolved

config.good_job.enable_cron = true
config.good_job.cron = {
remove_old_ai_hints: {
cron: '0 0 * * 6', # every Saturday at midnight
class: 'RemoveOldAiHintsJob',
description:
'At midnight every Saturday, remove ai_hints rows older than a day.'
}
}
end
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
resources :events, only: %i[create]

post '/friendly_error_messages', to: 'friendly_error_messages#show'
resources :ai_hints, only: %i[create show]
end

resource :github_webhooks, only: :create, defaults: { formats: :json }
Expand Down
15 changes: 15 additions & 0 deletions db/migrate/20261124143007_create_ai_hints.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

class CreateAiHints < ActiveRecord::Migration[8.1]
def change
create_table :ai_hints, id: :uuid do |t|
t.uuid :user_id, null: false
t.string :status, null: false, default: 'pending'
t.jsonb :input
t.text :hint
t.timestamps
end

add_index :ai_hints, :user_id
end
end
12 changes: 11 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion lib/friendly_error_messages_inference_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ class FriendlyErrorMessagesInferenceClient
class Error < StandardError; end

MAX_COMPLETION_TOKENS = 300
TIMEOUT = 15.seconds

SYSTEM_PROMPT = Rails.root.join('config/friendly_error_messages_prompt.md').read

def initialize
@client = OpenAI::Client.new(
base_url: "#{ENV.fetch('FEM_INFERENCE_API_URL', '')}/ai/v1",
api_key: ENV.fetch('FEM_INFERENCE_API_KEY', ''),
timeout: 15.0,
timeout: TIMEOUT.to_f,
max_retries: 0
)
end
Expand Down
8 changes: 8 additions & 0 deletions spec/factories/ai_hint.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# frozen_string_literal: true

FactoryBot.define do
factory :ai_hint do
user_id { SecureRandom.uuid }
input { { 'message' => 'NameError', 'trace' => 'line 1', 'runtime' => 'python', 'code' => 'print(x)' } }
end
end
76 changes: 76 additions & 0 deletions spec/jobs/generate_ai_hint_job_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe GenerateAiHintJob do
let(:ai_hint) { create(:ai_hint) }
let(:client) { instance_double(FriendlyErrorMessagesInferenceClient) }

before do
allow(FriendlyErrorMessagesInferenceClient).to receive(:new).and_return(client)
allow(client).to receive(:get_message).and_return('Check the variable name')
allow(Sentry).to receive(:capture_exception)
end

it 'uses the ai_hints queue' do
expect(described_class.new.queue_name).to eq('ai_hints')
end

it 'passes the input to the inference client' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(client).to have_received(:get_message).with('NameError', 'line 1', 'python', 'print(x)')
end

it 'saves the hint and marks it completed' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(ai_hint.reload).to have_attributes(status: 'completed', hint: 'Check the variable name', input: nil)
end

context 'when the hint waited too long in the queue' do
let(:ai_hint) { create(:ai_hint, created_at: (described_class::MAX_QUEUE_WAIT + 1.second).ago) }

it 'marks it failed' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(ai_hint.reload).to have_attributes(status: 'failed', input: nil)
end

it 'does not call the inference client' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(client).not_to have_received(:get_message)
end
end

context 'when the hint is no longer pending' do
let(:ai_hint) { create(:ai_hint, status: :completed, hint: 'Existing hint') }

it 'does not call the inference client' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(client).not_to have_received(:get_message)
end
end

context 'when the inference client fails' do
let(:error) { FriendlyErrorMessagesInferenceClient::Error.new('boom') }

before { allow(client).to receive(:get_message).and_raise(error) }

it 'marks it failed' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(ai_hint.reload).to have_attributes(status: 'failed', hint: nil, input: nil)
end

it 'reports the error to Sentry' do
described_class.perform_now(ai_hint_id: ai_hint.id)
expect(Sentry).to have_received(:capture_exception).with(error)
end
end

context 'when an unexpected error is raised' do
before { allow(client).to receive(:get_message).and_raise(StandardError, 'boom') }

it 'marks it failed and re-raises the error' do
expect { described_class.perform_now(ai_hint_id: ai_hint.id) }.to raise_error(StandardError, 'boom')
expect(ai_hint.reload).to have_attributes(status: 'failed', hint: nil, input: nil)
end
end
end
15 changes: 15 additions & 0 deletions spec/jobs/remove_old_ai_hints_job_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe RemoveOldAiHintsJob do
it 'removes hints older than a day and keeps newer ones' do
old_hint = create(:ai_hint, created_at: 2.days.ago)
new_hint = create(:ai_hint, created_at: 1.hour.ago)

described_class.perform_now

expect(AiHint.pluck(:id)).to contain_exactly(new_hint.id)
expect(AiHint.exists?(old_hint.id)).to be(false)
end
end
55 changes: 55 additions & 0 deletions spec/models/ai_hint_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# frozen_string_literal: true

require 'rails_helper'

RSpec.describe AiHint do
subject(:ai_hint) { build(:ai_hint) }

describe 'validations' do
it 'has a valid factory' do
expect(ai_hint).to be_valid
end

it 'requires a user_id' do
ai_hint.user_id = nil
expect(ai_hint).not_to be_valid
end

it 'rejects an unknown status' do
ai_hint.status = 'random'
expect(ai_hint).not_to be_valid
end
end

it 'defaults to pending' do
expect(described_class.new).to be_pending
end

describe '#complete!' do
before { ai_hint.save! }

it 'saves the hint and marks it completed' do
ai_hint.complete!('Check the variable name')
expect(ai_hint.reload).to have_attributes(status: 'completed', hint: 'Check the variable name')
end

it 'clears the input' do
ai_hint.complete!('Check the variable name')
expect(ai_hint.reload.input).to be_nil
end
end

describe '#fail!' do
before { ai_hint.save! }

it 'marks it failed without a hint' do
ai_hint.fail!
expect(ai_hint.reload).to have_attributes(status: 'failed', hint: nil)
end

it 'clears the input' do
ai_hint.fail!
expect(ai_hint.reload.input).to be_nil
end
end
end
Loading
Loading