diff --git a/Procfile b/Procfile index 73f55236b..c9cc92803 100644 --- a/Procfile +++ b/Procfile @@ -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 diff --git a/app/controllers/api/ai_hints_controller.rb b/app/controllers/api/ai_hints_controller.rb new file mode 100644 index 000000000..03cd03bd3 --- /dev/null +++ b/app/controllers/api/ai_hints_controller.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +module Api + class AiHintsController < ApiController + 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 diff --git a/app/jobs/generate_ai_hint_job.rb b/app/jobs/generate_ai_hint_job.rb new file mode 100644 index 000000000..5d8bd0ed2 --- /dev/null +++ b/app/jobs/generate_ai_hint_job.rb @@ -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! + 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 diff --git a/app/jobs/remove_old_ai_hints_job.rb b/app/jobs/remove_old_ai_hints_job.rb new file mode 100644 index 000000000..5c0dc30ba --- /dev/null +++ b/app/jobs/remove_old_ai_hints_job.rb @@ -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 diff --git a/app/models/ai_hint.rb b/app/models/ai_hint.rb new file mode 100644 index 000000000..ff0b3684e --- /dev/null +++ b/app/models/ai_hint.rb @@ -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 diff --git a/config/database.yml b/config/database.yml index d1044455b..4780c9b48 100644 --- a/config/database.yml +++ b/config/database.yml @@ -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 @@ -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: diff --git a/config/initializers/good_job.rb b/config/initializers/good_job.rb index b31cd2561..0feb21b59 100644 --- a/config/initializers/good_job.rb +++ b/config/initializers/good_job.rb @@ -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' + ) + + 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 diff --git a/config/routes.rb b/config/routes.rb index 2e24fc9de..d6da0c592 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -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 } diff --git a/db/migrate/20261124143007_create_ai_hints.rb b/db/migrate/20261124143007_create_ai_hints.rb new file mode 100644 index 000000000..cd5e83715 --- /dev/null +++ b/db/migrate/20261124143007_create_ai_hints.rb @@ -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 diff --git a/db/schema.rb b/db/schema.rb index 4859a5feb..d166c495e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_17_120139) do +ActiveRecord::Schema[8.1].define(version: 2026_11_24_143007) do # These are extensions that must be enabled in order to support this database enable_extension "pg_catalog.plpgsql" enable_extension "pgcrypto" @@ -43,6 +43,16 @@ t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true end + create_table "ai_hints", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t| + t.datetime "created_at", null: false + t.text "hint" + t.jsonb "input" + t.string "status", default: "pending", null: false + t.datetime "updated_at", null: false + t.uuid "user_id", null: false + t.index ["user_id"], name: "index_ai_hints_on_user_id" + end + create_table "class_students", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t| t.datetime "created_at", null: false t.uuid "school_class_id", null: false diff --git a/lib/friendly_error_messages_inference_client.rb b/lib/friendly_error_messages_inference_client.rb index 6e6b0ed6b..912432164 100644 --- a/lib/friendly_error_messages_inference_client.rb +++ b/lib/friendly_error_messages_inference_client.rb @@ -4,6 +4,7 @@ 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 @@ -11,7 +12,7 @@ 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 diff --git a/spec/factories/ai_hint.rb b/spec/factories/ai_hint.rb new file mode 100644 index 000000000..51c4ab8fd --- /dev/null +++ b/spec/factories/ai_hint.rb @@ -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 diff --git a/spec/jobs/generate_ai_hint_job_spec.rb b/spec/jobs/generate_ai_hint_job_spec.rb new file mode 100644 index 000000000..203672a62 --- /dev/null +++ b/spec/jobs/generate_ai_hint_job_spec.rb @@ -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 diff --git a/spec/jobs/remove_old_ai_hints_job_spec.rb b/spec/jobs/remove_old_ai_hints_job_spec.rb new file mode 100644 index 000000000..0b97e7ec5 --- /dev/null +++ b/spec/jobs/remove_old_ai_hints_job_spec.rb @@ -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 diff --git a/spec/models/ai_hint_spec.rb b/spec/models/ai_hint_spec.rb new file mode 100644 index 000000000..a41ba6f7b --- /dev/null +++ b/spec/models/ai_hint_spec.rb @@ -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 diff --git a/spec/requests/ai_hints_spec.rb b/spec/requests/ai_hints_spec.rb new file mode 100644 index 000000000..e8b383adf --- /dev/null +++ b/spec/requests/ai_hints_spec.rb @@ -0,0 +1,133 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe 'AiHints' do + let(:headers) { { Authorization: UserProfileMock::TOKEN } } + let(:school) { create(:school) } + let(:student) { create(:student, school:) } + let(:params) { { message: 'message', trace: 'trace', runtime: 'runtime', code: 'code' } } + + before do + Flipper.enable(:ai_friendly_errors) + end + + describe 'POST /api/ai_hints' do + it 'does not allow logged-out users' do + post('/api/ai_hints', params:) + + expect(response).to have_http_status(:unauthorized) + end + + it 'is protected by a feature flag' do + Flipper.disable(:ai_friendly_errors) + authenticated_in_hydra_as(student) + + post('/api/ai_hints', headers:, params:) + + expect(response).to have_http_status(:unauthorized) + end + + it 'disallows requests over 100KB in size' do + authenticated_in_hydra_as(student) + + post('/api/ai_hints', headers:, params: params.merge(code: 'a' * 100.kilobytes)) + + expect(response).to have_http_status(:content_too_large) + end + + it 'requires message, trace, runtime and code params' do + authenticated_in_hydra_as(student) + + post('/api/ai_hints', headers:, params: params.except(:code)) + + expect(response).to have_http_status(:bad_request) + end + + context 'with a well-formed request' do + before { authenticated_in_hydra_as(student) } + + it 'returns 202 with the id' do + post('/api/ai_hints', headers:, params:) + + expect(response).to have_http_status(:accepted) + expect(response.parsed_body[:id]).to eq(AiHint.last.id) + end + + it 'creates a pending hint for the current user with the input' do + post('/api/ai_hints', headers:, params:) + + expect(AiHint.last).to have_attributes( + user_id: student.id, + status: 'pending', + input: params.stringify_keys + ) + end + + it 'enqueues the job' do + expect { post('/api/ai_hints', headers:, params:) } + .to have_enqueued_job(GenerateAiHintJob).with(ai_hint_id: kind_of(String)) + end + end + end + + describe 'GET /api/ai_hints/:id' do + let(:ai_hint) { create(:ai_hint, user_id: student.id) } + + it 'does not allow logged-out users' do + get "/api/ai_hints/#{ai_hint.id}" + + expect(response).to have_http_status(:unauthorized) + end + + it 'is protected by a feature flag' do + Flipper.disable(:ai_friendly_errors) + authenticated_in_hydra_as(student) + + get("/api/ai_hints/#{ai_hint.id}", headers:) + + expect(response).to have_http_status(:unauthorized) + end + + context 'when authenticated' do + before { authenticated_in_hydra_as(student) } + + it 'returns pending' do + get("/api/ai_hints/#{ai_hint.id}", headers:) + + expect(response).to have_http_status(:ok) + expect(response.parsed_body).to eq('status' => 'pending') + end + + it 'returns the hint when completed' do + ai_hint.complete!('Check the variable name') + + get("/api/ai_hints/#{ai_hint.id}", headers:) + + expect(response.parsed_body).to eq('status' => 'completed', 'hint' => 'Check the variable name') + end + + it 'returns failed' do + ai_hint.fail! + + get("/api/ai_hints/#{ai_hint.id}", headers:) + + expect(response.parsed_body).to eq('status' => 'failed') + end + + it "returns 404 for another user's hint" do + other_hint = create(:ai_hint) + + get("/api/ai_hints/#{other_hint.id}", headers:) + + expect(response).to have_http_status(:not_found) + end + + it 'returns 404 for an unknown id' do + get("/api/ai_hints/#{SecureRandom.uuid}", headers:) + + expect(response).to have_http_status(:not_found) + end + end + end +end