Hold back background AI jobs while someone writes a chat message

Merged
JO
8d ago
+551-33

With one AI thread (the default since #4237), a chat waits for whatever background AI job is
running when it's sent. Merchant detection and categorization jobs take one to two minutes each
on a local model, so a user who opens the chat after applying a rule, or just after a sync,
often waits that long before the reply even starts.

This PR adds a short chat reservation. Clicking into or typing in the chat box, and each
finished reply, hold back new ai_low_priority jobs for 60 seconds, so the message runs as soon
as it's sent. A job that is already running is not interrupted. With several AI threads, nothing
changes.

How it works

  • ChatReservation::Fetch < Sidekiq::BasicFetch leaves queue:ai_low_priority out of the
    fetch command while the Redis key chat_reservation exists (TTL 60 s). Sidekiq builds that
    queue list on every fetch, so held jobs stay in their queue, in order, with no clash with
    unique-job locks. A job popped by a fetch that was already waiting when the hold started goes
    back to the front of its queue (Sidekiq's own UnitOfWork#requeue). It's set as the server's
    fetch_class in a startup hook, because app classes can't be loaded yet when the
    initializer runs. It only holds for a capsule that polls ai_low_priority with one thread.

  • Setting the key:

    • POST /chat_reservation (ChatReservationsController#create), sent by a new Stimulus
      controller on the chat box's focus and input, at most every 5 s.
    • AssistantResponseJob's ensure, through Chat#hold_reservation, so the user can read the
      reply and answer before background work takes the model back. This, and setting and clearing
      the chat flag, are best-effort (logged), so a Redis or broadcast error can't skip or fail a
      reply.
    • ChatReservation.hold! does nothing unless BackgroundJobHealth.one_ai_thread?. That now
      comes from the worker: a worker whose only AI capsule has one thread and polls both AI
      queues adds a one-ai-thread label to its Sidekiq process at startup, and the web side reads it from
      Sidekiq::ProcessSet, so web and worker can't disagree about RAILS_AI_MAX_THREADS. It's
      true only when exactly one live worker process polls the AI queues: with several, a chat can
      run on one while another runs background jobs, so nothing is held.
    • Cap: holds that follow each other within 60 s stop 15 minutes after the first one
      (chat_reservation:started), and holds resume 60 s later, so background AI jobs get a turn
      while someone keeps chatting. A hold that lapsed starts a new cap.
  • Bubble above the chat box (chats/_reservation), shown only when the hold makes a
    difference:

    • "ready", with a countdown, while ai_low_priority jobs are waiting;
    • "busy" while an ai_low_priority job is already running (it is never interrupted);
    • nothing while a chat is queued or running (ChatReservation.while_chat_runs sets a Redis
      flag around request_response, so interim replies count too), because the chat's own
      "Thinking" bubble covers that.

    The countdown runs in the browser from the server's seconds-left value; there's no polling.
    The bubble updates every chat composer on the page, in a role="status" polite live region.

  • BackgroundJobHealth.ai_busy? now means "one AI thread, and an AI-lane job (chat or
    background) is running right now" (one_ai_thread? && ai_job_running?, Sidekiq::WorkSet, not
    cached). The bubble only runs after hold! has checked for one AI thread, so it calls
    ai_job_running?(queues: ["ai_low_priority"]) directly and each ping scans the process set
    once. Both checks fail open (false) if Redis is unreachable, so focusing the chat box then
    renders no bubble instead of an error. The latency rule from #4237
    (AI_BUSY_SECONDS = 30) is removed: with the reservation, a waiting backlog no longer delays a
    chat, so only a running job does.

  • docs/hosting/ai.md: the "Busy notice" bullet is updated, a "Chat reservation" bullet is
    added, and the -q fallback says the reservation doesn't hold AI jobs on those shared threads.

  • Copy: the reservation bubble strings (en, de), and a friendlier chats.ai_busy ("Just
    finishing off a background task, then I'll get straight onto your message."). The ai_busy
    rewording is its own commit (the last one) and can be dropped.

Screenshots

Screenshot from 2026-10-23 16-49-52

Measurements

Self-hosted instance, v0.7.6-alpha.8 with this branch cherry-picked; llama.cpp, one slot, Qwen3.6
on CPU; RAILS_AI_MAX_THREADS unset (1). Each run applies a rule that queues three
AutoDetectMerchantsJobs (about 45–130 s each), then sends a chat message. Times are from the
worker's ActiveJob log lines and llama.cpp's timing lines.

RunHoldMerchant job running when the chat was sent?Chat wait (enqueue → start)
Baselinenoyes55.6 s
Baseline (hold requests didn't reach the server)noyes104 s
With the reservationyesno, all 3 held for 88 s before sending0.004 s

In the run with the reservation, the merchant jobs started 60.3 s after the reply finished
(the hold from the job's ensure), and then ran normally.

The cost: background AI work is delayed by whatever time the user spends in the chat box, plus
60 s after each reply. In that run, the merchant jobs were held for 8.8 minutes in total, of which
6.3 were the chat itself (they would have waited for it anyway under strict order). When the user
doesn't reply, the last 60 s leave the model idle. Back-to-back holds stop after 15 minutes and
resume 60 s later, so the hold alone can't keep background AI jobs waiting. A queued chat still
runs before them, as with strict order today.

Prompt cache: llama.cpp's host-RAM prompt cache (--cache-ram, on by default) saved the chat's
state when a background job took the slot and restored it afterwards: in one baseline turn, 18,360
of 19,246 prompt tokens were reused. So on a current llama.cpp the main win is the wait shown
above, not keeping the cache warm. Servers without such a cache, or with a smaller one, also
benefit there.

Not in this PR

  • Per-family holds. The key is global, because there's one AI lane per worker.

Related

  • Discussion #4439: the proposal and measurements.
  • #4237 (merged): the AI Sidekiq lane with strict order and the busy notice; this builds on it.
  • #4121 / #4133: chat tool rounds and prompt-cache reuse on local models.

Validation

  • test/models/chat_reservation_test.rb:

    • Fetch drops ai_low_priority only while the key exists;
    • hold! is a no-op with several AI threads;
    • back-to-back holds stop at the 15-minute cap and resume 60 s later; a lapsed hold starts a
      new cap (Redis faked with expiring keys, time travelled);
    • the bubble shows only when jobs wait or one runs, and is hidden while a chat is queued or
      running; it doesn't check for one AI thread again;
    • while_chat_runs clears its flag when the block raises, and a Redis error while clearing
      it doesn't fail the reply;
    • Fetch requeues an ai_low_priority job popped while held, and a capsule with several
      threads ignores the hold.

    Redis is stubbed, since parallel test processes share one Redis.

  • test/controllers/chat_reservations_controller_test.rb: typing sets the hold; the response is
    the ready bubble while jobs wait, the busy bubble while one runs, and empty otherwise.

  • test/models/chat_test.rb: a finished reply requests the response, holds the reservation and
    refreshes the bubble; a failed hold doesn't fail the reply.

  • test/models/background_job_health_test.rb: ai_busy? is true for a running chat or
    ai_low_priority job, false for other queues or several AI threads; ai_job_running? can be
    limited to some AI queues; both checks return false when Redis is unreachable;
    one_ai_thread? is true only for a single labelled worker process polling AI
    queues, not two; a worker only gets the label when its only AI capsule has one thread and polls
    both AI queues (not with a second capsule polling an AI queue, as with -q).

  • Booted real workers against the test Redis: one worker with one AI thread is published with
    the label and read as one AI thread, with the web side's own RAILS_AI_MAX_THREADS unset;
    one with two AI threads, or started with -q … ai_low_priority as well, gets no label; two
    one-thread workers together aren't one AI thread.

  • Ran on the self-hosted instance above for the measurements.

All 30 open PRs in the v0.7.6 milestone merge cleanly on top of this branch. The ones touching the
same files are:

  • config/routes.rb;
  • the Sidekiq initializer (#4295 middleware, #3098 startup hook);
  • the chat locales (#4295);
  • docs/hosting/ai.md (#4063, #3580).

Pre-PR checklist on 20b397519 (base main c8467fce1):

  • bin/rails test: 13,123 runs, 0 failures, 0 errors, 36 skips
  • bin/rubocop on the changed files: no offences
  • bin/brakeman --no-pager: 0 warnings

On 87245afde (20b397519 changes no views or JS):

  • DISABLE_PARALLELIZATION=true bin/rails test:system: 296 runs, 1 failure,
    CashFlowTest#test_spending_without_income_renders_the_deficit_cash_flow_expense_path, which
    fails the same way on main in this environment
  • bundle exec erb_lint ./app/**/*.erb -a: no errors
  • npm run lint: clean

🤖 Generated with Claude Code


Summary by cubic

With one AI thread, a chat sent while a background AI job runs waits one to two minutes for that job's LLM call on a local model. This PR holds new ai_low_priority jobs for 60 seconds while someone focuses on or types in the chat box, and after each finished reply, so the message starts immediately (measured wait drops from 56–104 s to under a second).

New Features

  • A custom Sidekiq fetch skips ai_low_priority only while a Redis key exists, so held jobs keep their order; a running job is never interrupted, and a job popped by a fetch that started before the hold returns to the front of its queue.
  • The hold applies only when exactly one worker process runs both AI queues with a single thread. The worker gets the one-ai-thread label only when its sole AI capsule has one thread; another capsule or process polling an AI queue (such as a worker started with -q) leaves a thread free for the chat, so nothing is held, and the web process reads the label so it can't disagree with the worker about RAILS_AI_MAX_THREADS.
  • Back-to-back holds stop 15 minutes after the first and resume 60 seconds later, so background AI work still gets a turn.
  • A bubble above the chat box shows a countdown while jobs wait, "busy" while one runs, and nothing while a chat is queued or running; it updates every chat composer on the page in a polite live region.
  • ai_busy? now means one AI thread and an AI job running right now, replacing the 30-second latency rule; the busy check covers ai_low_priority only, and Redis or broadcast errors never fail a finished reply or skip the chat's own run.

Summary by CodeRabbit

  • New Features

    • Added chat notices showing when background tasks are waiting or still finishing, with a countdown when available.
    • Reservation notices update as you compose a message and after the assistant replies. When the assistant is finishing a background task, a notice explains the delay. Background tasks wait while chat is active, while already-running tasks finish without interruption.
    • Reservations apply when a single AI thread is available and are limited in duration.
  • Documentation

    • Updated AI hosting guidance with reservation timing and background-task behavior.