From 8c7252030558de65904b3a16f38e0d01e7874885 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Tue, 24 Nov 2026 14:36:49 +0000 Subject: [PATCH 1/9] add AiHints table and do migration --- db/migrate/20261124143007_create_ai_hints.rb | 15 +++++++++++++++ db/schema.rb | 12 +++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 db/migrate/20261124143007_create_ai_hints.rb 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 From 02fa34ec972d395d1038dad29d4751270897ec48 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Tue, 24 Nov 2026 14:42:12 +0000 Subject: [PATCH 2/9] add ai_hint model Clearing input when either sucessfully completed or failed getting Ai hint. --- app/models/ai_hint.rb | 15 ++++++++++ spec/factories/ai_hint.rb | 8 ++++++ spec/models/ai_hint_spec.rb | 55 +++++++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 app/models/ai_hint.rb create mode 100644 spec/factories/ai_hint.rb create mode 100644 spec/models/ai_hint_spec.rb 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/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/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 From cb2f2cc1b31e8d8bc70bc0922efc7384d1d3b3ea Mon Sep 17 00:00:00 2001 From: cocomarine Date: Tue, 24 Nov 2026 15:34:45 +0000 Subject: [PATCH 3/9] add generate ai hint job --- app/jobs/generate_ai_hint_job.rb | 28 +++++++++++ config/initializers/good_job.rb | 2 +- spec/jobs/generate_ai_hint_job_spec.rb | 67 ++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 app/jobs/generate_ai_hint_job.rb create mode 100644 spec/jobs/generate_ai_hint_job_spec.rb diff --git a/app/jobs/generate_ai_hint_job.rb b/app/jobs/generate_ai_hint_job.rb new file mode 100644 index 000000000..10d813418 --- /dev/null +++ b/app/jobs/generate_ai_hint_job.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +class GenerateAiHintJob < ApplicationJob + # editor-ui will poll for up to 30s and the inference client can take up to 15s, + # so a hint that has waited longer than 15s in the queue can't finish in time. + MAX_QUEUE_WAIT = 15.seconds + + 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! + end +end diff --git a/config/initializers/good_job.rb b/config/initializers/good_job.rb index b31cd2561..288ca4a15 100644 --- a/config/initializers/good_job.rb +++ b/config/initializers/good_job.rb @@ -18,5 +18,5 @@ 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' + config.good_job.queues = 'create_students_job:1;import_schools_job:1;salesforce_sync:10;default:5;ai_hints:5' 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..290b85aea --- /dev/null +++ b/spec/jobs/generate_ai_hint_job_spec.rb @@ -0,0 +1,67 @@ +# 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 +end From f7291fc1d270097c6131da9a610e51445aae04d1 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Tue, 24 Nov 2026 16:04:50 +0000 Subject: [PATCH 4/9] Give the GoodJob worker a larger DB pool via DB_POOL --- Procfile | 2 +- config/database.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Procfile b/Procfile index 73f55236b..7b9a85614 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=25 bundle exec good_job start --max-threads=8 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: From ad8fac30e94c0e57eed4a00ca3307cf93a100f9c Mon Sep 17 00:00:00 2001 From: cocomarine Date: Tue, 24 Nov 2026 16:48:00 +0000 Subject: [PATCH 5/9] Add AiHintsController to create and show AI hints This controller will replace the existing controller, FriendlyErrorMessagesController, once polling is enabled in editor-ui and deployed. --- app/controllers/api/ai_hints_controller.rb | 44 +++++++ config/routes.rb | 1 + spec/requests/ai_hints_spec.rb | 133 +++++++++++++++++++++ 3 files changed, 178 insertions(+) create mode 100644 app/controllers/api/ai_hints_controller.rb create mode 100644 spec/requests/ai_hints_spec.rb 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/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/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 From 0e8fcf9844e7dac43d640dfadce6c115917cd2ed Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 11:21:13 +0000 Subject: [PATCH 6/9] handle unexpected job errors --- app/jobs/generate_ai_hint_job.rb | 5 +++++ spec/jobs/generate_ai_hint_job_spec.rb | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/app/jobs/generate_ai_hint_job.rb b/app/jobs/generate_ai_hint_job.rb index 10d813418..21f03ea15 100644 --- a/app/jobs/generate_ai_hint_job.rb +++ b/app/jobs/generate_ai_hint_job.rb @@ -24,5 +24,10 @@ def perform(ai_hint_id:) 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/spec/jobs/generate_ai_hint_job_spec.rb b/spec/jobs/generate_ai_hint_job_spec.rb index 290b85aea..203672a62 100644 --- a/spec/jobs/generate_ai_hint_job_spec.rb +++ b/spec/jobs/generate_ai_hint_job_spec.rb @@ -64,4 +64,13 @@ 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 From 017b01813c5bdbce191cc5b46a63a6f1adf2c618 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 12:53:12 +0000 Subject: [PATCH 7/9] Make worker pool and thread count configurable for different environments --- Procfile | 2 +- config/initializers/good_job.rb | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Procfile b/Procfile index 7b9a85614..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: DB_POOL=25 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/config/initializers/good_job.rb b/config/initializers/good_job.rb index 288ca4a15..da6d547df 100644 --- a/config/initializers/good_job.rb +++ b/config/initializers/good_job.rb @@ -18,5 +18,12 @@ 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;ai_hints: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' + ) end From 635604898c7e3077012291f94930f2ace920410a Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 16:50:50 +0000 Subject: [PATCH 8/9] clarify timings using constants --- app/jobs/generate_ai_hint_job.rb | 8 +++++--- lib/friendly_error_messages_inference_client.rb | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/app/jobs/generate_ai_hint_job.rb b/app/jobs/generate_ai_hint_job.rb index 21f03ea15..5d8bd0ed2 100644 --- a/app/jobs/generate_ai_hint_job.rb +++ b/app/jobs/generate_ai_hint_job.rb @@ -1,9 +1,11 @@ # frozen_string_literal: true class GenerateAiHintJob < ApplicationJob - # editor-ui will poll for up to 30s and the inference client can take up to 15s, - # so a hint that has waited longer than 15s in the queue can't finish in time. - MAX_QUEUE_WAIT = 15.seconds + # 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 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 From 84b6c6cfa09c04d2008e9b294bd59f9f7496a7c0 Mon Sep 17 00:00:00 2001 From: cocomarine Date: Thu, 26 Nov 2026 17:19:46 +0000 Subject: [PATCH 9/9] Add weekly cleanup job for old AI hints --- app/jobs/remove_old_ai_hints_job.rb | 11 +++++++++++ config/initializers/good_job.rb | 10 ++++++++++ spec/jobs/remove_old_ai_hints_job_spec.rb | 15 +++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 app/jobs/remove_old_ai_hints_job.rb create mode 100644 spec/jobs/remove_old_ai_hints_job_spec.rb 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/config/initializers/good_job.rb b/config/initializers/good_job.rb index da6d547df..0feb21b59 100644 --- a/config/initializers/good_job.rb +++ b/config/initializers/good_job.rb @@ -26,4 +26,14 @@ def authenticate_admin '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/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