fix(jobs): run AI jobs in their own Sidekiq capsule so they can't starve syncs
Fixes #4223.
Problem
Every LLM job holds a Sidekiq thread for the whole model call, and the worker has 3 shared threads
(RAILS_MAX_THREADS). With a slow or single-request model (local inference on CPU, for example),
chat (AssistantResponseJob, high_priority) and merchant detection / auto-categorize
(medium_priority) fill all three for minutes. Queue weights don't help, because Sidekiq never
interrupts a running job, so syncs, balance recalculation and scheduled jobs wait behind them.
Over 14 days on a self-hosted instance (llama.cpp, CPU, one request at a time), SyncJob waited up
to 951 s, the hourly sync and cleanup jobs up to 1,394 s, and IdentifyRecurringTransactionsJob
up to 8,212 s. To users, balances don't update after an edit for up to ~16 minutes. Full numbers are
in #4223.
Rule runs made it worse: they queued AI jobs of 20 transactions, and with LLM_MAX_ITEMS_PER_CALL
below 20 the provider split each job into several calls made back to back, holding the thread
throughout.
Change
An AI capsule (config/sidekiq.yml, using Sidekiq's capsules:):
| Capsule | Queues | Threads |
|---|---|---|
| default | unchanged: scheduled, high_priority, medium_priority, low_priority, default | RAILS_MAX_THREADS - RAILS_AI_MAX_THREADS (3 − 1 = 2) |
| ai | ai_high_priority, then ai_low_priority (strict order) | RAILS_AI_MAX_THREADS (default 1) |
ai_high_priority:AssistantResponseJob.ai_low_priority:AutoCategorizeJob,
AutoDetectMerchantsJob,EnhanceProviderMerchantsJob,ProcessPdfJob,GenerateInsightsJob
(its cron fan-out still runs onscheduled; only the per-family runs, which call the LLM, move).RAILS_MAX_THREADSstays the worker's total thread count, so the total anddatabase.yml's pool
are unchanged.- One AI thread with strict order means a waiting chat goes next (it doesn't interrupt the job
already running), and a chat turn's calls run back to back. With a single-slot local model, this also stops merchant calls from evicting the
chat's prompt cache between rounds: we measured 4-15 min re-reads per call when they interleaved.
Providers that serve requests in parallel can raiseRAILS_AI_MAX_THREADS.
One LLM call per AI job.
- Auto-categorize and merchant-detection rule jobs hold
LLM_MAX_ITEMS_PER_CALLtransactions (ENV,
then Setting, else its documented default of 25) instead of a fixed 20. - Merchant enhancement works the same way:
EnhanceProviderMerchantsJobqueues one job per
LLM_MAX_ITEMS_PER_CALLunenhanced merchants (it used to make one call per 25 within a single job).
The "Enhance" button's lock now holds the number of those jobs, and the last one to finish
releases it, so a second click can't queue the same merchants again while they run. - The providers' hardcoded item caps (OpenAI's
max_itemsinBatchSlicer, Anthropic's 25-item
checks) give way toLLM_MAX_ITEMS_PER_CALL, applied when jobs are created.BatchSlicerstill
splits a batch that won't fit the context window (OpenAI-compatible providers only).
Behind a rule or enhancement job, a waiting chat therefore waits for one call. PDF import, insight
and chat jobs can still make several calls; making those one call per job is left for a follow-up
PR. Provider::LlmConcept.max_items_per_call is the
one lookup for the setting, for every provider, and its settings field moves from the OpenAI panel
to under the provider choice. The eval runners batch by it as well, replacing their fixed 25s, so eval
calls are the same size as production calls.
Health checks (SidekiqHealth):
- The AI queues don't count towards "queue backed up": a large merchant-detection run can queue for
hours while everything else stays current. "Oldest job age" still includes them. - New reason
ai_queues_not_polled(English and German): if no worker polls the AI queues, for
example one started with its own-qlist, the status and banner say so instead of chats and AI
rules failing silently.
Chat page (BackgroundJobHealth):
- The "responses may not be delivered" warning also requires a worker that polls
ai_high_priority, so users who aren't super admins (who don't see the site-wide banner) are told
too. Its 60 s check onhigh_priorityis unchanged. - New busy notice: if a chat would wait behind another AI job (
ai_high_priorityhas waited over
30 s or, with one AI thread,ai_low_priorityhas), the pending bubble says "System is busy. Your
message will be processed after the current job." (English and German) until the chat's job
starts and switches it back to "Thinking ...". It's pushed over the chat's existing Turbo stream.
Docs: a "Where AI jobs run (Sidekiq lanes)" section in docs/hosting/ai.md. It covers thread settings, workers with their own queue lists, and queue names after an upgrade. It is linked from the local-model notes, and docs/hosting/docker.md has one sentence on the worker's thread floor.
Hardcoded limits now configurable
The item limits are still there; they now all come from LLM_MAX_ITEMS_PER_CALL (default 25), which
users can set, instead of separate hardcoded values:
| Hardcoded limit | Added in | Now |
|---|---|---|
| Anthropic provider: "Max is 25 per request" (categorize, merchant detection, enhancement) | #1984 ("parity with OpenAI") | LLM_MAX_ITEMS_PER_CALL sizes every job's call; still at parity with OpenAI |
OpenAI provider: item cap in BatchSlicer | #1384 | LLM_MAX_ITEMS_PER_CALL sizes the jobs instead of slicing in the provider; the context-window slicing from #1384 is unchanged |
ProviderMerchant::Enhancer::BATCH_SIZE = 25 | #1254 | one enhancement job per LLM_MAX_ITEMS_PER_CALL merchants |
Eval runners' BATCH_SIZE / DEFAULT_BATCH_SIZE = 25, and the categorization runner's batch_size override for local models | #400 | evals batch by LLM_MAX_ITEMS_PER_CALL, so small batches for local models are now one setting away (the override was never settable from evals:run) |
Rule executors' batch_size = 20 | #376 | LLM_MAX_ITEMS_PER_CALL |
Upgrade notes
- Queue names: jobs already waiting on
high_priority/medium_priority/scheduledkeep their
queue and still run, on the default capsule. RAILS_MAX_THREADSmust exceedRAILS_AI_MAX_THREADS(at least 2 by default). Otherwise the
default capsule gets 0 threads and Sidekiq refuses to start ("Concurrency of 0 is not supported").- Custom worker commands (
sidekiq -q …, a Helmworker.commandoverride) must also poll
ai_high_priorityandai_low_priority. The defaultbundle exec sidekiqand the chart's
-C config/sidekiq.ymlalready do. - Rule job size: with
LLM_MAX_ITEMS_PER_CALLunset, AI rule jobs now hold 25 transactions
(was 20). - Item limit is the setting: the hardcoded caps listed above are replaced by
LLM_MAX_ITEMS_PER_CALL, which Sure doesn't cap further. OpenAI-compatible providers still split a
batch that doesn't fit the context window; with Anthropic, raiseANTHROPIC_MAX_TOKENS(default
4096) along with it, or replies are cut off. The docs and the field's help text say so. - Evals batch by
LLM_MAX_ITEMS_PER_CALL(default 25), so comparing batch sizes means setting it
per run. The categorization runner's unusedbatch_sizeoverride is removed. - No migration.
Validation
Tests:
test/config/sidekiq_config_test.rb(new): rendersconfig/sidekiq.ymlthe way Sidekiq's CLI
does. It checks the ai capsule's queues, order and threads, the default capsule's 3 − 1, that
the two capsules share no queues, that all six AI jobs use the ai queues, and that
SidekiqHealth::AI_QUEUESmatches the capsule.test/models/sidekiq_health_test.rb: an AI backlog stays healthy but still shows in the oldest
job age; unpolled AI queues reportai_queues_not_polled; the healthy test process now polls the
AI queues.test/models/rule/action_executor/auto_detect_merchants_test.rb(new): jobs are sized by
LLM_MAX_ITEMS_PER_CALL.test/models/provider/llm_concept_test.rb(new):max_items_per_callreads ENV, then the
setting, then 25.test/controllers/settings/hostings_controller_test.rb: the Max Items Per Batch field renders
once, outside the OpenAI panel.test/models/provider/openai_test.rb: a batch that fits the context window is sent as one call. Item-cap cases are removed there and in
batch_slicer_test.rb.test/models/provider_merchant/enhancer_test.rb:batchesholdsLLM_MAX_ITEMS_PER_CALL
merchants each, and a job withmerchant_idssends only those.test/jobs/enhance_provider_merchants_job_test.rb(new): the lock holds until the last batch
finishes, and is released when there's nothing to enhance.test/models/background_job_health_test.rb: unhealthy when no worker pollsai_high_priority;
busy (but healthy) when a chat waits; anai_low_prioritybacklog is busy with one AI thread only.test/models/chat_test.rb: the pending bubble gets the busy text, then "Thinking" when the job
starts.- The banner system test now covers the new reason's German text.
Pre-PR checklist on the latest commit (793f59c5c), run in the devcontainer services on top of
main (a3bb5d9). A baseline on unmodified main was also all green.
bin/rails test: 11,836 runs, 0 failures, 0 errors, 34 skipsDISABLE_PARALLELIZATION=true bin/rails test:system: 238 runs, 0 failures, 0 errorsbin/rubocop -f github -a: no offences, no autocorrectionsbundle exec erb_lint ./app/**/*.erb -a: no errorsnpm run lint: cleanbin/brakeman --no-pager: 0 warnings
On a self-hosted instance (llama.cpp, CPU, one request at a time), the same capsule and queue design
ran as a local patch on v0.7.5-hotfix.2. That patch has the capsule, the queues, the health
changes and jobs sized by LLM_MAX_ITEMS_PER_CALL, but not the rest of this PR: removing the
providers' item caps, the enhancer's per-batch jobs and the eval runners' batching are covered by
the unit tests only. First results, with LLM_MAX_ITEMS_PER_CALL=5:
- Balances update within seconds of an edit while merchant detection and chat run (previously up to
~16 minutes). - Merchant-detection jobs take ~45 s each (one call), down from 6-24 minutes (several calls).
- A chat queued during merchant detection waited 28 s, for the one merchant call in progress, then
ran ahead of the remaining merchant jobs.
Then with LLM_MAX_ITEMS_PER_CALL=20 (one rule run: 54 transactions, so 3 jobs of 20, 20 and 14):
- Each merchant job was one call: 130 s, 129 s and 99 s.
- A chat queued 22 s into the first job waited 108 s for it, then ran ahead of the two remaining
jobs. Its two calls ran back to back, and the second reused the first's prompt cache (17,580 of
22,194 tokens). - Two balance syncs from edits made during the run started at once and took ~0.2 s each.
Batch size versus accuracy and call time, on the same instance: Sure's merchant-detection eval
(merchant_detection_golden_v2, 100 samples, LLM_JSON_MODE=json_object) for five local models at
LLM_MAX_ITEMS_PER_CALL 5, 20 and 25. The call time is the longest a chat waits behind one merchant
job. Single runs: a repeat at 25 moved accuracy by up to 4 points.
| Model | Accuracy at 5 / 20 / 25 (repeat at 25) | Seconds per call at 5 / 20 / 25 |
|---|---|---|
| qwen3.6-35b-a3b | 92 / 91 / 92 (89) | 39 / 114 / 141 |
| thomson-1.0-small | 89 / 88 / 91 (90) | 37 / 127 / 159 |
| siq-1-35b-a3b | 83 / 83 / 85 (89) | 34 / 104 / 122 |
| tiel-coder-35b-a3b | 79 / 81 / 79 (81) | 33 / 104 / 114 |
| ling-3.0-tiny | 66 / 59 / 54 (56) | 19 / 66 / 72 |
- For the 35B-class models, accuracy doesn't depend on batch size beyond run-to-run noise. The
smallest model gets worse with bigger batches. - Call time grows roughly linearly with batch size (about 5 s per transaction plus ~14 s per call for
qwen3.6). At 5 a whole run takes ~35% longer than at 25 (qwen3.6: 781 s vs 566 s for 100
samples), but a chat waits ~40 s instead of ~2.5 min. - So the default of 25 suits fast or hosted providers, and slow local models can trade some
throughput for chat latency by loweringLLM_MAX_ITEMS_PER_CALL.
🤖 Generated with Claude Code
Summary by CodeRabbit
- New Features
- AI tasks now run in a dedicated processing lane, helping keep chat and other background work organized.
- Chat messages show a busy notice when AI processing is delayed, then update to a thinking status when processing begins.
- Merchant enhancements are processed in batches, with progress tracked until all batches are complete.
- Hosting settings now include a maximum batch size for LLM requests.
- Improvements
- AI processing can handle larger requests, with batch sizes adjusted to provider limits and oversized OpenAI-compatible requests split to fit context windows.
- Health reporting detects when AI queues are not being processed and distinguishes AI backlogs from other queue delays.