The personal finance app for everyone (by everyone)
Ruby
fix(pdf-vision): render PDFs with poppler-utils + surface a concrete admin failure reason (#3275)
jaysbeekay125666f59d7a
diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfileindex 8d62c15254..fcbe5cb76d 100644--- a/.devcontainer/Dockerfile+++ b/.devcontainer/Dockerfile@@ -6,6 +6,7 @@ ENV DEBIAN_FRONTEND=noninteractive# libvips42 supports ActiveStorage image variants through image_processing/ruby-vips# for existing profile/avatar images. AccountStatement.original_file only stores# PDF/CSV/XLSX originals, but the devcontainer needs this broader image stack.+# poppler-utils provides pdftoppm, required for the PDF vision processing path.RUN apt-get update -qq \&& apt-get -y install --no-install-recommends \apt-utils \@@ -20,8 +21,9 @@ RUN apt-get update -qq \libyaml-0-2 \openssh-client \postgresql-client \- vim \+ poppler-utils \procps \+ vim \&& rm -rf /var/lib/apt/lists /var/cache/apt/archivesRUN gem install bundler foremandiff --git a/Dockerfile b/Dockerfileindex f691c470bf..b2547216d4 100644--- a/Dockerfile+++ b/Dockerfile@@ -8,8 +8,9 @@ FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim AS baseWORKDIR /rails# Install base packages+# poppler-utils provides pdftoppm, required for the PDF vision processing pathRUN apt-get update -qq \- && apt-get install --no-install-recommends -y curl libvips postgresql-client libyaml-0-2 procps libjemalloc2 \+ && apt-get install --no-install-recommends -y curl libvips postgresql-client libyaml-0-2 procps libjemalloc2 poppler-utils \&& rm -rf /var/lib/apt/lists /var/cache/apt/archives# Set production environmentdiff --git a/app/models/ai_health/probe.rb b/app/models/ai_health/probe.rbindex 374df44a18..9046e95bc0 100644--- a/app/models/ai_health/probe.rb+++ b/app/models/ai_health/probe.rb@@ -475,8 +475,14 @@ class AiHealthseconds.positive? ? seconds : DEFAULT_TIMEOUTend+ # Map a probe error to a machine-readable code for the admin AI status+ # page. Prefers an explicit `failure_code` the error carries (e.g. a+ # provider raising for a specific reason like a missing renderer binary),+ # then classifies Faraday/Timeout errors as :timeout, and falls back to+ # :request_failed for everything else.def failure_code(error)- return error.failure_code if error.respond_to?(:failure_code)+ code = error.failure_code if error.respond_to?(:failure_code)+ return code if codeerror.is_a?(Faraday::TimeoutError) || error.is_a?(Timeout::Error) ? :timeout : :request_failedenddiff --git a/app/models/provider.rb b/app/models/provider.rbindex e97023499a..dfa49c91d0 100644--- a/app/models/provider.rb+++ b/app/models/provider.rb@@ -2,17 +2,25 @@ class ProviderResponse = Data.define(:success?, :data, :error)class Error < StandardError- attr_reader :details+ attr_reader :details, :failure_code- def initialize(message, details: nil)+ # Builds a provider error. `details` holds opaque response metadata+ # (e.g. the upstream body); `failure_code` is an optional symbol the+ # admin AI status page and health probe key on so they can show a+ # specific, actionable reason instead of a generic message.+ def initialize(message, details: nil, failure_code: nil)super(message)@details = details+ @failure_code = failure_codeend+ # Serialized form for API consumers. Includes `failure_code` so+ # downstream UI can branch on the reason rather than the message text.def as_json{message: message,- details: details+ details: details,+ failure_code: failure_code}endend@@ -43,15 +51,26 @@ class Provider)end- # Override to set class-level error transformation for methods using `with_provider_response`+ # Fallback transformation applied by `with_provider_response` when no+ # `error_transformer:` is given. Re-wraps an arbitrary rescue into a+ # `self.class::Error`, carrying over the error's `failure_code` (when+ # present and truthy) and, for Faraday errors, the response body as+ # `details`. Subclasses may override this to customise.def default_error_transformer(error)+ kwargs = if error.respond_to?(:failure_code) && error.failure_code+ { failure_code: error.failure_code }+ else+ {}+ end+if error.is_a?(Faraday::Error)self.class::Error.new(error.message,details: error.response&.dig(:body),+ **kwargs)else- self.class::Error.new(error.message)+ self.class::Error.new(error.message, **kwargs)endendenddiff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rbindex 871ba7dc19..375155817b 100644--- a/app/models/provider/openai/pdf_processor.rb+++ b/app/models/provider/openai/pdf_processor.rb@@ -205,6 +205,11 @@ class Provider::Openai::PdfProcessorparse_response_generic(response)end+ # Render each PDF page to a base64-encoded PNG using pdftoppm+ # (poppler-utils). Distinguishes "renderer binary absent" (raise a coded+ # Provider::Openai::Error with failure_code :render_missing_binary) from+ # "renderer ran but rejected the input" (return [] so the caller can+ # degrade to the text-extraction path unchanged).def convert_pdf_to_imagesreturn [] if pdf_content.blank?@@ -212,21 +217,36 @@ class Provider::Openai::PdfProcessorpdf_path = File.join(tmpdir, "input.pdf")File.binwrite(pdf_path, pdf_content)- # Convert PDF to PNG images using pdftoppm+ # Render via pdftoppm (poppler-utils). Kernel#system returns `nil` when+ # the executable cannot be started (binary not installed) and `false`+ # when it runs but exits non-zero (present but rejected the input).output_prefix = File.join(tmpdir, "page")- system("pdftoppm", "-png", "-r", "150", pdf_path, output_prefix)+ rendered = system("pdftoppm", "-png", "-r", "150", pdf_path, output_prefix)+ raise binary_missing_error if rendered.nil?- # Read all generated images+ # Read all generated images (empty array when pdftoppm exited non-zero)image_files = Dir.glob(File.join(tmpdir, "page-*.png")).sortimage_files.map do |img_path|Base64.strict_encode64(File.binread(img_path))endend+ rescue Provider::Openai::Error+ raiserescue => eRails.logger.error("Failed to convert PDF to images: #{e.message}")[]end+ # Coded error for the "pdftoppm not installed" case so the admin AI status+ # page can show a concrete, actionable failure reason instead of a generic+ # service error.+ def binary_missing_error+ Provider::Openai::Error.new(+ "Could not convert PDF to images: pdftoppm (poppler-utils) is not installed",+ failure_code: :render_missing_binary+ )+ end+def parse_response_generic(response)raw = response.dig("choices", 0, "message", "content")parsed = parse_json_flexibly(raw)diff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.ymlindex d1d52faabc..eab6c4ba45 100644--- a/config/locales/views/admin/system_health/en.yml+++ b/config/locales/views/admin/system_health/en.yml@@ -159,6 +159,7 @@ en:dimensions_mismatch: The embedding vector dimensions do not match the configured dimensionsextension_not_enabled: The PostgreSQL vector extension is not enabledtable_not_found: The vector_store_chunks table was not found+ render_missing_binary: The pdftoppm renderer (poppler-utils) is not available in this containertimeout: The service did not respond before the probe timeoutrequest_failed: The service request failedunsupported_provider: The provider does not support this checkdiff --git a/test/models/provider/openai/pdf_processor_test.rb b/test/models/provider/openai/pdf_processor_test.rbindex cb57b81868..2afa27335a 100644--- a/test/models/provider/openai/pdf_processor_test.rb+++ b/test/models/provider/openai/pdf_processor_test.rb@@ -97,6 +97,45 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCaseassert_equal expected, processor.processend+ test "convert_pdf_to_images raises a coded error when the pdftoppm binary is missing" do+ processor = Provider::Openai::PdfProcessor.new(+ mock,+ model: "gpt-4.1",+ pdf_content: @pdf_content,+ max_response_tokens: 512,+ processing_mode: :vision+ )++ # Simulate poppler-utils not being installed: Kernel#system returns `nil`+ # (the executable cannot be started) rather than `false`.+ processor.stubs(:system).returns(nil)++ error = assert_raises(Provider::Openai::Error) do+ processor.send(:convert_pdf_to_images)+ end++ assert_equal :render_missing_binary, error.failure_code+ assert_match(/poppler-utils/, error.message)+ end++ test "convert_pdf_to_images still degrades to [] when pdftoppm is present but rejects the PDF" do+ Rails.logger.stubs(:error)+ processor = Provider::Openai::PdfProcessor.new(+ mock,+ model: "gpt-4.1",+ pdf_content: @pdf_content,+ max_response_tokens: 512,+ processing_mode: :vision+ )++ # Binary is installed, but pdftoppm exits non-zero on bad input (system+ # returns `false`): keep the pre-existing "return no pages" behavior (no+ # coded error).+ processor.stubs(:system).returns(false)++ assert_equal [], processor.send(:convert_pdf_to_images)+ end+privatedef build_processor(error, trace)client = mockdiff --git a/test/models/provider_test.rb b/test/models/provider_test.rbindex 6d7fe13b1d..8a2f8653c9 100644--- a/test/models/provider_test.rb+++ b/test/models/provider_test.rb@@ -54,4 +54,53 @@ class ProviderTest < ActiveSupport::TestCaseassert_equal("some error", response.error.message)assert_instance_of TestProvider::TestError, response.errorend++ test "default_error_transformer preserves the failure_code when present" do+ source = Provider::Error.new("render failed", failure_code: :render_missing_binary)++ transformed = @provider.send(:default_error_transformer, source)++ assert_equal :render_missing_binary, transformed.failure_code+ end++ test "default_error_transformer drops a nil failure_code instead of passing it" do+ source = Provider::Error.new("render failed")++ transformed = @provider.send(:default_error_transformer, source)++ assert_nil transformed.failure_code+ end++ test "default_error_transformer preserves failure_code and response body for Faraday errors" do+ source = Faraday::ConnectionFailed.new("upstream failed")+ source.define_singleton_method(:failure_code) { :render_missing_binary }++ transformed = @provider.send(:default_error_transformer, source)++ assert_instance_of TestProvider::Error, transformed+ assert_equal "upstream failed", transformed.message+ assert_equal :render_missing_binary, transformed.failure_code+ end++ test "default_error_transformer extracts the response body into details for Faraday errors" do+ source = Faraday::ConnectionFailed.new("upstream failed")+ source.define_singleton_method(:response) { { body: { "error" => { "code" => "bad_pdf" } } } }++ transformed = @provider.send(:default_error_transformer, source)++ assert_equal({ "error" => { "code" => "bad_pdf" } }, transformed.details)+ assert_nil transformed.failure_code+ end++ test "Error#as_json includes the failure_code" do+ error = Provider::Error.new("render failed", details: { hint: "install poppler-utils" }, failure_code: :render_missing_binary)++ assert_equal(+ { message: "render failed", details: { hint: "install poppler-utils" }, failure_code: :render_missing_binary },+ error.as_json+ )++ plain = Provider::Error.new("boom")+ assert_nil plain.as_json[:failure_code]+ endend