Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Verify PDF support with a synthetic health probe (#3191)

Juan José Mata2abce5f5b739
diff --git a/app/models/ai_health.rb b/app/models/ai_health.rb
index af8737adf6..e20fee294d 100644
--- a/app/models/ai_health.rb
+++ b/app/models/ai_health.rb
@@ -19,6 +19,7 @@ class AiHealth
:embedding_endpoint, :embedding_model, :embedding_dimensions,
:pgvector_extension_available, :pgvector_extension_enabled,
:pgvector_table_available, :qdrant_endpoint, :llm_probe,
+ :pdf_text_extraction_probe, :pdf_vision_processing_probe,
:vector_store_probe, :embedding_probe
def initialize(run_probes: true, force_probes: false)
@@ -55,14 +56,20 @@ class AiHealth
@openai_custom_endpoint
end
- def pdf_processing_supported?
- @pdf_processing_supported == true
+ def pdf_text_extraction_supported?
+ @pdf_text_extraction_capable == true && pdf_text_extraction_probe.passing?
end
- def pdf_processing_status
- return :unavailable unless llm_configured?
+ def pdf_text_extraction_status
+ pdf_probe_status(pdf_text_extraction_probe, capable: @pdf_text_extraction_capable)
+ end
+
+ def pdf_vision_processing_supported?
+ @pdf_vision_processing_capable == true && pdf_vision_processing_probe.passing?
+ end
- pdf_processing_supported? ? :supported : :unsupported
+ def pdf_vision_processing_status
+ pdf_probe_status(pdf_vision_processing_probe, capable: @pdf_vision_processing_capable)
end
def vector_store_configured?
@@ -86,7 +93,9 @@ class AiHealth
end
def last_checked_at
- [ llm_probe, vector_store_probe, embedding_probe ].filter_map(&:checked_at).max
+ [ llm_probe, pdf_text_extraction_probe, pdf_vision_processing_probe, vector_store_probe, embedding_probe ]
+ .filter_map(&:checked_at)
+ .max
end
def self.redact_endpoint(value)
@@ -120,9 +129,11 @@ class AiHealth
@llm_model = effective_model(provider_for_details)
@llm_endpoint = endpoint(provider_for_details)
@llm_request_timeout = request_timeout(provider_for_details)
- @pdf_processing_supported = safely(false) do
+ @pdf_processing_capable = safely(false) do
@llm_provider&.supports_pdf_processing?(model: llm_model)
end
+ @pdf_text_extraction_capable = @pdf_processing_capable && @effective_llm_protocol == :openai
+ @pdf_vision_processing_capable = @pdf_processing_capable
@openai_endpoint = redact_endpoint(openai_uri_base.presence || OPENAI_DEFAULT_ENDPOINT)
@llm_access_token = access_token(@effective_llm_protocol)
@@ -148,6 +159,8 @@ class AiHealth
def load_probes
@llm_probe = llm_configured? ? Probe.not_checked : Probe.not_configured
+ @pdf_text_extraction_probe = llm_configured? && @pdf_text_extraction_capable ? Probe.not_checked : Probe.not_configured
+ @pdf_vision_processing_probe = llm_configured? && @pdf_vision_processing_capable ? Probe.not_checked : Probe.not_configured
@vector_store_probe = vector_store_adapter.present? ? Probe.not_checked : Probe.not_configured
@embedding_probe = vector_store_adapter == :pgvector ? Probe.not_checked : Probe.not_configured
return unless run_probes?
@@ -161,6 +174,24 @@ class AiHealth
model: llm_model,
openai_compatible: @effective_llm_protocol == :openai && openai_compatible_endpoint?
)
+ if @pdf_text_extraction_capable
+ @pdf_text_extraction_probe = probe.pdf_text_extraction(
+ provider: @effective_llm_protocol,
+ endpoint: @llm_raw_endpoint,
+ access_token: @llm_access_token,
+ model: llm_model,
+ openai_compatible: openai_compatible_endpoint?
+ )
+ end
+ if @pdf_vision_processing_capable
+ @pdf_vision_processing_probe = probe.pdf_vision_processing(
+ provider: @effective_llm_protocol,
+ endpoint: @llm_raw_endpoint,
+ access_token: @llm_access_token,
+ model: llm_model,
+ openai_compatible: @effective_llm_protocol == :openai && openai_compatible_endpoint?
+ )
+ end
end
case vector_store_adapter
@@ -186,6 +217,14 @@ class AiHealth
@run_probes
end
+ def pdf_probe_status(probe, capable:)
+ return :unavailable unless llm_configured?
+ return :unsupported unless capable
+ return :not_checked unless run_probes?
+
+ probe.passing? ? :supported : :failing
+ end
+
def load_pgvector_status
connection = ActiveRecord::Base.connection
@pgvector_table_available = connection.table_exists?(VectorStore::Pgvector::TABLE_NAME)
diff --git a/app/models/ai_health/probe.rb b/app/models/ai_health/probe.rb
index b4bb5c2a1a..21cb5798dd 100644
--- a/app/models/ai_health/probe.rb
+++ b/app/models/ai_health/probe.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require "digest"
+require "timeout"
class AiHealth
# Performs bounded, non-destructive checks against the exact services used
@@ -13,6 +14,18 @@ class AiHealth
DEFAULT_TIMEOUT = 5
EMBEDDING_TEST_INPUT = "Sure AI health check"
CHAT_TEST_INPUT = "Reply with OK."
+ PDF_TEST_INSTITUTION = "SUREHEALTHCHECKBANK"
+ PDF_TEST_LINES = [
+ "Bank Statement",
+ "Institution: #{PDF_TEST_INSTITUTION}",
+ "Account holder: Health Check",
+ "Statement period: 2026-01-01 to 2026-01-31",
+ "Opening balance: USD 100.00",
+ "Closing balance: USD 125.00",
+ "Transactions: 2",
+ "Synthetic data only. No customer data."
+ ].freeze
+ PDF_MAX_RESPONSE_TOKENS = 512
Result = Data.define(:status, :checked_at, :failure_code, :http_status) do
def passing?
@@ -76,6 +89,32 @@ class AiHealth
end
end
+ def pdf_text_extraction(provider:, endpoint:, access_token:, model:, openai_compatible: false)
+ pdf_processing(
+ provider: provider,
+ endpoint: endpoint,
+ access_token: access_token,
+ model: model,
+ openai_compatible: openai_compatible,
+ component: "pdf_text_extraction",
+ verification: :synthetic_pdf_text,
+ processing_mode: :text
+ )
+ end
+
+ def pdf_vision_processing(provider:, endpoint:, access_token:, model:, openai_compatible: false)
+ pdf_processing(
+ provider: provider,
+ endpoint: endpoint,
+ access_token: access_token,
+ model: model,
+ openai_compatible: openai_compatible,
+ component: "pdf_vision_processing",
+ verification: :synthetic_pdf_vision,
+ processing_mode: :vision
+ )
+ end
+
def openai_vector_store(endpoint:, access_token:)
run(
component: "vector_store",
@@ -120,6 +159,44 @@ class AiHealth
private
attr_reader :cache, :force
+ def pdf_processing(provider:, endpoint:, access_token:, model:, openai_compatible:, component:, verification:,
+ processing_mode:)
+ run(
+ component: component,
+ provider_key: provider,
+ endpoint: endpoint,
+ model: model,
+ credential: access_token,
+ verification: verification
+ ) do
+ result = Timeout.timeout(timeout) do
+ case provider
+ when :openai
+ Provider::Openai::PdfProcessor.new(
+ openai_client(access_token:, endpoint:),
+ model: model,
+ pdf_content: synthetic_pdf,
+ custom_provider: openai_compatible,
+ max_response_tokens: PDF_MAX_RESPONSE_TOKENS,
+ processing_mode: processing_mode
+ ).process
+ when :anthropic
+ raise Failure, :unsupported_provider unless processing_mode == :vision
+
+ Provider::Anthropic::PdfProcessor.new(
+ anthropic_client(access_token:, endpoint:),
+ model: model,
+ pdf_content: synthetic_pdf
+ ).process
+ else
+ raise Failure, :unsupported_provider
+ end
+ end
+
+ raise Failure, :invalid_response unless valid_pdf_result?(result)
+ end
+ end
+
def run(component:, provider_key:, endpoint: nil, model: nil, credential: nil, dimensions: nil, verification: nil)
key = cache_key(component:, provider_key:, endpoint:, model:, credential:, dimensions:, verification:)
cache.delete(key) if force
@@ -187,6 +264,41 @@ class AiHealth
response.is_a?(Hash) && response["choices"].is_a?(Array) && response["choices"].any?
end
+ def valid_pdf_result?(result)
+ result.is_a?(Provider::LlmConcept::PdfProcessingResult) &&
+ result.document_type == "bank_statement" &&
+ result.extracted_data.is_a?(Hash) &&
+ result.extracted_data["institution_name"] == PDF_TEST_INSTITUTION
+ end
+
+ def synthetic_pdf
+ return @synthetic_pdf if defined?(@synthetic_pdf)
+
+ text = PDF_TEST_LINES.map { |line| "(#{line}) Tj T*" }.join("\n")
+ content = "BT /F1 14 Tf 24 190 Td 22 TL\n#{text}\nET\n".b
+ objects = [
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 480 216] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
+ "<< /Length #{content.bytesize} >>\nstream\n#{content}endstream",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"
+ ]
+
+ pdf = "%PDF-1.4\n".b
+ offsets = [ 0 ]
+ objects.each_with_index do |object, index|
+ offsets << pdf.bytesize
+ pdf << "#{index + 1} 0 obj\n#{object}\nendobj\n".b
+ end
+
+ xref_offset = pdf.bytesize
+ pdf << "xref\n0 #{objects.size + 1}\n".b
+ pdf << "0000000000 65535 f \n".b
+ offsets.drop(1).each { |offset| pdf << format("%010d 00000 n \n", offset).b }
+ pdf << "trailer\n<< /Size #{objects.size + 1} /Root 1 0 R >>\nstartxref\n#{xref_offset}\n%%EOF\n".b
+ @synthetic_pdf = pdf.freeze
+ end
+
def cache_key(component:, provider_key:, endpoint:, model:, credential:, dimensions:, verification:)
fingerprint = Digest::SHA256.hexdigest(
[ component, provider_key, endpoint, model, credential, dimensions, verification ].join("\0")
@@ -207,7 +319,7 @@ class AiHealth
def failure_code(error)
return error.failure_code if error.respond_to?(:failure_code)
- error.is_a?(Faraday::TimeoutError) ? :timeout : :request_failed
+ error.is_a?(Faraday::TimeoutError) || error.is_a?(Timeout::Error) ? :timeout : :request_failed
end
def http_status(error)
diff --git a/app/models/provider/anthropic/pdf_processor.rb b/app/models/provider/anthropic/pdf_processor.rb
index 4b476751b2..b19d920266 100644
--- a/app/models/provider/anthropic/pdf_processor.rb
+++ b/app/models/provider/anthropic/pdf_processor.rb
@@ -83,6 +83,17 @@ class Provider::Anthropic::PdfProcessor
end
def output_tool
+ extracted_data_properties = {
+ institution_name: { type: [ "string", "null" ] },
+ statement_period_start: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },
+ statement_period_end: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },
+ transaction_count: { type: [ "integer", "null" ] },
+ opening_balance: { type: [ "number", "null" ] },
+ closing_balance: { type: [ "number", "null" ] },
+ currency: { type: [ "string", "null" ] },
+ account_holder: { type: [ "string", "null" ] }
+ }
+
{
name: TOOL_NAME,
description: "Return the structured analysis of the attached document.",
@@ -100,16 +111,7 @@ class Provider::Anthropic::PdfProcessor
},
extracted_data: {
type: "object",
- properties: {
- institution_name: { type: [ "string", "null" ] },
- statement_period_start: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },
- statement_period_end: { type: [ "string", "null" ], pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "YYYY-MM-DD or null" },
- transaction_count: { type: [ "integer", "null" ] },
- opening_balance: { type: [ "number", "null" ] },
- closing_balance: { type: [ "number", "null" ] },
- currency: { type: [ "string", "null" ] },
- account_holder: { type: [ "string", "null" ] }
- },
+ properties: extracted_data_properties,
required: [],
additionalProperties: false
}
diff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rb
index 5bf8267b48..871ba7dc19 100644
--- a/app/models/provider/openai/pdf_processor.rb
+++ b/app/models/provider/openai/pdf_processor.rb
@@ -1,9 +1,11 @@
class Provider::Openai::PdfProcessor
include Provider::Openai::Concerns::UsageRecorder
- attr_reader :client, :model, :pdf_content, :custom_provider, :langfuse_trace, :family, :max_response_tokens
+ attr_reader :client, :model, :pdf_content, :custom_provider, :langfuse_trace, :family, :max_response_tokens,
+ :processing_mode
- def initialize(client, model: "", pdf_content: nil, custom_provider: false, langfuse_trace: nil, family: nil, max_response_tokens:)
+ def initialize(client, model: "", pdf_content: nil, custom_provider: false, langfuse_trace: nil, family: nil,
+ max_response_tokens:, processing_mode: :auto)
@client = client
@model = model
@pdf_content = pdf_content
@@ -11,6 +13,7 @@ class Provider::Openai::PdfProcessor
@langfuse_trace = langfuse_trace
@family = family
@max_response_tokens = max_response_tokens
+ @processing_mode = processing_mode
end
def process
@@ -21,11 +24,20 @@ class Provider::Openai::PdfProcessor
# Try text extraction first (works with all models)
# Fall back to vision API with images if text extraction fails (for scanned PDFs)
- response = begin
+ response = case processing_mode
+ when :text
process_with_text_extraction
- rescue Provider::Openai::Error => e
- Rails.logger.warn("Text extraction failed: #{e.message}, trying vision API with images")
+ when :vision
process_with_vision
+ when :auto
+ begin
+ process_with_text_extraction
+ rescue Provider::Openai::Error => e
+ Rails.logger.warn("Text extraction failed: #{e.message}, trying vision API with images")
+ process_with_vision
+ end
+ else
+ raise ArgumentError, "Unknown PDF processing mode: #{processing_mode.inspect}"
end
span&.end(output: response.to_h)
diff --git a/app/views/admin/system_health/_ai_status.html.erb b/app/views/admin/system_health/_ai_status.html.erb
index 01cf6d0483..84ceb5608c 100644
--- a/app/views/admin/system_health/_ai_status.html.erb
+++ b/app/views/admin/system_health/_ai_status.html.erb
@@ -1,3 +1,18 @@
+<% pdf_checks = [
+ {
+ key: :pdf_text_extraction,
+ status: ai_health.pdf_text_extraction_status,
+ supported: ai_health.pdf_text_extraction_supported?,
+ probe: ai_health.pdf_text_extraction_probe
+ },
+ {
+ key: :pdf_vision_processing,
+ status: ai_health.pdf_vision_processing_status,
+ supported: ai_health.pdf_vision_processing_supported?,
+ probe: ai_health.pdf_vision_processing_probe
+ }
+] %>
+
<div class="space-y-4" data-testid="ai-status">
<div class="flex flex-wrap items-center justify-between gap-3">
<p class="text-sm text-secondary">
@@ -25,6 +40,14 @@
) %>
<% end %>
+ <% pdf_checks.select { |check| check[:status] == :failing }.each do |check| %>
+ <%= render DS::Alert.new(
+ title: t("admin.system_health.show.ai.alerts.#{check[:key]}_failed.title"),
+ message: t("admin.system_health.show.ai.alerts.#{check[:key]}_failed.message"),
+ variant: :error
+ ) %>
+ <% end %>
+
<% case ai_health.vector_store_status %>
<% when :failing %>
<% if ai_health.openai_vector_store_uses_custom_endpoint? %>
@@ -100,12 +123,14 @@
<dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.endpoint") %></dt>
<dd class="mt-1 break-all font-mono text-primary"><%= ai_health.llm_endpoint %></dd>
</div>
- <div>
- <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.pdf_processing") %></dt>
- <dd class="mt-1 font-medium <%= ai_health.pdf_processing_supported? ? "text-success" : "text-warning" %>">
- <%= t("admin.system_health.show.ai.pdf_statuses.#{ai_health.pdf_processing_status}") %>
- </dd>
- </div>
+ <% pdf_checks.each do |check| %>
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.#{check[:key]}") %></dt>
+ <dd class="mt-1 font-medium <%= check[:supported] ? "text-success" : (check[:status] == :failing ? "text-destructive" : "text-warning") %>">
+ <%= t("admin.system_health.show.ai.pdf_statuses.#{check[:status]}") %>
+ </dd>
+ </div>
+ <% end %>
<div>
<dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.request_timeout") %></dt>
<dd class="mt-1 font-medium text-primary"><%= t("admin.system_health.show.values.seconds", seconds: ai_health.llm_request_timeout) %></dd>
@@ -130,6 +155,12 @@
<dd class="mt-1 font-medium text-destructive"><%= t("admin.system_health.show.ai.failure_codes.#{ai_health.llm_probe.failure_code}") %></dd>
</div>
<% end %>
+ <% pdf_checks.select { |check| check[:probe].failure_code }.each do |check| %>
+ <div>
+ <dt class="text-secondary"><%= t("admin.system_health.show.ai.labels.#{check[:key]}_failure_reason") %></dt>
+ <dd class="mt-1 font-medium text-destructive"><%= t("admin.system_health.show.ai.failure_codes.#{check[:probe].failure_code}") %></dd>
+ </div>
+ <% end %>
</dl>
<% end %>
diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.yml
index 1e221cd782..939e97c69f 100644
--- a/config/locales/views/admin/system_health/en.yml
+++ b/config/locales/views/admin/system_health/en.yml
@@ -45,6 +45,12 @@ en:
llm_probe_failed:
title: The LLM live check failed
message: Sure could not verify both the configured endpoint and model. The failure was recorded in Settings → Debug logs and Rails.logger.
+ pdf_text_extraction_failed:
+ title: The synthetic PDF text-extraction check failed
+ message: Sure could not complete the text-first path that extracts embedded PDF text locally and sends it to the configured model. No customer data was sent. The failure was recorded in Settings → Debug logs and Rails.logger.
+ pdf_vision_processing_failed:
+ title: The synthetic PDF vision/native check failed
+ message: Sure could not complete the image or native-document PDF path through the configured model. No customer data was sent. The failure was recorded in Settings → Debug logs and Rails.logger.
vector_probe_failed:
title: The document-search live check failed
message: Sure could not verify the selected vector store and every required embedding service. The failure was recorded in Settings → Debug logs and Rails.logger.
@@ -59,7 +65,7 @@ en:
message: Check the adapter requirements below. For pgvector, the database must provide the vector extension or an existing vector_store_chunks table.
llm:
title: LLM and PDF processing
- description: The live check queries the provider's models API and verifies that the configured model is available. Credential values are never displayed.
+ description: The live checks verify the configured model, then separately exercise text extraction and vision/native processing with a one-page synthetic PDF containing no customer data. Credential values are never displayed.
vector_store:
title: Vector store and document search
description: The live check queries the hosted vector-store API, or tests the pgvector table and creates one short embedding without storing it.
@@ -68,7 +74,8 @@ en:
effective_provider: Effective provider
model: Model
endpoint: Endpoint
- pdf_processing: PDF processing
+ pdf_text_extraction: PDF text-extraction path
+ pdf_vision_processing: PDF vision/native path
request_timeout: Request timeout
openai_credentials: OpenAI credentials
openai_compatible_credentials: OpenAI-compatible API credentials
@@ -80,6 +87,8 @@ en:
embedding_model: Embedding model
embedding_endpoint: Embedding endpoint
embedding_dimensions: Embedding dimensions
+ pdf_text_extraction_failure_reason: Text-extraction failure reason
+ pdf_vision_processing_failure_reason: Vision/native failure reason
storage_probe: pgvector storage check
embedding_probe: Embedding endpoint check
failure_reason: Failure reason
@@ -110,8 +119,10 @@ en:
available: Available
not_found: Not found
pdf_statuses:
- supported: Supported
- unsupported: Not supported by the effective provider/model
+ supported: Synthetic PDF check passed
+ failing: Synthetic PDF check failed
+ unsupported: Disabled or not supported by the effective provider/model
+ not_checked: Not checked
unavailable: Unavailable until an LLM provider is configured
probe_statuses:
passing: Live check passed
diff --git a/test/controllers/admin/system_health_controller_test.rb b/test/controllers/admin/system_health_controller_test.rb
index 7b5c3ac61b..5af9070db4 100644
--- a/test/controllers/admin/system_health_controller_test.rb
+++ b/test/controllers/admin/system_health_controller_test.rb
@@ -19,6 +19,8 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
Setting.stubs(:anthropic_base_url).returns(nil)
Setting.stubs(:anthropic_model).returns(nil)
AiHealth::Probe.any_instance.stubs(:llm).returns(probe_result(:passing))
+ AiHealth::Probe.any_instance.stubs(:pdf_text_extraction).returns(probe_result(:passing))
+ AiHealth::Probe.any_instance.stubs(:pdf_vision_processing).returns(probe_result(:passing))
AiHealth::Probe.any_instance.stubs(:openai_vector_store).returns(probe_result(:passing))
AiHealth::Probe.any_instance.stubs(:pgvector).returns(probe_result(:passing))
AiHealth::Probe.any_instance.stubs(:embedding).returns(probe_result(:passing))
@@ -97,7 +99,9 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_match(/OpenAI hosted vector store/, response.body)
assert_match(/Live check passed/, response.body)
assert_match(/Live checks passed/, response.body)
- assert_match(/Supported/, response.body)
+ assert_match(/PDF text-extraction path/, response.body)
+ assert_match(/PDF vision\/native path/, response.body)
+ assert_equal 2, response.body.scan(/Synthetic PDF check passed/).size
assert_no_match(/sk-secret-openai/, response.body)
end
@@ -105,6 +109,8 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
sign_in users(:sure_support_staff)
stub_healthy_sidekiq
AiHealth::Probe.any_instance.expects(:llm).never
+ AiHealth::Probe.any_instance.expects(:pdf_text_extraction).never
+ AiHealth::Probe.any_instance.expects(:pdf_vision_processing).never
AiHealth::Probe.any_instance.expects(:openai_vector_store).never
with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
@@ -150,6 +156,46 @@ class Admin::SystemHealthControllerTest < ActionDispatch::IntegrationTest
assert_no_match(/local-token|uri-secret|query-secret/, response.body)
end
+ test "AI status reports text and vision PDF probes separately" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+ AiHealth::Probe.any_instance.stubs(:pdf_vision_processing).returns(
+ probe_result(:failing, failure_code: :invalid_response)
+ )
+
+ with_ai_environment("OPENAI_ACCESS_TOKEN" => "sk-secret-openai") do
+ get admin_system_health_url(tab: "ai")
+ end
+
+ assert_response :success
+ assert_match(/PDF text-extraction path/, response.body)
+ assert_match(/PDF vision\/native path/, response.body)
+ assert_match(/The synthetic PDF vision\/native check failed/, response.body)
+ assert_match(/Synthetic PDF check passed/, response.body)
+ assert_match(/Synthetic PDF check failed/, response.body)
+ assert_match(/Vision\/native failure reason/, response.body)
+ assert_match(/unexpected response/, response.body)
+ assert_no_match(/sk-secret-openai/, response.body)
+ end
+
+ test "AI status does not probe PDF processing when it is explicitly disabled" do
+ sign_in users(:sure_support_staff)
+ stub_healthy_sidekiq
+ AiHealth::Probe.any_instance.expects(:pdf_text_extraction).never
+ AiHealth::Probe.any_instance.expects(:pdf_vision_processing).never
+
+ with_ai_environment(
+ "OPENAI_ACCESS_TOKEN" => "sk-secret-openai",
+ "OPENAI_SUPPORTS_PDF_PROCESSING" => "false"
+ ) do
+ get admin_system_health_url(tab: "ai")
+ end
+
+ assert_response :success
+ assert_match(/Disabled or not supported by the effective provider\/model/, response.body)
+ assert_no_match(/The synthetic PDF .* check failed/, response.body)
+ end
+
test "AI status reports Anthropic with an available pgvector store" do
sign_in users(:sure_support_staff)
stub_healthy_sidekiq
diff --git a/test/models/ai_health/probe_test.rb b/test/models/ai_health/probe_test.rb
index 07fb85a2e4..5e7430cd0e 100644
--- a/test/models/ai_health/probe_test.rb
+++ b/test/models/ai_health/probe_test.rb
@@ -74,6 +74,160 @@ class AiHealth::ProbeTest < ActiveSupport::TestCase
assert result.passing?
end
+ test "synthetic PDF is valid and contains no customer data" do
+ pdf = @probe.send(:synthetic_pdf)
+ reader = PDF::Reader.new(StringIO.new(pdf))
+
+ assert_equal 1, reader.page_count
+ AiHealth::Probe::PDF_TEST_LINES.each do |line|
+ assert_includes reader.pages.first.text, line
+ end
+ end
+
+ test "PDF text-extraction probe exercises only the OpenAI text processor and validates its result" do
+ response = {
+ "choices" => [
+ {
+ "message" => {
+ "content" => {
+ document_type: "bank_statement",
+ summary: "A synthetic bank statement containing no customer data.",
+ extracted_data: {
+ institution_name: AiHealth::Probe::PDF_TEST_INSTITUTION
+ }
+ }.to_json
+ }
+ }
+ ]
+ }
+ client = mock("openai_client")
+ captured = nil
+ client.expects(:chat).with do |params|
+ captured = params
+ true
+ end.returns(response)
+ @probe.stubs(:openai_client).returns(client)
+ Provider::Openai::PdfProcessor.any_instance.expects(:convert_pdf_to_images).never
+
+ result = @probe.pdf_text_extraction(
+ provider: :openai,
+ endpoint: "https://api.cloudflare.example.test/v1",
+ access_token: "token",
+ model: "text-model",
+ openai_compatible: true
+ )
+
+ assert result.passing?
+ instructions = captured.dig(:parameters, :messages, 0, :content)
+ document_text = captured.dig(:parameters, :messages, 1, :content)
+ assert_not_includes instructions, AiHealth::Probe::PDF_TEST_INSTITUTION
+ assert_includes document_text, AiHealth::Probe::PDF_TEST_INSTITUTION
+ end
+
+ test "PDF vision probe exercises only the OpenAI vision processor and validates its result" do
+ response = {
+ "choices" => [
+ {
+ "message" => {
+ "content" => {
+ document_type: "bank_statement",
+ summary: "A synthetic bank statement containing no customer data.",
+ extracted_data: {
+ institution_name: AiHealth::Probe::PDF_TEST_INSTITUTION
+ }
+ }.to_json
+ }
+ }
+ ]
+ }
+ client = mock("openai_client")
+ captured = nil
+ client.expects(:chat).with do |params|
+ captured = params
+ true
+ end.returns(response)
+ @probe.stubs(:openai_client).returns(client)
+ Provider::Openai::PdfProcessor.any_instance.expects(:convert_pdf_to_images).once.returns([ "encoded-page" ])
+
+ result = @probe.pdf_vision_processing(
+ provider: :openai,
+ endpoint: "https://api.cloudflare.example.test/v1",
+ access_token: "token",
+ model: "vision-model",
+ openai_compatible: true
+ )
+
+ assert result.passing?
+ instructions = captured.dig(:parameters, :messages, 0, :content)
+ assert_not_includes instructions, AiHealth::Probe::PDF_TEST_INSTITUTION
+ end
+
+ test "PDF processing probes require the expected institution in the standard result fields" do
+ response = {
+ "choices" => [
+ {
+ "message" => {
+ "content" => {
+ document_type: "bank_statement",
+ summary: "A different bank statement.",
+ extracted_data: { institution_name: "Another Bank" }
+ }.to_json
+ }
+ }
+ ]
+ }
+ client = stub(chat: response)
+ @probe.stubs(:openai_client).returns(client)
+ Provider::Openai::PdfProcessor.any_instance.stubs(:convert_pdf_to_images).returns([ "encoded-page" ])
+ Rails.logger.stubs(:error)
+ DebugLogEntry.stubs(:capture)
+
+ result = @probe.pdf_vision_processing(
+ provider: :openai,
+ endpoint: "https://api.cloudflare.example.test/v1",
+ access_token: "token",
+ model: "vision-model",
+ openai_compatible: true
+ )
+
+ assert result.failing?
+ assert_equal :invalid_response, result.failure_code
+ end
+
+ test "PDF vision probe sends the synthetic PDF as an Anthropic document block" do
+ tool_use = Struct.new(:type, :input).new(
+ :tool_use,
+ {
+ "document_type" => "bank_statement",
+ "summary" => "A synthetic bank statement containing no customer data.",
+ "extracted_data" => {
+ "institution_name" => AiHealth::Probe::PDF_TEST_INSTITUTION
+ }
+ }
+ )
+ response = Struct.new(:content, :usage).new([ tool_use ], nil)
+ messages = mock("anthropic_messages")
+ messages.expects(:create).with do |params|
+ source = params.dig(:messages, 0, :content, 0, :source)
+ extracted_data_schema = params.dig(:tools, 0, :input_schema, :properties, :extracted_data)
+ source[:media_type] == "application/pdf" &&
+ Base64.strict_decode64(source[:data]) == @probe.send(:synthetic_pdf) &&
+ extracted_data_schema[:properties].key?(:institution_name) &&
+ extracted_data_schema[:required].empty? &&
+ !params[:system_].include?(AiHealth::Probe::PDF_TEST_INSTITUTION)
+ end.returns(response)
+ @probe.stubs(:anthropic_client).returns(stub(messages: messages))
+
+ result = @probe.pdf_vision_processing(
+ provider: :anthropic,
+ endpoint: "https://api.anthropic.com",
+ access_token: "token",
+ model: "claude-sonnet-4-6"
+ )
+
+ assert result.passing?
+ end
+
test "failed LLM probe writes a system-wide debug entry and Rails log without secrets" do
models = stub(list: { "data" => [ { "id" => "another-model" } ] })
@probe.stubs(:openai_client).returns(stub(models: models))
diff --git a/test/models/provider/openai/pdf_processor_test.rb b/test/models/provider/openai/pdf_processor_test.rb
index 4f6ff1b2b9..cb57b81868 100644
--- a/test/models/provider/openai/pdf_processor_test.rb
+++ b/test/models/provider/openai/pdf_processor_test.rb
@@ -59,6 +59,44 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase
assert_match(/detail unavailable/i, captured_output[:error_detail])
end
+ test "text mode exercises only text extraction" do
+ expected = Provider::LlmConcept::PdfProcessingResult.new(
+ summary: "Synthetic PDF",
+ document_type: "other",
+ extracted_data: {}
+ )
+ processor = Provider::Openai::PdfProcessor.new(
+ mock,
+ model: "gpt-4.1",
+ pdf_content: @pdf_content,
+ max_response_tokens: 512,
+ processing_mode: :text
+ )
+ processor.expects(:process_with_text_extraction).returns(expected)
+ processor.expects(:process_with_vision).never
+
+ assert_equal expected, processor.process
+ end
+
+ test "vision mode exercises only vision processing" do
+ expected = Provider::LlmConcept::PdfProcessingResult.new(
+ summary: "Synthetic PDF",
+ document_type: "other",
+ extracted_data: {}
+ )
+ processor = Provider::Openai::PdfProcessor.new(
+ mock,
+ model: "gpt-4.1",
+ pdf_content: @pdf_content,
+ max_response_tokens: 512,
+ processing_mode: :vision
+ )
+ processor.expects(:process_with_text_extraction).never
+ processor.expects(:process_with_vision).returns(expected)
+
+ assert_equal expected, processor.process
+ end
+
private
def build_processor(error, trace)
client = mock
diff --git a/test/system/admin/system_health_test.rb b/test/system/admin/system_health_test.rb
index 7a0a022b03..4b102dd4b2 100644
--- a/test/system/admin/system_health_test.rb
+++ b/test/system/admin/system_health_test.rb
@@ -9,6 +9,8 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
Setting.stubs(:openai_model).returns(nil)
stub_healthy_sidekiq
AiHealth::Probe.any_instance.stubs(:llm).returns(probe_result(:passing))
+ AiHealth::Probe.any_instance.stubs(:pdf_text_extraction).returns(probe_result(:passing))
+ AiHealth::Probe.any_instance.stubs(:pdf_vision_processing).returns(probe_result(:passing))
AiHealth::Probe.any_instance.stubs(:openai_vector_store).returns(probe_result(:passing))
end
@@ -26,6 +28,9 @@ class Admin::SystemHealthTest < ApplicationSystemTestCase
assert_current_path admin_system_health_path(tab: "ai")
assert_selector "button[role='tab'][aria-selected='true']", text: "AI status"
assert_text "Live check passed"
+ assert_text "PDF text-extraction path"
+ assert_text "PDF vision/native path"
+ assert_text "Synthetic PDF check passed", count: 2
assert_text "Live checks passed"
end
end