Give each local model host a gate, with lanes and interrupts

Merged
JO
2d ago
+2005-147

Fourth PR in stack #5748 (#5744 → #5745 outbox → #5756 4a → 4b → 4c). #5745 and #5756 are merged, so this is now based on refactor/ai-plumbing. Plan: pr-4-sequencer.md steps 3–4, with the 4b items of stack-sequencer-off-the-web-thread.md §3, §3a, §3b and §3e (G1–G3).

Problem

4a gives each lane a queue and chat its own thread, but nothing orders the requests that reach a local model host. With more than one AI thread, a host with one slot gets several requests at once. A background request already at the model keeps it for its whole batch, whatever is waiting behind it.

Change

Opt-in, after review (2026-12-03). @luis-ibanez's review showed the gate doesn't suit an instance many families share, and found three bugs. We agreed that chat first is for one household on a local model, so it's now opt-in:

  • One setting, renamed. #5756 shipped Setting.ai_prompt_before_background (AI_PROMPT_BEFORE_BACKGROUND), which only orders the AI queues. It's renamed to ai_local_chat_first (AI_LOCAL_CHAT_FIRST, Self-hosting → Local model, one household). It's off by default, and it now also switches the gate: with it off there's no gate, and local requests go to the server as they come, as on main. 4c's typing hold follows it too.
  • Interrupts are bounded. A request interrupted twice is sent so that nothing interrupts it, so it ends. Before, steady chat traffic could resend a PDF read without end (21 sends on a 3 s budget in Luis's test).
  • Only the interrupt counts as the interrupt. A request's error becomes Ai::Gate::Interrupted only when it's a connection error after the interrupt shut that request's own socket (Holder#cut?). A 500, a timeout or a refused connection keeps its own error and retry rules.
  • No dead waiter. Joining the gate runs under Thread.handle_interrupt(Object => :never), and only the wait and the request itself can be interrupted, so a Timeout or a killed thread can't strand a place or a waiter.
  • A job that calls a model belongs on an AI queue. A model call from a job on any other queue raises Ai::Capsule::Violation in development and test (Ai::Capsule.check_job!, run by every transport call: the job half of the check 3d turns on fully). The full suite passes with it on. In production such a call is logged and runs in the prompt lane, not as interactive: it waits for a local host without interrupting anything, and never meets Busy, which would run a whole non-AI job (a sync, say) again.

The rest of this description is the gate as it works with the setting on.

  • Ai::Gate, one per local model host (host and port) in each worker. Every request to a local endpoint holds a place while it runs. RubyLLM's instrumenter, which every request passes, takes the place. Cloud endpoints have no gate.
    • Interactive requests wait first. When the host is full they interrupt the running request of the lowest lane, background before prompt, never another interactive one.
    • Prompt requests wait after them, in arrival order.
    • Background requests never wait: they raise Ai::Error::Busy.
    • With two or more places, one is kept for interactive requests.
  • The interrupt shuts the request's own socket. ProxyNetHttp reports each request's connection to the gate. shutdown wakes the blocked read, and the adapter raises Ai::Gate::Interrupted, a RubyLLM::CancelledError, so RubyLLM records that request's usage row as cancelled (tokens and cost unknown, G1), not failed. The shared Faraday connection is never touched (G2). The first commit proves this against a stub server before anything else was built: silent (reading the prompt) and streaming, direct and through a forward proxy.
  • Size: llama.cpp's total_slots from GET /props (through Ai::Transport::Http, so the proxy setting applies), else the endpoint's parallel_requests, else 1. Asked again after ten minutes.
  • Waiting doesn't spend the budget: the wait is added to the call's deadline, and the budget is checked after it.
  • Cancel point (§12): a generation's cancelled check runs once its request has a place, before it's sent.
  • Local endpoints connect within 10 s (connect_timeout), so a host that's off can't hold a place for the request timeout.
  • Local generations stream, so a server stops when the socket closes. The message is the same; usage still arrives. Each chunk resets the read timeout, so the stream block checks the call's budget on each chunk and raises Timeout once it's spent, which closes the connection. log_stream_debug = false next to log_bodies = false, so RUBYLLM_STREAM_DEBUG can't put chunks in the log.
  • Preempted is sent again by the transport. Ai::Transport::Base#attempt resends a preempted request on the same route once the gate lets it back in. It isn't a try, and it isn't a down mark or a failover. The instrumenter, which sees both intervals, credits the gate wait and the interrupted run to the call's deadline, each once.
  • Busy puts the job back. ApplicationJob has retry_on Ai::Error::Busy, wait: ->(_) { rand(5..15) }, attempts: :unlimited (G3: no cap). It's the same job, so the other errors' retry counts carry on; a generation step the queue refuses goes through GenerationJob#retry_job, which tells the requester. Ai::Generation#call, Ai::GenerationJob#perform and AiHealth::Probe re-raise it instead of treating it as a failure. A generation step stays in next_job and the run was touched as the job loaded it, so delivery doesn't step in, and nothing counts as a delivery or a step. The window is unchanged.
  • Busy isn't reported as a failure. The debug log and Langfuse skip it, as they skip health probes (Ai::Instrumentation.unreported?). Each re-enqueue would otherwise log an error every 5–15 s. Found live in 4c's measurement.
  • A local Jev batch that has begun finishes. It's one request per item, and a chat midway used to raise Busy and lose every answer so far. After its first answer, the rest wait in the prompt lane.
  • A shadow run whose host is busy is skipped, since a shadow run is never retried.
  • Jev's fan-out to a local server never asks for more places than its lane may hold (it would be Busy for good otherwise).

Differs from the plan:

  • Preempted is resent in the transport's attempt, not in Ai::Generation#on_routes. OCR, embeddings and Jev don't go through on_routes, so a PDF import's OCR page would otherwise fail on an interrupt. Same behaviour: same request, same route, not an attempt.
  • Busy is handled once, in ApplicationJob, not separately in GenerationJob and ProbeJob. ShadowJob skips it.
  • The drained ai_low_priority queue runs in the prompt lane, not background (changes 4a). It held PDF imports and indexing too, which mustn't meet Busy mid-import.
  • The cancel check runs once a place is free, not while waiting. No polling a database check under the gate's lock.
  • §3b's "read the proxy setting before waiting at the gate": on the stack proxy_or_warn never raises (an invalid proxy URL is warned about and skipped), so there's nothing to fail early. It matters again when #5487 lands.

Still in 4c: chat isn't on RubyLLM, so chat doesn't pass the gate yet (its temporary gate lines), the typing hold, the watchdog and the bubble, and the after-measurement. Today the gate orders bill suggestions (interactive), PDF imports and documents (prompt) and background work.

Tests

  • gate_interrupt_test (real sockets): interrupt while silent and while streaming, direct and through a forward proxy, and the server sees the close; interrupted before connecting; only its own request when two share one Faraday connection; an error without an interrupt is raised as it is. Each fails with the shutdown removed. A local generation still streaming when its 1 s budget runs out raises Timeout, the server sees the close, and its place is freed.

  • ai_gate_test: lane order; interrupt the lowest lane, one per waiting interactive request; never another interactive one; Busy; the kept interactive place; wait time yielded and added to the budget; an interrupted request's wait and run credited once each (0.5 s, not 0.82 s) and the request sent again; the cancel check; a place freed on error; shared gates per host; lanes from the job; sizing from parallel_requests, /props (with the key), a 404 and a refused connection, resized after ten minutes; Jev's cap; the connect timeout.

  • ai_transport_local_stream_test: a local generation streams (stream_options.include_usage), a cloud one doesn't; an interrupted request is sent again, with a cancelled usage row (tokens unknown, no cost, no error) and no failed row; two interrupts that outlast the budget still answer; a busy host is no down mark and no failover; no chunk text in the log with RUBYLLM_STREAM_DEBUG.

  • GenerationJob: Busy re-enqueues the same step and window in 5–15 s with no retry or delivery counted, then finishes; six Busys don't spend the five retries; four timeouts, a Busy and a fifth timeout give up; a refused requeue tells the requester. ProbeJob: Busy re-enqueues and stores nothing.

  • The llama.cpp categorize and bill-setup cassettes are re-recorded streamed, on 2026-11-24 against venus's llama.cpp (qwen3.6-35b-a3b-mtp, RubyLLM 2.2.3).

  • AiTestHelper#open_loopback_sockets gives the interrupt test real sockets (WebMock buffers a streamed body whole). It refuses any host but 127.0.0.1, and it lives in the one file the network policy allows.

Validation: bin/rails test, full suite, 20,288 runs, 0 failures (TZ=Etc/UTC). Rubocop and erb_lint clean, Brakeman no warnings. New tests: no gate without the setting; a request interrupted twice is sent uninterruptible and ends; an uninterruptible request makes chat wait; only a connection error after a cut socket is the interrupt (500, timeout and refused connection aren't); a thread killed just after it got its place leaves nothing behind (fails on the old gate); a model call from a job on a non-AI queue raises in test and is logged in production; such a job runs in the prompt lane.

Upgrade

The setting's rename needs no carry-over: ai_prompt_before_background reached only refactor/ai-plumbing (#5756), not main or any release, so no install has it set. The gate is off unless an admin turns on Local model, one household. With it on, each worker keeps its own gates, so use one worker process; with several workers against one local host, RAILS_AI_MAX_THREADS=0 on all but one (4a's docs) still applies. Behind an HTTP proxy, put local model hosts in NO_PROXY: an interrupt frees the server only if the proxy closes its upstream connection, and a dead host answers only after the proxy's own timeout.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUUTovNPgC5oNfUHKhd


Summary by cubic

Gives each local model host an optional gate that orders the requests reaching it, so a single-slot host no longer juggles several AI threads at once and a waiting interactive request gets served first. The gate follows ai_local_chat_first (renamed from ai_prompt_before_background), off by default: a local endpoint then has no gate and serves requests as they come.

  • Ai::Gate, one per local host per worker, holds a place for every request: interactive requests wait first and interrupt the lowest running lane; prompt requests wait in arrival order; background requests never wait and raise Busy, which ApplicationJob re-queues in 5–15 s via retry_on with no cap.
  • A host's servers (one per port) share its gate, since they share its GPU. It has as many places as the smallest server reports: llama.cpp's total_slots from GET /props, else the endpoint's parallel_requests, else 1, re-asked after ten minutes. Waiting is added to the call's deadline; the budget is checked after the wait.
  • An interrupt shuts the interrupted request's own socket (ProxyNetHttp), recording that usage row as cancelled. Only a connection error after that shutdown counts: a 500, timeout or refusal keeps its own rules, and a request interrupted twice is sent so nothing interrupts it again.
  • Local generations stream so a server stops when interrupted; each chunk checks the call's budget and log_stream_debug is off.
  • Jev's fan-out stays within the lane's places, and a background Jev batch that has begun waits in the prompt lane for the rest of its requests, so answers already gathered aren't lost on a busy host. The drained ai_low_priority queue now runs in the prompt lane so PDF imports and indexing don't hit Busy mid-import.
  • A Busy call is no failure: no debug-log entry or Langfuse error trace, since the job comes back anyway. A shadow run is skipped rather than re-queued.
  • A job outside the AI queues runs in the prompt lane, and a model call from one raises Ai::Capsule::Violation in development and test.

Summary by CodeRabbit

  • New Features
    • Local AI requests now share available host capacity, with interactive requests prioritized over prompt and background work.
    • Interactive requests can interrupt lower-priority work, which is retried without counting as an attempt.
    • Local AI responses stream as they are generated.
  • Bug Fixes
    • Background jobs that encounter a busy host are rescheduled after a short delay without using a retry.
    • PDF imports and other prompt work wait for a host slot instead of being treated as background work.
  • Documentation
    • Updated hosting and AI pipeline guides with local host capacity and request-priority behavior.