Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(ai): verify AI configuration and provider liveness from worker processes (#3298)

jaysbeekay4bac6e4422ce
diff --git a/app/controllers/admin/system_health_controller.rb b/app/controllers/admin/system_health_controller.rb
index deb2a52f31..ab4fc1f1c3 100644
--- a/app/controllers/admin/system_health_controller.rb
+++ b/app/controllers/admin/system_health_controller.rb
@@ -15,6 +15,16 @@ module Admin
run_probes: ai_tab,
force_probes: ai_tab && params[:refresh_ai_health] == "1"
)
+ @worker_ai_health_results = WorkerAiHealth.recent if ai_tab
+ end
+
+ # Queues an asynchronous worker-side verification (see
+ # WorkerAiHealthCheckJob) and returns immediately -- the result appears
+ # in the AI status tab once whichever worker process dequeues it
+ # finishes, typically within a few seconds.
+ def verify_worker_ai
+ WorkerAiHealth.request_check!
+ redirect_to admin_system_health_path(tab: "ai"), notice: t(".queued")
end
end
end
diff --git a/app/jobs/worker_ai_health_check_job.rb b/app/jobs/worker_ai_health_check_job.rb
new file mode 100644
index 0000000000..fa4ea55d49
--- /dev/null
+++ b/app/jobs/worker_ai_health_check_job.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+# Runs the same bounded, non-destructive AI liveness probes AiHealth runs for
+# the web admin page, but from inside a Sidekiq worker process, and records
+# the result for System health -> AI status to display (#3169).
+#
+# Queued on demand (WorkerAiHealth.request_check!) rather than run
+# automatically: this makes real provider calls, so it should only happen
+# when an operator asks for it, exactly like the web page's "Run checks
+# again" button.
+#
+# Deliberately probes with an isolated, one-shot cache (ActiveSupport::Cache::NullStore)
+# instead of the shared Rails.cache AiHealth::Probe otherwise uses. Without
+# that, this job could read back a result a *web* request already cached
+# (proving nothing about the worker's own network path), and its own result
+# would sit in the shared cache where a subsequent web request could read it
+# back as if it had checked itself. Every run is a fresh, live check with no
+# footprint left in the shared probe cache either way.
+class WorkerAiHealthCheckJob < ApplicationJob
+ # Admin-triggered and its own result is what the operator is waiting on,
+ # so it shouldn't sit behind routine background work.
+ queue_as :high_priority
+
+ def perform
+ ai_health = AiHealth.new(run_probes: true, probe_cache: ActiveSupport::Cache::NullStore.new)
+
+ snapshot = WorkerAiHealth::Snapshot.new(
+ process_identity: WorkerAiHealth.current_process_identity,
+ hostname: Socket.gethostname,
+ pid: Process.pid,
+ checked_at: Time.current,
+ effective_provider: ai_health.effective_llm_provider,
+ llm_model: ai_health.llm_model,
+ llm_endpoint: ai_health.llm_endpoint,
+ llm_request_timeout: ai_health.llm_request_timeout,
+ function_calling_status: ai_health.function_calling_status,
+ vector_store_adapter: ai_health.vector_store_adapter,
+ embedding_model: ai_health.embedding_model,
+ embedding_endpoint: ai_health.embedding_endpoint,
+ embedding_dimensions: ai_health.embedding_dimensions,
+ llm_status: ai_health.llm_status,
+ vector_store_status: ai_health.vector_store_status,
+ failure_codes: failure_codes(ai_health)
+ )
+
+ WorkerAiHealth.record!(snapshot)
+ record_failure(snapshot) if snapshot.failing?
+ snapshot
+ end
+
+ private
+ def failure_codes(ai_health)
+ [
+ ai_health.llm_probe.failure_code,
+ ai_health.function_calling_probe.failure_code,
+ ai_health.pdf_text_extraction_probe.failure_code,
+ ai_health.pdf_vision_processing_probe.failure_code,
+ ai_health.vector_store_probe.failure_code,
+ ai_health.embedding_probe.failure_code
+ ].compact.uniq
+ end
+
+ # Mirrors AiHealth::Probe#record_failure's destinations (Rails.logger and
+ # DebugLogEntry) so a worker-side failure shows up in the same places an
+ # operator already checks for a web-side one, distinguished by category
+ # and the recorded process identity.
+ def record_failure(snapshot)
+ message = "AI health worker check failed on #{snapshot.process_identity}"
+ metadata = {
+ process_identity: snapshot.process_identity,
+ hostname: snapshot.hostname,
+ pid: snapshot.pid,
+ llm_status: snapshot.llm_status,
+ vector_store_status: snapshot.vector_store_status,
+ function_calling_status: snapshot.function_calling_status,
+ failure_codes: snapshot.failure_codes
+ }
+
+ Rails.logger.error("#{message}: #{metadata.to_json}")
+ DebugLogEntry.capture(
+ category: "ai_health_worker",
+ level: "error",
+ message: message,
+ source: self.class.name,
+ metadata: metadata
+ )
+ end
+end
diff --git a/app/models/ai_health.rb b/app/models/ai_health.rb
index 67afafe1a5..ac7217c2f6 100644
--- a/app/models/ai_health.rb
+++ b/app/models/ai_health.rb
@@ -22,9 +22,15 @@ class AiHealth
:function_calling_probe, :pdf_text_extraction_probe,
:pdf_vision_processing_probe, :vector_store_probe, :embedding_probe
- def initialize(run_probes: true, force_probes: false)
+ # probe_cache lets a caller isolate where probe results are cached. The web
+ # admin page shares the default `Rails.cache`-backed probe cache so repeat
+ # page loads within the TTL don't re-hit providers; worker-originated
+ # verification (see WorkerAiHealthCheckJob) passes an isolated store so its
+ # results can never be served back to a web request, and vice versa (#3169).
+ def initialize(run_probes: true, force_probes: false, probe_cache: Rails.cache)
@run_probes = run_probes
@force_probes = force_probes
+ @probe_cache = probe_cache
load_llm_status
load_vector_store_status
load_probes
@@ -199,7 +205,7 @@ class AiHealth
@embedding_probe = vector_store_adapter == :pgvector ? Probe.not_checked : Probe.not_configured
return unless run_probes?
- probe = Probe.new(force: @force_probes)
+ probe = Probe.new(force: @force_probes, cache: @probe_cache)
if llm_configured?
@llm_probe = probe.llm(
provider: @effective_llm_protocol,
diff --git a/app/models/worker_ai_health.rb b/app/models/worker_ai_health.rb
new file mode 100644
index 0000000000..2a479c6992
--- /dev/null
+++ b/app/models/worker_ai_health.rb
@@ -0,0 +1,134 @@
+# frozen_string_literal: true
+
+require "socket"
+
+# Stores and reads short-lived, worker-originated AI configuration/liveness
+# results so System health -> AI status can show what a Sidekiq worker
+# actually resolves and can reach, not just the web process (#3169).
+#
+# AiHealth (and the page built on it) proves only that the `web` process
+# resolved a valid-looking configuration and could reach the provider from
+# its own network context. Most AI workloads -- assistant responses, PDF
+# processing, embeddings, auto-categorization, merchant detection -- run in
+# Sidekiq `worker` processes instead, which can differ in environment, DNS,
+# proxy, network policy, credentials, or model availability. A passing web
+# check says nothing about whether those actually work.
+#
+# A single queued WorkerAiHealthCheckJob only verifies whichever one worker
+# process dequeues it -- Sidekiq doesn't broadcast to every process, so this
+# is explicitly *not* full-fleet coverage. #recent keeps a small bounded
+# history keyed by process identity so an operator who runs the check a few
+# times (or across a few replicas) can see more than one process's result,
+# but a `passing` entry only ever describes the process named on it.
+class WorkerAiHealth
+ CACHE_KEY = "worker_ai_health/results/v1"
+
+ # How long a recorded result is kept in the shared store at all. Chosen to
+ # comfortably outlive an operator clicking through a few checks in one
+ # sitting without piling up results from workers that no longer exist.
+ RETENTION = 15.minutes
+
+ # A result older than this still displays (so a slow investigation doesn't
+ # lose context), but reads as :stale rather than :passing/:failing --
+ # "verification describes what new job executions will resolve", not a
+ # live guarantee about the process that produced it.
+ STALE_AFTER = 5.minutes
+
+ # Bounds how many distinct worker processes' results are retained at once,
+ # so a churning fleet (deploys, autoscaling) can't grow this without limit.
+ MAX_RESULTS = 5
+
+ # One worker process's configuration fingerprint and probe outcomes. Only
+ # non-secret fields: redacted endpoints (AiHealth already redacts these),
+ # model/adapter names, and probe statuses -- never a raw credential.
+ Snapshot = Data.define(
+ :process_identity, :hostname, :pid, :checked_at,
+ :effective_provider, :llm_model, :llm_endpoint, :llm_request_timeout,
+ :function_calling_status,
+ :vector_store_adapter, :embedding_model, :embedding_endpoint, :embedding_dimensions,
+ :llm_status, :vector_store_status,
+ :failure_codes
+ ) do
+ def stale?
+ checked_at.nil? || checked_at < WorkerAiHealth::STALE_AFTER.ago
+ end
+
+ # Most-specific-first: a stale result can't be trusted as passing or
+ # failing regardless of what it recorded at the time.
+ def status
+ return :stale if stale?
+ return :failing if failure_codes.present?
+ return :failing if llm_status.in?(%i[not_configured failing]) || vector_store_status.in?(%i[not_configured failing])
+ return :failing if function_calling_status.in?(%i[unavailable unsupported failing])
+
+ :passing
+ end
+
+ def passing?
+ status == :passing
+ end
+
+ def failing?
+ status == :failing
+ end
+
+ # Compares this worker's *effective* configuration against a web-side
+ # AiHealth snapshot. Endpoints on both sides are already redacted by
+ # AiHealth, so this never needs (or exposes) a credential to compare.
+ def matches_web?(ai_health)
+ effective_provider == ai_health.effective_llm_provider &&
+ llm_model == ai_health.llm_model &&
+ llm_endpoint == ai_health.llm_endpoint &&
+ llm_request_timeout == ai_health.llm_request_timeout &&
+ vector_store_adapter == ai_health.vector_store_adapter &&
+ embedding_model == ai_health.embedding_model &&
+ embedding_endpoint == ai_health.embedding_endpoint &&
+ embedding_dimensions == ai_health.embedding_dimensions
+ end
+ end
+
+ class << self
+ # Records (or replaces) the calling process's result. Keyed by process
+ # identity so repeated checks from the same worker update in place
+ # instead of accumulating, while different processes coexist up to
+ # MAX_RESULTS.
+ #
+ # Concurrent writes from two processes checking at nearly the same
+ # instant can race (read-modify-write on one cache key) and the loser's
+ # result is dropped for that round. Acceptable here: this is an
+ # operator-triggered, low-frequency action, not a hot path, and a
+ # dropped write just means running the check again.
+ def record!(snapshot, cache: Rails.cache)
+ results = recent(cache: cache).reject { |r| r.process_identity == snapshot.process_identity }
+ results = [ snapshot, *results ].first(MAX_RESULTS)
+ # Don't set expires_in here; let individual entries expire via checked_at time
+ cache.write(CACHE_KEY, results)
+ snapshot
+ end
+
+ # Every recorded result, most-recently-checked first. Entries beyond
+ # RETENTION age out of the cache entirely; entries within it but past
+ # STALE_AFTER are still returned (status: :stale) so an operator can see
+ # a worker went quiet rather than the section going empty.
+ def recent(cache: Rails.cache)
+ results = Array(cache.read(CACHE_KEY))
+ # Filter out entries older than RETENTION
+ results = results.select { |r| r.checked_at && r.checked_at > RETENTION.ago }
+ results.sort_by { |r| r.checked_at || Time.at(0) }.reverse
+ end
+
+ # Stable identity for "this OS process" -- hostname:pid. Good enough to
+ # distinguish workers across a fleet and to let repeated checks from the
+ # same process update one entry rather than duplicating it. Not a
+ # cryptographic identity; it doesn't need to be for an operator-facing
+ # display.
+ def current_process_identity
+ "#{Socket.gethostname}:#{Process.pid}"
+ end
+
+ # Enqueues an asynchronous worker-side check without blocking the caller.
+ def request_check!
+ WorkerAiHealthCheckJob.perform_later
+ end
+ end
+end
diff --git a/app/views/admin/system_health/_ai_status.html.erb b/app/views/admin/system_health/_ai_status.html.erb
index 1279b9073f..5b7019218a 100644
--- a/app/views/admin/system_health/_ai_status.html.erb
+++ b/app/views/admin/system_health/_ai_status.html.erb
@@ -321,6 +321,103 @@
</dl>
<% end %>
+ <%= render DS::Card.new(class: "gap-4") do %>
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <h2 class="text-lg font-semibold text-primary"><%= t("admin.system_health.show.ai.worker.title") %></h2>
+ <p class="mt-1 text-sm text-secondary"><%= t("admin.system_health.show.ai.worker.description") %></p>
+ </div>
+ <%= render DS::Button.new(
+ href: verify_worker_ai_admin_system_health_path,
+ method: :post,
+ variant: :outline,
+ size: :sm,
+ icon: "server",
+ text: t("admin.system_health.show.ai.worker.verify_button")
+ ) %>
+ </div>
+
+ <p class="text-sm text-secondary"><%= t("admin.system_health.show.ai.worker.coverage_notice") %></p>
+
+ <% worker_ai_health_results = Array(worker_ai_health_results) %>
+ <% if worker_ai_health_results.empty? %>
+ <%= render DS::Alert.new(title: t("admin.system_health.show.ai.worker.empty.title"), variant: :info) do %>
+ <p><%= t("admin.system_health.show.ai.worker.empty.description") %></p>
+ <% end %>
+ <% else %>
+ <div class="space-y-3" data-testid="worker-ai-health-results">
+ <% worker_ai_health_results.each do |result| %>
+ <% status_tone = { passing: :success, failing: :error, stale: :neutral }.fetch(result.status) %>
+ <% status_icon = { passing: "circle-check", failing: "circle-x", stale: "circle-help" }.fetch(result.status) %>
+ <% matches_web = result.matches_web?(ai_health) %>
+ <div class="rounded-lg border border-primary p-3" data-testid="worker-ai-health-result">
+ <div class="flex flex-wrap items-center justify-between gap-2">
+ <div>
+ <p class="font-mono text-sm text-primary" data-testid="worker-process-identity"><%= result.process_identity %></p>
+ <p class="text-xs text-secondary">
+ <%= t("admin.system_health.show.ai.worker.labels.checked_at") %>
+ <%= t("admin.system_health.show.values.time_ago", time_ago: time_ago_in_words(result.checked_at)) %>
+ </p>
+ </div>
+ <div class="flex flex-wrap items-center gap-2">
+ <%= render DS::Pill.new(
+ label: t("admin.system_health.show.ai.worker.configuration_statuses.#{matches_web ? :match : :mismatch}"),
+ tone: matches_web ? :neutral : :warning,
+ marker: false
+ ) %>
+ <%= render DS::Pill.new(
+ label: t("admin.system_health.show.ai.worker.statuses.#{result.status}"),
+ tone: status_tone,
+ marker: false,
+ icon: status_icon
+ ) %>
+ </div>
+ </div>
+ <dl class="mt-3 grid grid-cols-1 gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.effective_provider") %></dt>
+ <dd class="mt-1 font-medium text-primary">
+ <% if result.effective_provider %>
+ <%= t("admin.system_health.show.ai.providers.#{result.effective_provider}") %>
+ <% else %>
+ <span class="text-warning"><%= t("admin.system_health.show.ai.values.not_configured") %></span>
+ <% end %>
+ </dd>
+ </div>
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.model") %></dt>
+ <dd class="mt-1 break-all font-mono text-primary"><%= result.llm_model.presence || t("admin.system_health.show.ai.values.not_set") %></dd>
+ </div>
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.endpoint") %></dt>
+ <dd class="mt-1 break-all font-mono text-primary"><%= result.llm_endpoint %></dd>
+ </div>
+ <% if result.vector_store_adapter %>
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.adapter") %></dt>
+ <dd class="mt-1 font-medium text-primary"><%= t("admin.system_health.show.ai.adapters.#{result.vector_store_adapter}") %></dd>
+ </div>
+ <% end %>
+ <% if result.failure_codes.present? %>
+ <div class="sm:col-span-2 lg:col-span-3">
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.failure_reason") %></dt>
+ <dd class="mt-1 font-medium text-destructive">
+ <%= result.failure_codes.map { |code| t("admin.system_health.show.ai.failure_codes.#{code}") }.join(" · ") %>
+ </dd>
+ </div>
+ <% end %>
+ </dl>
+ </div>
+ <% end %>
+ </div>
+ <% end %>
+ <% end %>
+
+ <%= render DS::Alert.new(title: t("admin.system_health.show.ai.worker.settings_origin.title"), variant: :info) do %>
+ <p><%= t("admin.system_health.show.ai.worker.settings_origin.database_backed") %></p>
+ <p><%= t("admin.system_health.show.ai.worker.settings_origin.env_backed") %></p>
+ <% end %>
+
<%= render DS::Alert.new(title: t("admin.system_health.show.ai.local_setup.title"), variant: :info) do %>
<p><%= t("admin.system_health.show.ai.local_setup.description") %></p>
<p>
diff --git a/app/views/admin/system_health/show.html.erb b/app/views/admin/system_health/show.html.erb
index 59163cd59b..148decd6ce 100644
--- a/app/views/admin/system_health/show.html.erb
+++ b/app/views/admin/system_health/show.html.erb
@@ -16,6 +16,6 @@
<% end %>
<% tabs.with_panel(tab_id: "ai") do %>
- <%= render "ai_status", ai_health: @ai_health %>
+ <%= render "ai_status", ai_health: @ai_health, worker_ai_health_results: @worker_ai_health_results %>
<% end %>
<% end %>
diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.yml
index ca86a706da..19d56be4c5 100644
--- a/config/locales/views/admin/system_health/en.yml
+++ b/config/locales/views/admin/system_health/en.yml
@@ -2,6 +2,8 @@
en:
admin:
system_health:
+ verify_worker_ai:
+ queued: "Worker check queued. It will appear below once a worker process picks it up, usually within a few seconds."
show:
title: System health
tabs:
@@ -185,6 +187,29 @@ en:
timeout: The service did not respond before the probe timeout
request_failed: The service request failed
unsupported_provider: The provider does not support this check
+ worker:
+ title: Worker verification
+ description: The checks above ran from this web process. Most AI work -- assistant responses, PDF processing, embeddings, auto-categorization, and merchant detection -- actually runs in a Sidekiq worker process, which can differ in network access, DNS, proxy rules, or even loaded credentials. Queue a check to verify a worker's own configuration and connectivity.
+ verify_button: Verify worker configuration
+ coverage_notice: Each check verifies exactly one worker process -- whichever one dequeues it. With more than one worker replica, a passing result does not confirm every worker is healthy; queue the check again to sample another.
+ empty:
+ title: No worker has checked in yet
+ description: Click "Verify worker configuration" to queue an asynchronous check. The result appears here once a worker process picks it up.
+ labels:
+ process: Worker process
+ checked_at: Checked
+ configuration: Configuration
+ configuration_statuses:
+ match: Matches web
+ mismatch: Differs from web
+ statuses:
+ passing: Passing
+ failing: Failing
+ stale: Stale
+ settings_origin:
+ title: Which settings need a restart?
+ database_backed: "Provider, model, and API-key settings changed in Settings → Self-Hosting are stored in the database. rails-settings-cached invalidates the shared cache on write, so both web and worker resolve the new value for the next request or queued job -- no restart needed."
+ env_backed: "Embedding configuration, and any value only set through an environment variable, is fixed when each container starts. Rails cannot change another container's environment, so changing these requires restarting or recreating both the web and worker services -- and any deployment tooling that only restarts one of them (partial rollout, an updated Secret without a pod restart) will not pick up the change."
local_setup:
title: Recommended local setup
description: Run the LLM through your local OpenAI-compatible endpoint, store document vectors in pgvector, and point the embedding settings at an OpenAI-compatible embeddings endpoint. The PostgreSQL image must include the vector extension, and embedding dimensions must match the selected model.
diff --git a/config/routes.rb b/config/routes.rb
index 099f49c59b..65dd81d6dd 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -945,7 +945,9 @@ Rails.application.routes.draw do
# name even for singular resources, unlike its plural siblings above
# that happen to round-trip cleanly). The controller file is singular,
# so name it explicitly.
- resource :system_health, only: :show, controller: "system_health"
+ resource :system_health, only: :show, controller: "system_health" do
+ post :verify_worker_ai
+ end
end
# Defines the root path route ("/")
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index f80768d7ac..765f40257b 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -1485,6 +1485,54 @@ timeout and `AI_HEALTH_PROBE_CACHE_TTL` to change the cache duration. Failed
checks are written as system-wide entries in **Settings → Debug logs** and to
`Rails.logger`; endpoints are redacted and credentials are never included.
+#### Verifying Worker Configuration
+
+The checks above all run from the `web` process. Most AI work — assistant
+responses, PDF processing, embeddings, auto-categorization, and merchant
+detection — actually executes in a Sidekiq `worker` process, which can differ
+from `web` in network access, DNS, proxy rules, or even which credentials it
+loaded, especially in Kubernetes deployments using workload-specific overrides
+or a Secret updated without a pod restart. A passing web check does not prove
+a worker can reach the same provider.
+
+Click **Verify worker configuration** on the AI status tab to queue an
+asynchronous check (`WorkerAiHealthCheckJob`). It runs the same live probes
+from inside whichever worker process dequeues it, and the tab lists the
+result: that worker's process identity, when it checked, whether its
+effective configuration matches what `web` resolved, and probe outcomes.
+
+A few things this does and doesn't prove:
+
+- **One check verifies one worker.** Sidekiq doesn't broadcast a job to every
+ process, so a passing result confirms the process named on it is healthy —
+ not your whole fleet. With multiple worker replicas, queue the check again
+ to sample another; only the 5 most recently checked-in distinct processes
+ are kept (`WorkerAiHealth::MAX_RESULTS`) — a 6th eviction can push out an
+ older entry before its own `WorkerAiHealth::RETENTION` (15 minutes) is up —
+ and a result older than `WorkerAiHealth::STALE_AFTER` displays as **Stale**
+ rather than pass/fail.
+- **Worker checks never reuse a web-cached result, or vice versa.** The web
+ page's probes are cached briefly (see above) so repeat page loads don't
+ re-hit providers; the worker job deliberately bypasses that shared cache so
+ its result always reflects a live call from its own network context, and
+ never leaves an entry a web request could read back as if it had checked
+ itself.
+- **In local development, the web and worker results won't show up together.**
+ `bin/dev` runs `web` and `worker` as separate OS processes, and
+ `config/environments/development.rb` uses a process-local `:memory_store` /
+ `:null_store` cache there (production uses a shared Redis store). A worker
+ check queued locally writes to the worker process's own in-memory cache, so
+ the web page's "Verify worker configuration" button can appear to do
+ nothing — it isn't a bug, there's just no result for it to read back.
+- **Which settings need a restart depends on how they're set.** Provider,
+ model, and API-key settings changed in **Settings → Self-Hosting** are
+ stored in the database and take effect automatically for the next request
+ or queued job on both `web` and `worker` — no restart needed. Embedding
+ configuration, and anything only set through an environment variable, is
+ fixed when each container starts; changing it requires restarting or
+ recreating **both** `web` and `worker`. The AI status tab labels this
+ distinction next to the worker results.
+
#### Troubleshooting Pgvector and Embeddings
The AI status page reports separate failures for the PostgreSQL storage check
diff --git a/test/controllers/admin/system_health_controller_test.rb b/test/controllers/admin/system_health_controller_test.rb
index ab38294616..ef24af5687 100644
--- a/test/controllers/admin/system_health_controller_test.rb
+++ b/test/controllers/admin/system_health_controller_test.rb
@@ -454,7 +454,169 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_no_match(/qdrant-secret|query-secret|header-secret/, response.body)
end
+ test "AI status explains when no worker has checked in yet" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ get admin_system_health_url(tab: "ai")
+ end
+
+ assert_response :success
+ assert_match(/Worker verification/, response.body)
+ assert_match(/No worker has checked in yet/, response.body)
+ end
+
+ test "AI status renders a worker result and flags it matching the web configuration" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+
+ with_memory_cache do
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ WorkerAiHealth.record!(worker_snapshot(
+ process_identity: "worker-1:123",
+ effective_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ vector_store_adapter: :openai
+ ))
+
+ get admin_system_health_url(tab: "ai")
+ end
+ end
+
+ assert_response :success
+ assert_select "[data-testid='worker-process-identity']", text: "worker-1:123"
+ assert_match(/Matches web/, response.body)
+ assert_no_match(/sk-secret-openai/, response.body)
+ end
+
+ test "AI status flags a worker result whose configuration differs from the web process" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+
+ with_memory_cache do
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ WorkerAiHealth.record!(worker_snapshot(
+ process_identity: "worker-1:123",
+ effective_provider: :openai,
+ llm_model: "a-different-model-than-web-resolves",
+ llm_endpoint: "https://api.openai.com/v1"
+ ))
+
+ get admin_system_health_url(tab: "ai")
+ end
+ end
+
+ assert_response :success
+ assert_match(/Differs from web/, response.body)
+ end
+
+ test "AI status shows a failing worker result with its failure reason" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+
+ with_memory_cache do
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ WorkerAiHealth.record!(worker_snapshot(
+ process_identity: "worker-1:123",
+ llm_status: :failing,
+ failure_codes: [ :model_not_available ]
+ ))
+
+ get admin_system_health_url(tab: "ai")
+ end
+ end
+
+ assert_response :success
+ assert_match(/The configured model was not returned by the provider/, response.body)
+ end
+
+ test "AI status shows a stale worker result as stale rather than passing" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+
+ with_memory_cache do
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ WorkerAiHealth.record!(worker_snapshot(
+ process_identity: "worker-1:123",
+ checked_at: (WorkerAiHealth::STALE_AFTER + 1.minute).ago
+ ))
+
+ get admin_system_health_url(tab: "ai")
+ end
+ end
+
+ assert_response :success
+ assert_match(/Stale/, response.body)
+ end
+
+ test "verify_worker_ai queues an asynchronous worker check and redirects to the AI tab" do
+ sign_in users(:sure_support_staff)
+
+ assert_enqueued_with(job: WorkerAiHealthCheckJob) do
+ post verify_worker_ai_admin_system_health_url
+ end
+
+ assert_redirected_to admin_system_health_path(tab: "ai")
+ follow_redirect!
+ assert_match(/Worker check queued/, response.body)
+ end
+
+ test "non super admin cannot queue a worker check" do
+ sign_in users(:family_admin)
+
+ assert_no_enqueued_jobs only: WorkerAiHealthCheckJob do
+ post verify_worker_ai_admin_system_health_url
+ end
+
+ assert_redirected_to root_path
+ end
+
+ test "unauthenticated user cannot queue a worker check" do
+ assert_no_enqueued_jobs only: WorkerAiHealthCheckJob do
+ post verify_worker_ai_admin_system_health_url
+ end
+
+ assert_redirected_to new_session_path
+ end
+
private
+ # Stubs Rails.cache with an in-process MemoryStore for the duration of
+ # the block. Test env normally runs a NullStore (see config/environments/test.rb),
+ # under which WorkerAiHealth.record!/.recent (both cache: Rails.cache by
+ # default) would silently no-op -- fine for controller tests that don't
+ # care about worker results, but these need the round trip to actually work.
+ def with_memory_cache
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ yield
+ ensure
+ Rails.unstub(:cache)
+ end
+
+ def worker_snapshot(overrides = {})
+ WorkerAiHealth::Snapshot.new(
+ **{
+ process_identity: "worker:1",
+ hostname: "worker",
+ pid: 1,
+ checked_at: Time.current,
+ effective_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ llm_request_timeout: 60,
+ function_calling_status: :supported,
+ vector_store_adapter: nil,
+ embedding_model: nil,
+ embedding_endpoint: nil,
+ embedding_dimensions: nil,
+ llm_status: :passing,
+ vector_store_status: :not_configured,
+ failure_codes: []
+ }.merge(overrides)
+ )
+ end
+
def credentialed_url(scheme:, host:, port:, user:, password:, path: nil, query: nil)
URI::Generic.build(
scheme: scheme,
diff --git a/test/jobs/worker_ai_health_check_job_test.rb b/test/jobs/worker_ai_health_check_job_test.rb
new file mode 100644
index 0000000000..34a4f9398e
--- /dev/null
+++ b/test/jobs/worker_ai_health_check_job_test.rb
@@ -0,0 +1,136 @@
+require "test_helper"
+
+class WorkerAiHealthCheckJobTest < ActiveSupport::TestCase
+ AI_ENVIRONMENT = %w[
+ OPENAI_ACCESS_TOKEN OPENAI_URI_BASE OPENAI_MODEL
+ ANTHROPIC_ACCESS_TOKEN ANTHROPIC_API_KEY VECTOR_STORE_PROVIDER
+ ].index_with(nil).freeze
+
+ setup do
+ Setting.stubs(:llm_provider).returns("openai")
+ Setting.stubs(:openai_access_token).returns(nil)
+ Setting.stubs(:openai_uri_base).returns(nil)
+ Setting.stubs(:openai_model).returns(nil)
+ Setting.stubs(:anthropic_access_token).returns(nil)
+ @cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(@cache)
+ end
+
+ test "records a passing snapshot identifying this process" do
+ stub_probes(status: :passing)
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret") do
+ WorkerAiHealthCheckJob.perform_now
+ end
+
+ results = WorkerAiHealth.recent
+ assert_equal 1, results.size
+
+ snapshot = results.first
+ assert_equal WorkerAiHealth.current_process_identity, snapshot.process_identity
+ assert_equal Socket.gethostname, snapshot.hostname
+ assert_equal Process.pid, snapshot.pid
+ assert_equal :openai, snapshot.effective_provider
+ assert snapshot.passing?
+ end
+
+ test "never persists or logs the raw access token" do
+ stub_probes(status: :passing)
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-super-secret") do
+ WorkerAiHealthCheckJob.perform_now
+ end
+
+ snapshot = WorkerAiHealth.recent.first
+ refute_includes snapshot.to_h.values.map(&:to_s).join, "sk-super-secret"
+ end
+
+ test "a failing probe is recorded and written to the debug log" do
+ stub_probes(status: :failing, failure_code: :model_not_available)
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret") do
+ WorkerAiHealthCheckJob.perform_now
+ end
+
+ snapshot = WorkerAiHealth.recent.first
+ assert snapshot.failing?
+ assert_includes snapshot.failure_codes, :model_not_available
+
+ entry = DebugLogEntry.where(category: "ai_health_worker").last
+ assert_equal "error", entry.level
+ assert_match(/AI health worker check failed/, entry.message)
+ assert_equal WorkerAiHealth.current_process_identity, entry.metadata["process_identity"]
+ assert_no_match(/sk-secret/, entry.to_json)
+ end
+
+ test "a passing probe does not write to the debug log" do
+ stub_probes(status: :passing)
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret") do
+ assert_no_difference -> { DebugLogEntry.where(category: "ai_health_worker").count } do
+ WorkerAiHealthCheckJob.perform_now
+ end
+ end
+ end
+
+ test "probes with an isolated cache instead of the shared web-facing one" do
+ # The defining property this job needs (#3169): its probes must never
+ # read back a result a *web* AiHealth.new(probe_cache: Rails.cache) call
+ # cached, and must never leave one behind for a web request to reuse.
+ # Asserting the exact cache instance passed to AiHealth.new is a more
+ # direct proof of that than exercising real HTTP through every probe
+ # type, and doesn't need every probe stubbed to avoid unrelated
+ # WebMock failures.
+ AiHealth.expects(:new).with(run_probes: true, probe_cache: instance_of(ActiveSupport::Cache::NullStore))
+ .returns(stub_ai_health(status: :passing))
+
+ WorkerAiHealthCheckJob.perform_now
+
+ assert WorkerAiHealth.recent.first.passing?
+ end
+
+ private
+ def stub_probes(status:, failure_code: nil)
+ passing = AiHealth::Probe::Result.new(status: :passing, checked_at: Time.current, failure_code: nil, http_status: nil)
+ target = AiHealth::Probe::Result.new(status: status, checked_at: Time.current, failure_code: failure_code, http_status: nil)
+
+ AiHealth::Probe.any_instance.stubs(:llm).returns(target)
+ AiHealth::Probe.any_instance.stubs(:function_calling).returns(passing)
+ AiHealth::Probe.any_instance.stubs(:pdf_text_extraction).returns(passing)
+ AiHealth::Probe.any_instance.stubs(:pdf_vision_processing).returns(passing)
+ AiHealth::Probe.any_instance.stubs(:openai_vector_store).returns(passing)
+ AiHealth::Probe.any_instance.stubs(:pgvector).returns(passing)
+ AiHealth::Probe.any_instance.stubs(:embedding).returns(passing)
+ end
+
+ # A minimal stand-in for AiHealth exposing only what the job reads,
+ # for the cache-isolation test above where the real probing pipeline
+ # (and everything it would call out to) isn't the point being proven.
+ def stub_ai_health(status:)
+ probe_result = AiHealth::Probe::Result.new(status: status, checked_at: Time.current, failure_code: nil, http_status: nil)
+ not_configured = AiHealth::Probe.not_configured
+
+ OpenStruct.new(
+ effective_llm_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ function_calling_status: :supported,
+ vector_store_adapter: nil,
+ embedding_model: nil,
+ embedding_endpoint: nil,
+ embedding_dimensions: nil,
+ llm_status: status,
+ vector_store_status: :missing,
+ llm_probe: probe_result,
+ function_calling_probe: probe_result,
+ pdf_text_extraction_probe: not_configured,
+ pdf_vision_processing_probe: not_configured,
+ vector_store_probe: not_configured,
+ embedding_probe: not_configured
+ )
+ end
+
+ def with_ai_environment(overrides = {}, &block)
+ ClimateControl.modify(AI_ENVIRONMENT.merge(overrides), &block)
+ end
+end
diff --git a/test/models/worker_ai_health_test.rb b/test/models/worker_ai_health_test.rb
new file mode 100644
index 0000000000..bb1e90b075
--- /dev/null
+++ b/test/models/worker_ai_health_test.rb
@@ -0,0 +1,194 @@
+require "test_helper"
+
+class WorkerAiHealthTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
+
+ setup do
+ @cache = ActiveSupport::Cache::MemoryStore.new
+ end
+
+ test "records a snapshot and reads it back" do
+ snapshot = passing_snapshot(process_identity: "host-a:1")
+
+ WorkerAiHealth.record!(snapshot, cache: @cache)
+
+ assert_equal [ snapshot ], WorkerAiHealth.recent(cache: @cache)
+ end
+
+ test "returns an empty list when nothing has been recorded" do
+ assert_equal [], WorkerAiHealth.recent(cache: @cache)
+ end
+
+ test "recording again from the same process replaces its entry instead of duplicating" do
+ first = passing_snapshot(process_identity: "host-a:1", checked_at: 2.minutes.ago)
+ second = passing_snapshot(process_identity: "host-a:1", checked_at: Time.current)
+
+ WorkerAiHealth.record!(first, cache: @cache)
+ WorkerAiHealth.record!(second, cache: @cache)
+
+ results = WorkerAiHealth.recent(cache: @cache)
+ assert_equal 1, results.size
+ assert_equal second, results.first
+ end
+
+ test "different processes coexist, most recently checked first" do
+ older = passing_snapshot(process_identity: "host-a:1", checked_at: 2.minutes.ago)
+ newer = passing_snapshot(process_identity: "host-b:2", checked_at: Time.current)
+
+ WorkerAiHealth.record!(older, cache: @cache)
+ WorkerAiHealth.record!(newer, cache: @cache)
+
+ assert_equal [ newer, older ], WorkerAiHealth.recent(cache: @cache)
+ end
+
+ test "bounds the number of retained results" do
+ (WorkerAiHealth::MAX_RESULTS + 2).times do |i|
+ WorkerAiHealth.record!(
+ passing_snapshot(process_identity: "host-#{i}:#{i}", checked_at: i.minutes.ago),
+ cache: @cache
+ )
+ end
+
+ assert_equal WorkerAiHealth::MAX_RESULTS, WorkerAiHealth.recent(cache: @cache).size
+ end
+
+ test "a snapshot without a checked_at is stale" do
+ snapshot = passing_snapshot(checked_at: nil)
+
+ assert snapshot.stale?
+ assert_equal :stale, snapshot.status
+ end
+
+ test "a snapshot older than STALE_AFTER is stale even if it recorded passing" do
+ snapshot = passing_snapshot(checked_at: (WorkerAiHealth::STALE_AFTER + 1.second).ago)
+
+ assert snapshot.stale?
+ assert_equal :stale, snapshot.status
+ end
+
+ test "a fresh snapshot with no failures and nothing failing is passing" do
+ snapshot = passing_snapshot(checked_at: Time.current)
+
+ assert_not snapshot.stale?
+ assert_equal :passing, snapshot.status
+ assert snapshot.passing?
+ assert_not snapshot.failing?
+ end
+
+ test "any recorded failure code marks the snapshot failing regardless of individual statuses" do
+ snapshot = passing_snapshot(failure_codes: [ :model_not_available ])
+
+ assert_equal :failing, snapshot.status
+ assert snapshot.failing?
+ end
+
+ test "a failing llm_status marks the snapshot failing even with no failure codes" do
+ snapshot = passing_snapshot(llm_status: :failing)
+
+ assert_equal :failing, snapshot.status
+ end
+
+ test "a failing vector_store_status marks the snapshot failing" do
+ snapshot = passing_snapshot(vector_store_status: :failing)
+
+ assert_equal :failing, snapshot.status
+ end
+
+ test "unsupported or failing function calling marks the snapshot failing" do
+ assert_equal :failing, passing_snapshot(function_calling_status: :unsupported).status
+ assert_equal :failing, passing_snapshot(function_calling_status: :failing).status
+ end
+
+ test "matches_web? compares effective configuration field by field" do
+ ai_health = fake_ai_health
+
+ matching = passing_snapshot(
+ effective_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ vector_store_adapter: :pgvector,
+ embedding_model: "mxbai-embed-large",
+ embedding_endpoint: "http://ollama:11434/v1",
+ embedding_dimensions: 1024
+ )
+ assert matching.matches_web?(ai_health)
+
+ mismatched = passing_snapshot(
+ effective_provider: :openai,
+ llm_model: "a-different-model",
+ llm_endpoint: "https://api.openai.com/v1",
+ vector_store_adapter: :pgvector,
+ embedding_model: "mxbai-embed-large",
+ embedding_endpoint: "http://ollama:11434/v1",
+ embedding_dimensions: 1024
+ )
+ assert_not mismatched.matches_web?(ai_health)
+ end
+
+ test "matches_web? catches a request-timeout mismatch even when every other field matches" do
+ ai_health = fake_ai_health
+
+ assert passing_snapshot(llm_request_timeout: 30).matches_web?(ai_health)
+ assert_not passing_snapshot(llm_request_timeout: 90).matches_web?(ai_health)
+ end
+
+ test "current_process_identity combines hostname and pid" do
+ identity = WorkerAiHealth.current_process_identity
+
+ assert_includes identity, Socket.gethostname
+ assert_includes identity, Process.pid.to_s
+ end
+
+ test "request_check! enqueues the worker check job" do
+ assert_enqueued_with(job: WorkerAiHealthCheckJob) do
+ WorkerAiHealth.request_check!
+ end
+ end
+
+ test "a snapshot never carries a credential-shaped field" do
+ # Structural guard: the fields a Snapshot can hold are a fixed allowlist,
+ # so there is no field for a raw token, key, or password to ever land in
+ # by a future edit adding one more `ai_health.*` reader without noticing
+ # it's a secret (#3169's "never persist or display raw credentials").
+ disallowed = /token|secret|password|api_key|credential/i
+
+ assert_empty WorkerAiHealth::Snapshot.members.grep(disallowed)
+ end
+
+ private
+ def passing_snapshot(overrides = {})
+ WorkerAiHealth::Snapshot.new(
+ **{
+ process_identity: "host:1",
+ hostname: "host",
+ pid: 1,
+ checked_at: Time.current,
+ effective_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ llm_request_timeout: 30,
+ function_calling_status: :supported,
+ vector_store_adapter: :pgvector,
+ embedding_model: "mxbai-embed-large",
+ embedding_endpoint: "http://ollama:11434/v1",
+ embedding_dimensions: 1024,
+ llm_status: :passing,
+ vector_store_status: :passing,
+ failure_codes: []
+ }.merge(overrides)
+ )
+ end
+
+ def fake_ai_health
+ OpenStruct.new(
+ effective_llm_provider: :openai,
+ llm_model: "gpt-4.1",
+ llm_endpoint: "https://api.openai.com/v1",
+ llm_request_timeout: 30,
+ vector_store_adapter: :pgvector,
+ embedding_model: "mxbai-embed-large",
+ embedding_endpoint: "http://ollama:11434/v1",
+ embedding_dimensions: 1024
+ )
+ end
+end