The personal finance app for everyone (by everyone)
Ruby
Hold back background AI jobs while someone writes a chat message (#4444)
Josh Sanders6b4d97a624d0
diff --git a/app/controllers/chat_reservations_controller.rb b/app/controllers/chat_reservations_controller.rbnew file mode 100644index 0000000000..d73e2fe568--- /dev/null+++ b/app/controllers/chat_reservations_controller.rb@@ -0,0 +1,10 @@+class ChatReservationsController < ApplicationController+ include FeatureGuardable++ guard_feature unless: -> { Current.user.ai_enabled? }++ def create+ bubble = ChatReservation.bubble(ChatReservation.hold!)+ render turbo_stream: turbo_stream.update_all(ChatReservation::TARGETS, partial: "chats/reservation", locals: { bubble: bubble })+ end+enddiff --git a/app/javascript/controllers/chat_reservation_controller.js b/app/javascript/controllers/chat_reservation_controller.jsnew file mode 100644index 0000000000..badb8391e5--- /dev/null+++ b/app/javascript/controllers/chat_reservation_controller.js@@ -0,0 +1,46 @@+import { Controller } from "@hotwired/stimulus";++// Focusing or typing in the chat box holds back background AI jobs+// (ChatReservation), pinging at most every 5 s.+export default class extends Controller {+ static targets = ["bubble", "countdown"];+ static values = { url: String };++ disconnect() {+ clearInterval(this.timer);+ }++ hold() {+ if (Date.now() - (this.lastPingAt || 0) < 5000) return;+ this.lastPingAt = Date.now();++ fetch(this.urlValue, {+ method: "POST",+ headers: {+ "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]')?.content,+ Accept: "text/vnd.turbo-stream.html",+ },+ })+ .then((response) => (response.ok ? response.text() : ""))+ .then((html) => html && Turbo.renderStreamMessage(html))+ .catch(() => {});+ }++ hide() {+ clearInterval(this.timer);+ if (this.hasBubbleTarget) this.bubbleTarget.remove();+ }++ bubbleTargetConnected(bubble) {+ clearInterval(this.timer);+ this.endsAt = Date.now() + Number(bubble.dataset.seconds) * 1000;+ this.#tick();+ this.timer = setInterval(() => this.#tick(), 1000);+ }++ #tick() {+ const seconds = Math.ceil((this.endsAt - Date.now()) / 1000);+ if (seconds <= 0 || !this.hasBubbleTarget) return this.hide();+ if (this.hasCountdownTarget) this.countdownTarget.textContent = seconds;+ }+}diff --git a/app/jobs/assistant_response_job.rb b/app/jobs/assistant_response_job.rbindex 1f98945b30..134956bee4 100644--- a/app/jobs/assistant_response_job.rb+++ b/app/jobs/assistant_response_job.rb@@ -2,6 +2,9 @@ class AssistantResponseJob < ApplicationJobqueue_as :ai_high_prioritydef perform(message, assistant_message = nil)- message.request_response(assistant_message: assistant_message)+ ChatReservation.while_chat_runs { message.request_response(assistant_message: assistant_message) }+ ensure+ # Hold background AI jobs back so a reply to this answer runs next.+ message.chat.hold_reservationendenddiff --git a/app/models/background_job_health.rb b/app/models/background_job_health.rbindex 677d98c8bf..add9c3b0de 100644--- a/app/models/background_job_health.rb+++ b/app/models/background_job_health.rb@@ -11,13 +11,13 @@ class BackgroundJobHealth# Syncs and imports run here; chat runs on ai_high_priority.CRITICAL_QUEUE = "high_priority".freezeCHAT_QUEUE = "ai_high_priority".freeze+ AI_QUEUES = [ CHAT_QUEUE, "ai_low_priority" ].freeze+ # A worker whose AI lane has one thread for both AI queues adds this label to+ # its Sidekiq process at startup (config/initializers/sidekiq.rb), so web+ # processes read the worker's lane instead of their own RAILS_AI_MAX_THREADS.+ ONE_AI_THREAD_LABEL = "one-ai-thread".freezeLATENCY_WARN_SECONDS = 60- # A chat waiting this long is behind another AI job: normal with one AI- # thread and a slow model, so it's "busy", not unhealthy. With one thread,- # an ai_low_priority backlog means a chat sent now waits too.- AI_BUSY_SECONDS = 30-CACHE_KEY = "background_job_health".freezeCACHE_TTL = 15.seconds@@ -37,8 +37,31 @@ class BackgroundJobHealthcurrentend+ # Only when a single worker process polls the AI queues: with several, a+ # chat can run on one while another runs background AI jobs.+ def one_ai_thread?+ ai_processes = Sidekiq::ProcessSet.new(false).select { |process| process.queues.intersect?(AI_QUEUES) }+ ai_processes.one? && ai_processes.first.labels.include?(ONE_AI_THREAD_LABEL)+ rescue => e+ Rails.logger.warn("BackgroundJobHealth AI thread check failed: #{e.class}: #{e.message}")+ false+ end++ def one_ai_thread_worker?(config)+ ai_capsules = config.capsules.values.select { |capsule| capsule.queues.intersect?(AI_QUEUES) }+ ai_capsules.one? && ai_capsules.first.concurrency == 1 && (AI_QUEUES - ai_capsules.first.queues).empty?+ end++ # With one AI thread, a chat sent now waits for any running AI job.def ai_busy?- current[:ai_busy]+ one_ai_thread? && ai_job_running?+ end++ def ai_job_running?(queues: AI_QUEUES)+ Sidekiq::WorkSet.new.any? { |_process, _thread, work| queues.include?(work.queue) }+ rescue => e+ Rails.logger.warn("BackgroundJobHealth busy check failed: #{e.class}: #{e.message}")+ falseenddef summary@@ -55,13 +78,8 @@ class BackgroundJobHealthpolls_chat = polled_queues.include?(CHAT_QUEUE)latency = Sidekiq::Queue.new(CRITICAL_QUEUE).latency- ai_queues = [ CHAT_QUEUE ]- ai_queues << "ai_low_priority" if ENV.fetch("RAILS_AI_MAX_THREADS", 1).to_i == 1- ai_latency = ai_queues.map { |q| Sidekiq::Queue.new(q).latency }.max-{healthy: workers.positive? && polls_critical && polls_chat && latency < LATENCY_WARN_SECONDS,- ai_busy: ai_latency > AI_BUSY_SECONDS,workers: workers,polls_critical_queue: polls_critical,polls_chat_queue: polls_chat,@@ -71,7 +89,7 @@ class BackgroundJobHealthenddef fail_open- { healthy: true, ai_busy: false, workers: nil, polls_critical_queue: nil, polls_chat_queue: nil, latency: nil, checked_at: Time.current, error: true }+ { healthy: true, workers: nil, polls_critical_queue: nil, polls_chat_queue: nil, latency: nil, checked_at: Time.current, error: true }endendenddiff --git a/app/models/chat.rb b/app/models/chat.rbindex 40ffa3e16b..9a1f9784ef 100644--- a/app/models/chat.rb+++ b/app/models/chat.rb@@ -141,6 +141,14 @@ class Chat < ApplicationRecordassistant.respond_to(message, assistant_message: assistant_message)end+ # Not broadcast_update: it adds `chat` to the locals and drops a nil bubble.+ def hold_reservation+ Turbo::StreamsChannel.broadcast_update_to self, targets: ChatReservation::TARGETS, partial: "chats/reservation",+ locals: { bubble: ChatReservation.bubble(ChatReservation.hold!) }+ rescue => e+ Rails.logger.warn("ChatReservation hold failed: #{e.class}: #{e.message}")+ end+# The pending bubble says "busy" while the response waits behind another AI# job, and "Thinking" once its job starts.def broadcast_pending_status(assistant_message, busy: false)diff --git a/app/models/chat_reservation.rb b/app/models/chat_reservation.rbnew file mode 100644index 0000000000..82e4037342--- /dev/null+++ b/app/models/chat_reservation.rb@@ -0,0 +1,68 @@+# With one AI thread, a chat message sent while a background AI job runs waits+# for that job's LLM call. Focusing or typing in the chat box, and each finished+# reply, hold new ai_low_priority jobs back for TTL. Back-to-back holds stop+# CAP after the first one and resume TTL later, so those jobs get a turn.+module ChatReservation+ KEY = "chat_reservation".freeze+ STARTED_KEY = "chat_reservation:started".freeze+ CHAT_KEY = "chat_reservation:chat_running".freeze+ TARGETS = ".chat-reservation".freeze+ TTL = 60.seconds+ CAP = 15.minutes++ # Returns the seconds held, or nil when nothing is held: several AI threads+ # leave one free anyway, or the cap was reached.+ def self.hold!+ return unless BackgroundJobHealth.one_ai_thread?++ Sidekiq.redis do |conn|+ now = Time.current.to_i+ started = conn.call("GET", STARTED_KEY)&.to_i+ if started.nil? || (now - started < CAP && conn.call("EXISTS", KEY).zero?)+ started = now+ conn.call("SET", STARTED_KEY, now, "EX", (CAP + TTL).to_i)+ end++ seconds = [ TTL.to_i, started + CAP.to_i - now ].min+ next unless seconds.positive?++ conn.call("SET", KEY, "1", "EX", seconds)+ seconds+ end+ end++ # Marks a chat job as running, interim replies included. Expires with the+ # chat's response timeout in case the worker dies mid-job.+ def self.while_chat_runs+ begin+ Sidekiq.redis { |conn| conn.call("SET", CHAT_KEY, "1", "EX", Chat.response_timeout.to_i) }+ rescue => e+ Rails.logger.warn("ChatReservation chat flag not set: #{e.class}: #{e.message}")+ end+ yield+ ensure+ begin+ Sidekiq.redis { |conn| conn.call("DEL", CHAT_KEY) }+ rescue => e+ Rails.logger.warn("ChatReservation chat flag not cleared: #{e.class}: #{e.message}")+ end+ end++ def self.held?+ Sidekiq.redis { |conn| conn.call("EXISTS", KEY) } == 1+ end++ def self.chat_active?+ Sidekiq.redis { |conn| conn.call("EXISTS", CHAT_KEY) } == 1 || Sidekiq::Queue.new("ai_high_priority").size.positive?+ end++ # Nothing while a chat is queued or running: its own bubble covers that.+ # Otherwise busy while a background AI job runs, ready while some wait.+ # seconds comes from hold!, which has already checked for one AI thread.+ def self.bubble(seconds)+ return if seconds.nil? || chat_active?++ busy = BackgroundJobHealth.ai_job_running?(queues: [ "ai_low_priority" ])+ { seconds: seconds, busy: busy } if busy || Sidekiq::Queue.new("ai_low_priority").size.positive?+ end+enddiff --git a/app/models/chat_reservation/fetch.rb b/app/models/chat_reservation/fetch.rbnew file mode 100644index 0000000000..109e26d8ed--- /dev/null+++ b/app/models/chat_reservation/fetch.rb@@ -0,0 +1,28 @@+require "sidekiq/fetch"++# Sidekiq rebuilds the queue list on every fetch (at least every 2 s), so+# dropping ai_low_priority holds those jobs in their queue, in order. A job+# popped by a fetch that started before the hold goes back to the front of+# its queue. Only a single-threaded AI capsule holds: with more threads, one+# is free for the chat anyway.+class ChatReservation::Fetch < Sidekiq::BasicFetch+ LOW_QUEUE = "queue:ai_low_priority".freeze++ def queues_cmd+ queues = super+ holds?(queues) ? queues - [ LOW_QUEUE ] : queues+ end++ def retrieve_work+ work = super+ return work unless work&.queue == LOW_QUEUE && holds?([ LOW_QUEUE ])++ work.requeue+ nil+ end++ private+ def holds?(queues)+ queues.include?(LOW_QUEUE) && config.concurrency == 1 && ChatReservation.held?+ end+enddiff --git a/app/views/chats/_reservation.html.erb b/app/views/chats/_reservation.html.erbnew file mode 100644index 0000000000..0f3835ee4c--- /dev/null+++ b/app/views/chats/_reservation.html.erb@@ -0,0 +1,11 @@+<%# locals: (bubble:) %>+<% if bubble %>+ <div class="flex items-start gap-2 px-1 text-xs text-secondary"+ data-chat-reservation-target="bubble"+ data-seconds="<%= bubble[:seconds] %>">+ <%= icon(bubble[:busy] ? "hourglass" : "circle-check", size: "sm") %>+ <p>+ <%= bubble[:busy] ? t("chats.reservation.busy") : t("chats.reservation.ready_html", countdown: tag.span(data: { chat_reservation_target: "countdown" })) %>+ </p>+ </div>+<% end %>diff --git a/app/views/messages/_chat_form.html.erb b/app/views/messages/_chat_form.html.erbindex 68dce8a89f..59d177735c 100644--- a/app/views/messages/_chat_form.html.erb+++ b/app/views/messages/_chat_form.html.erb@@ -1,18 +1,22 @@<%# locals: (chat: nil, message_hint: nil) %>-<div id="chat-form" class="space-y-2">+<div id="chat-form" class="space-y-2"+ data-controller="chat-reservation"+ data-chat-reservation-url-value="<%= chat_reservation_path %>">+ <div class="chat-reservation" role="status" aria-live="polite"></div>+<% model = chat && chat.persisted? ? [chat, Message.new] : Chat.new %><%= form_with model: model,class: "flex lg:flex-col gap-2 bg-container px-2 py-1.5 rounded-full lg:rounded-lg shadow-border-xs",- data: { chat_target: "form" } do |f| %>+ data: { chat_target: "form", action: "submit->chat-reservation#hide" } do |f| %><%# In the future, this will be a dropdown with different AI models %><%= f.hidden_field :ai_model, value: default_ai_model %><%= f.text_area :content, placeholder: t(".placeholder"), value: message_hint, autofocus: message_hint.present?,class: "w-full border-0 focus:ring-0 text-sm resize-none px-1 bg-transparent",- data: { chat_target: "input", action: "input->chat#autoResize keydown->chat#handleInputKeyDown" },+ data: { chat_target: "input", action: "input->chat#autoResize focus->chat-reservation#hold input->chat-reservation#hold keydown->chat#handleInputKeyDown" },rows: 1 %><div class="flex items-center justify-between gap-1">diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rbindex d4a824bba1..3c1dfb4de3 100644--- a/config/initializers/sidekiq.rb+++ b/config/initializers/sidekiq.rb@@ -63,6 +63,12 @@ endSidekiq.configure_server do |config|config.redis = redis_config+ # At startup: app classes aren't loadable yet when this file runs.+ config.on(:startup) do+ config[:fetch_class] = ChatReservation::Fetch+ config[:labels] << BackgroundJobHealth::ONE_AI_THREAD_LABEL if BackgroundJobHealth.one_ai_thread_worker?(config)+ end+# Initialize auto-sync scheduler when Sidekiq server startsconfig.on(:startup) doAutoSyncScheduler.sync!diff --git a/config/locales/views/chats/de.yml b/config/locales/views/chats/de.ymlindex 10603533fb..d3af450f04 100644--- a/config/locales/views/chats/de.yml+++ b/config/locales/views/chats/de.yml@@ -4,7 +4,10 @@ de:demo_banner_title: "Demo-Modus aktiv"demo_banner_message: "Du nutzt ein Open-Weight-Qwen3-LLM mit Credits von Cloudflare Workers AI. Die Ergebnisse können abweichen, weil die Codebasis vor allem mit `gpt-4.1` getestet wurde. Deine Tokens werden nirgends zum Training verwendet. 🤖"thinking: "Wird verarbeitet ..."- ai_busy: "Das System ist ausgelastet. Deine Nachricht wird nach dem aktuellen Auftrag verarbeitet."+ ai_busy: "Ich erledige nur noch schnell eine Hintergrundaufgabe, dann kümmere ich mich gleich um deine Nachricht."+ reservation:+ ready_html: "Ich habe ein paar Hintergrundaufgaben aufgeschoben, damit ich gleich mit deiner Nachricht loslegen kann. In %{countdown} s schleichen sie sich zurück, also tipp weiter!"+ busy: "Ich erledige nur noch schnell eine Hintergrundaufgabe, dann bin ich ganz für dich da. Tipp ruhig weiter!"ai_consent:available_description: Der KI-Chat beantwortet Finanzfragen und wertet deine Daten aus. Du musst die Funktion ausdrücklich einschalten, bevor du sie nutzen kannst.disable_note: Jederzeit abschaltbar. Alle Daten, die an unsere LLM-Anbieter gehen, sind anonymisiert.diff --git a/config/locales/views/chats/en.yml b/config/locales/views/chats/en.ymlindex 66ee7e3f71..54b9b5aaf6 100644--- a/config/locales/views/chats/en.yml+++ b/config/locales/views/chats/en.yml@@ -4,7 +4,10 @@ en:demo_banner_title: "Demo Mode Active"demo_banner_message: "You are using LLMs via credits provided by Cloudflare Workers AI. Results may vary since the codebase was tested on `gpt-4.1` but your tokens don't go anywhere else to be trained with! 🤖"thinking: "Thinking ..."- ai_busy: "System is busy. Your message will be processed after the current job."+ ai_busy: "Just finishing off a background task, then I'll get straight onto your message."+ reservation:+ ready_html: "I've put off some background tasks so I can get straight onto your message. They'll sneak back in %{countdown} s, so keep typing!"+ busy: "Just finishing off a background task, then I'm all yours. Keep typing!"worker_unhealthy_warning: "AI responses may not be delivered right now — the background worker appears to be down or backed up. Check that your Sidekiq worker is running."ai_greeting:greeting: "Hey %{name}! I'm an AI/large-language-model that can help with your finances. I have access to the web and your account data."diff --git a/config/routes.rb b/config/routes.rbindex ed5478015d..cb96a26b58 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -301,6 +301,8 @@ Rails.application.routes.draw doend# AI chats+ resource :chat_reservation, only: :create+resources :chats doresources :messages, only: :create domember dodiff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex c3ed35c656..07322a2623 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -50,9 +50,10 @@ AI work runs in the Sidekiq `worker`, in its own capsule ("lane"), so a slow mod- `RAILS_MAX_THREADS` is the worker's total thread count, as before, and also sizes its database pool. It must be greater than `RAILS_AI_MAX_THREADS` (so at least `2` by default): a lane with 0 threads stops the worker from starting ("Concurrency of 0 is not supported"). Puma reads the same variable, so if you lower it for the web service to save memory, set the worker's separately.- **Strict order:** a waiting chat runs next, but it doesn't interrupt the AI job already running. Auto-categorization, merchant-detection and merchant-enhancement jobs make one LLM call each, of `LLM_MAX_ITEMS_PER_CALL` items (default `25`), or more if the batch doesn't fit the context window; PDF import and chat jobs can make several. With one AI thread, a PDF import or other `ai_low_priority` job waits behind earlier ones, and continuous chat use pauses background AI work.-- **Busy notice:** when a chat would wait behind another AI job (a chat has waited over 30 seconds, or, with one AI thread, background AI work has), its "Thinking" bubble says the system is busy until the chat's job starts. `AI_RESPONSE_TIMEOUT` includes that wait.+- **Busy notice:** with one AI thread in a single worker process running the AI queues, while another AI job (a background job or another chat) is running, a chat's "Thinking" bubble says the system is busy until the chat's job starts. `AI_RESPONSE_TIMEOUT` includes that wait.+- **Chat reservation:** with one AI thread, clicking into or typing in the chat box, and each finished reply, hold back new background AI jobs for 60 seconds, so the message runs next. This applies when a single worker process runs the AI queues; with several, a chat can run on one while another runs background jobs, so nothing is held. Back-to-back holds stop after 15 minutes and resume 60 seconds later, so background AI work gets a turn. When you click into or type in the chat box while background AI jobs wait, a bubble above it shows the countdown, or says one is still finishing. A job that is already running is not interrupted.- **One AI thread suits a model that serves one request at a time,** such as a local model on CPU: a chat turn's calls then run back to back, keeping the model's prompt cache warm. If your provider serves requests in parallel (hosted APIs, or a local server with several slots), raise `RAILS_AI_MAX_THREADS`, and `RAILS_MAX_THREADS` by the same amount so the default lane keeps its threads.-- **The worker must load `config/sidekiq.yml`,** as `bundle exec sidekiq` does by default. A worker started with its own queue list (`sidekiq -q …`, a custom Helm `worker.command`) doesn't get the AI lane. If no worker polls `ai_high_priority` and `ai_low_priority`, **System health** (`/admin/system_health`) and the site-wide banner report "No worker is processing the AI queues", and the chat page warns that responses may not be delivered. Keep `-C config/sidekiq.yml`; adding `-q ai_high_priority -q ai_low_priority` also works, but AI jobs then share that worker's threads.+- **The worker must load `config/sidekiq.yml`,** as `bundle exec sidekiq` does by default. A worker started with its own queue list (`sidekiq -q …`, a custom Helm `worker.command`) doesn't get the AI lane. If no worker polls `ai_high_priority` and `ai_low_priority`, **System health** (`/admin/system_health`) and the site-wide banner report "No worker is processing the AI queues", and the chat page warns that responses may not be delivered. Keep `-C config/sidekiq.yml`; adding `-q ai_high_priority -q ai_low_priority` also works, but AI jobs then share that worker's threads, and the chat reservation doesn't hold them, since a chat can usually take another thread.- **System health:** AI backlog doesn't count towards "queue backed up" (a large merchant-detection run can queue for hours), but "Oldest job age" still includes it. Check the queue table or `/sidekiq` to see which queue is waiting.- **Upgrading:** AI jobs moved from `high_priority` (chat), `medium_priority` and `scheduled` to the AI queues. Jobs already queued under the old names still run once, in the default lane.- **Large batches:** Sure doesn't limit `LLM_MAX_ITEMS_PER_CALL`. OpenAI-compatible providers split a batch that doesn't fit the context window; with the native Anthropic provider, raise `ANTHROPIC_MAX_TOKENS` (default `4096`) along with it, or replies are cut off.diff --git a/test/controllers/chat_reservations_controller_test.rb b/test/controllers/chat_reservations_controller_test.rbnew file mode 100644index 0000000000..352f1c623a--- /dev/null+++ b/test/controllers/chat_reservations_controller_test.rb@@ -0,0 +1,52 @@+require "test_helper"++class ChatReservationsControllerTest < ActionDispatch::IntegrationTest+ setup do+ sign_in users(:family_admin)+ BackgroundJobHealth.stubs(:ai_job_running?).with(queues: [ "ai_low_priority" ]).returns(false)+ ChatReservation.stubs(:chat_active?).returns(false)+ stub_waiting_jobs(1)+ end++ test "typing holds the reservation and shows ready while background AI jobs wait" do+ ChatReservation.expects(:hold!).returns(60)++ post chat_reservation_url, as: :turbo_stream++ assert_response :success+ assert_select "turbo-stream[action=update][targets='.chat-reservation'] template", text: /put off some background tasks/+ end++ test "no bubble when no background AI job waits" do+ ChatReservation.expects(:hold!).returns(60)+ stub_waiting_jobs(0)++ post chat_reservation_url, as: :turbo_stream++ assert_select "turbo-stream[action=update][targets='.chat-reservation'] template", text: ""+ end++ test "the bubble says busy while a background AI job runs" do+ ChatReservation.expects(:hold!).returns(60)+ BackgroundJobHealth.stubs(:ai_job_running?).with(queues: [ "ai_low_priority" ]).returns(true)+ stub_waiting_jobs(0)++ post chat_reservation_url, as: :turbo_stream++ assert_select "turbo-stream[targets='.chat-reservation'] template", text: /#{Regexp.escape(I18n.t("chats.reservation.busy"))}/+ end++ test "forbidden without AI consent" do+ users(:family_admin).update!(ai_enabled: false)+ ChatReservation.expects(:hold!).never++ post chat_reservation_url, as: :turbo_stream++ assert_response :forbidden+ end++ private+ def stub_waiting_jobs(count)+ Sidekiq::Queue.stubs(:new).with("ai_low_priority").returns(stub(size: count))+ end+enddiff --git a/test/models/background_job_health_test.rb b/test/models/background_job_health_test.rbindex ae82cb579a..a9ce32a30c 100644--- a/test/models/background_job_health_test.rb+++ b/test/models/background_job_health_test.rb@@ -35,41 +35,104 @@ class BackgroundJobHealthTest < ActiveSupport::TestCaseassert_not BackgroundJobHealth.healthy?end- test "a chat waiting behind another AI job is busy, not unhealthy" do- stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_high: 45.0)+ test "with one AI thread, a running ai_low_priority job is busy" do+ stub_running("ai_low_priority")- assert BackgroundJobHealth.healthy?assert BackgroundJobHealth.ai_busy?end- test "with one AI thread, an ai_low_priority backlog is busy" do- stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_low: 45.0)+ test "with one AI thread, a running chat is busy for the next one" do+ stub_running("ai_high_priority")++ assert BackgroundJobHealth.ai_busy?+ end++ test "other running jobs aren't busy" do+ stub_running("default")++ assert_not BackgroundJobHealth.ai_busy?+ end++ test "the running-job check can be limited to some AI queues" do+ stub_running("ai_high_priority")++ assert BackgroundJobHealth.ai_job_running?+ assert_not BackgroundJobHealth.ai_job_running?(queues: [ "ai_low_priority" ])+ end++ test "with several AI threads, a running ai_low_priority job isn't busy" do+ stub_running("ai_low_priority", one_ai_thread: false)++ assert_not BackgroundJobHealth.ai_busy?+ end++ test "one AI thread when the only worker process polling AI queues carries the label" do+ stub_processes(ai_process(labelled: true), stub(queues: %w[default], labels: []))+ assert BackgroundJobHealth.one_ai_thread?- with_env_overrides("RAILS_AI_MAX_THREADS" => nil) { assert BackgroundJobHealth.ai_busy? }+ stub_processes(ai_process(labelled: false))+ assert_not BackgroundJobHealth.one_ai_thread?end- test "with several AI threads, an ai_low_priority backlog isn't busy" do- stub_sidekiq(processes: [ { "queues" => [ "high_priority", "ai_high_priority" ] } ], latency: 0.0, ai_low: 45.0)+ test "several worker processes polling AI queues aren't one AI thread" do+ stub_processes(ai_process(labelled: true), ai_process(labelled: true))- with_env_overrides("RAILS_AI_MAX_THREADS" => "2") { assert_not BackgroundJobHealth.ai_busy? }+ assert_not BackgroundJobHealth.one_ai_thread?+ end++ test "a worker gets the label only for a one-thread capsule polling both AI queues" do+ config = Sidekiq::Config.new+ ai = config.capsule("ai") { |capsule| capsule.queues = %w[ai_high_priority ai_low_priority] }++ ai.concurrency = 1+ assert BackgroundJobHealth.one_ai_thread_worker?(config)++ ai.concurrency = 2+ assert_not BackgroundJobHealth.one_ai_thread_worker?(config)++ low_only = Sidekiq::Config.new+ low_only.capsule("ai") { |capsule| capsule.queues = %w[ai_low_priority]; capsule.concurrency = 1 }+ assert_not BackgroundJobHealth.one_ai_thread_worker?(low_only)+ end++ test "no label when another capsule in the worker also polls an AI queue" do+ config = Sidekiq::Config.new+ config.capsule("ai") { |capsule| capsule.queues = %w[ai_high_priority ai_low_priority]; capsule.concurrency = 1 }+ config.default_capsule { |capsule| capsule.queues = %w[default ai_low_priority]; capsule.concurrency = 2 }++ assert_not BackgroundJobHealth.one_ai_thread_worker?(config)endtest "fails open when Sidekiq/Redis is unreachable" doSidekiq::ProcessSet.stubs(:new).raises(StandardError.new("no redis"))+ Sidekiq::WorkSet.stubs(:new).raises(StandardError.new("no redis"))assert BackgroundJobHealth.healthy?assert BackgroundJobHealth.snapshot[:error]+ assert_not BackgroundJobHealth.one_ai_thread?+ assert_not BackgroundJobHealth.ai_job_running?endprivate- def stub_sidekiq(processes:, latency:, ai_high: 0.0, ai_low: 0.0)+ def stub_sidekiq(processes:, latency:)process_set = mock("ProcessSet")process_set.stubs(:size).returns(processes.size)process_set.stubs(:flat_map).returns(processes.flat_map { |p| p["queues"] })Sidekiq::ProcessSet.stubs(:new).returns(process_set)- { "high_priority" => latency, "ai_high_priority" => ai_high, "ai_low_priority" => ai_low }.each do |name, wait|- Sidekiq::Queue.stubs(:new).with(name).returns(stub(latency: wait))- end+ Sidekiq::Queue.stubs(:new).with("high_priority").returns(stub(latency: latency))+ end++ def stub_processes(*processes)+ Sidekiq::ProcessSet.stubs(:new).with(false).returns(processes)+ end++ def ai_process(labelled:)+ stub(queues: %w[default ai_high_priority ai_low_priority], labels: labelled ? [ BackgroundJobHealth::ONE_AI_THREAD_LABEL ] : [])+ end++ def stub_running(queue, one_ai_thread: true)+ BackgroundJobHealth.stubs(:one_ai_thread?).returns(one_ai_thread)+ Sidekiq::WorkSet.stubs(:new).returns([ [ "worker:1", "tid", stub(queue: queue) ] ])endenddiff --git a/test/models/chat_reservation_test.rb b/test/models/chat_reservation_test.rbnew file mode 100644index 0000000000..5f605d38d6--- /dev/null+++ b/test/models/chat_reservation_test.rb@@ -0,0 +1,172 @@+require "test_helper"+require "sidekiq/capsule"++# Redis is stubbed: parallel test processes share one Redis, and other tests'+# chat jobs set the same global key.+class ChatReservationTest < ActiveSupport::TestCase+ test "with one AI thread, hold! reserves the AI thread for the TTL" do+ with_hold_redis do |redis|+ assert_equal 60, ChatReservation.hold!+ assert redis.key?(ChatReservation::KEY)+ end+ end++ test "back-to-back holds stop at the cap and resume a TTL later" do+ with_hold_redis do |redis|+ travel_to Time.zone.parse("2026-10-23 09:00:00")+ 29.times { ChatReservation.hold!; travel 30.seconds }+ travel_to Time.zone.parse("2026-10-23 09:14:30")+ assert_equal 30, ChatReservation.hold!++ travel_to Time.zone.parse("2026-10-23 09:15:00")+ assert_nil ChatReservation.hold!+ assert_not redis.key?(ChatReservation::KEY)++ travel_to Time.zone.parse("2026-10-23 09:16:00")+ assert_equal 60, ChatReservation.hold!+ end+ end++ test "a hold that lapsed starts a new cap" do+ with_hold_redis do+ travel_to Time.zone.parse("2026-10-23 09:00:00")+ ChatReservation.hold!+ travel_to Time.zone.parse("2026-10-23 09:14:50")+ assert_equal 60, ChatReservation.hold!+ end+ end++ test "with several AI threads, hold! reserves nothing" do+ BackgroundJobHealth.stubs(:one_ai_thread?).returns(false)+ Sidekiq.expects(:redis).never++ assert_nil ChatReservation.hold!+ end++ test "the bubble says busy while a background AI job runs, ready while some wait, else nothing" do+ BackgroundJobHealth.expects(:one_ai_thread?).never+ ChatReservation.stubs(:chat_active?).returns(false)+ BackgroundJobHealth.stubs(:ai_job_running?).with(queues: [ "ai_low_priority" ]).returns(false)+ Sidekiq::Queue.stubs(:new).with("ai_low_priority").returns(stub(size: 0))+ assert_nil ChatReservation.bubble(60)++ Sidekiq::Queue.stubs(:new).with("ai_low_priority").returns(stub(size: 2))+ assert_equal({ seconds: 60, busy: false }, ChatReservation.bubble(60))++ BackgroundJobHealth.stubs(:ai_job_running?).with(queues: [ "ai_low_priority" ]).returns(true)+ assert_equal({ seconds: 60, busy: true }, ChatReservation.bubble(60))+ assert_nil ChatReservation.bubble(nil)+ end++ test "no bubble while a chat is queued or running" do+ ChatReservation.stubs(:chat_active?).returns(true)+ BackgroundJobHealth.stubs(:ai_job_running?).returns(true)++ assert_nil ChatReservation.bubble(60)+ end++ test "a running chat counts as active until its job ends, even if it raises" do+ conn = mock+ conn.expects(:call).with("SET", ChatReservation::CHAT_KEY, "1", "EX", Chat.response_timeout.to_i)+ conn.expects(:call).with("DEL", ChatReservation::CHAT_KEY)+ Sidekiq.stubs(:redis).yields(conn)++ assert_raises(RuntimeError) { ChatReservation.while_chat_runs { raise "boom" } }+ end++ test "a Redis error while setting the chat flag doesn't skip the reply" do+ conn = mock+ conn.stubs(:call).with("SET", ChatReservation::CHAT_KEY, "1", "EX", Chat.response_timeout.to_i).raises(RedisClient::ConnectionError)+ conn.stubs(:call).with("DEL", ChatReservation::CHAT_KEY)+ Sidekiq.stubs(:redis).yields(conn)++ assert_equal :reply, ChatReservation.while_chat_runs { :reply }+ end++ test "a reply isn't failed by a Redis error while clearing the chat flag" do+ conn = mock+ conn.stubs(:call).with("SET", ChatReservation::CHAT_KEY, "1", "EX", Chat.response_timeout.to_i)+ conn.stubs(:call).with("DEL", ChatReservation::CHAT_KEY).raises(RedisClient::ConnectionError)+ Sidekiq.stubs(:redis).yields(conn)++ assert_equal :reply, ChatReservation.while_chat_runs { :reply }+ end++ test "the AI capsule skips ai_low_priority while a reservation is held" do+ fetch = fetch_for(%w[ai_high_priority ai_low_priority])++ ChatReservation.stubs(:held?).returns(false)+ assert_equal %w[queue:ai_high_priority queue:ai_low_priority], fetch.queues_cmd++ ChatReservation.stubs(:held?).returns(true)+ assert_equal %w[queue:ai_high_priority], fetch.queues_cmd+ end++ test "other capsules' queues are left alone" do+ fetch = fetch_for(%w[high_priority default])+ ChatReservation.expects(:held?).never++ assert_equal %w[queue:high_priority queue:default], fetch.queues_cmd+ end++ test "an AI capsule with several threads ignores the reservation" do+ fetch = fetch_for(%w[ai_high_priority ai_low_priority], concurrency: 2)+ ChatReservation.stubs(:held?).returns(true)++ assert_equal %w[queue:ai_high_priority queue:ai_low_priority], fetch.queues_cmd+ end++ test "an ai_low_priority job popped after a hold started goes back to its queue" do+ fetch = fetch_for(%w[ai_high_priority ai_low_priority])+ work = Sidekiq::BasicFetch::UnitOfWork.new("queue:ai_low_priority", "{}", nil)+ Sidekiq::BasicFetch.any_instance.stubs(:retrieve_work).returns(work)++ ChatReservation.stubs(:held?).returns(true)+ work.expects(:requeue)+ assert_nil fetch.retrieve_work++ ChatReservation.stubs(:held?).returns(false)+ work.expects(:requeue).never+ assert_equal work, fetch.retrieve_work+ end++ private+ # Redis with expiring keys, enough for hold!.+ class FakeRedis+ def initialize+ @data = {}+ end++ def key?(key)+ expire(key)+ @data.key?(key)+ end++ def call(command, key, *args)+ expire(key)+ case command+ when "GET" then @data.dig(key, :value)+ when "EXISTS" then @data.key?(key) ? 1 : 0+ when "SET" then @data[key] = { value: args[0].to_s, expires_at: Time.current + args[2].to_i }+ end+ end++ private+ def expire(key)+ @data.delete(key) if @data.key?(key) && @data[key][:expires_at] <= Time.current+ end+ end++ def with_hold_redis+ redis = FakeRedis.new+ BackgroundJobHealth.stubs(:one_ai_thread?).returns(true)+ Sidekiq.stub(:redis, ->(&block) { block.call(redis) }) { yield redis }+ end++ def fetch_for(queues, concurrency: 1)+ capsule = Sidekiq::Capsule.new("test", Sidekiq.default_configuration)+ capsule.queues = queues+ capsule.concurrency = concurrency+ ChatReservation::Fetch.new(capsule)+ end+enddiff --git a/test/models/chat_test.rb b/test/models/chat_test.rbindex ba86ebdc81..2e4806a6bf 100644--- a/test/models/chat_test.rb+++ b/test/models/chat_test.rb@@ -68,6 +68,26 @@ class ChatTest < ActiveSupport::TestCasechat.ask_assistant(user_message, assistant_message: pending)end+ test "a finished reply holds the reservation and refreshes the bubble" do+ chat = chats(:one)+ user_message = chat.messages.where(type: "UserMessage").first+ UserMessage.any_instance.expects(:request_response).with(assistant_message: nil)+ ChatReservation.expects(:hold!).returns(60)+ ChatReservation.expects(:bubble).with(60).returns(seconds: 60, busy: false)+ Turbo::StreamsChannel.expects(:broadcast_update_to).with(chat, targets: ChatReservation::TARGETS, partial: "chats/reservation", locals: { bubble: { seconds: 60, busy: false } })++ AssistantResponseJob.perform_now(user_message)+ end++ test "a failed hold doesn't fail a finished reply" do+ user_message = chats(:one).messages.where(type: "UserMessage").first+ UserMessage.any_instance.expects(:request_response).with(assistant_message: nil)+ ChatReservation.stubs(:while_chat_runs).yields+ ChatReservation.expects(:hold!).raises(RedisClient::ConnectionError)++ assert_nothing_raised { AssistantResponseJob.perform_now(user_message) }+ end+test "creates with default model when model is nil" doprompt = "Test prompt"