AI plumbing 2e: documents

Merged
JO
8d ago
+7140-4385

Part 2e of the AI plumbing series. 2a (#4773) and 2b (#4774) are merged. This PR is one commit on refactor/ai-plumbing, after 2c (#4775) and 2d (#4765), and before 2f (#4892). Merge them in that order. Until 2c and 2d merge, this diff includes their changes. It includes #3422 (the statement vault bridge).

Part 2e of the AI plumbing redesign (#4440, §19): documents. PDF import and document search move onto the plumbing 2a–2d build, and the per-provider PDF workers go.

Implementation plan, with the decisions and an "As built" section: docs/proposals/v0.8/pr-2e-documents.md on #4440.

Problem

PDF import

  • Three classes per step, per provider. Today's PDF import uses Provider::{Openai,Anthropic}::{PdfProcessor,BankStatementExtractor}: 906 lines, each with its own usage recorder, JSON-mode or structured-output concern, and Langfuse traces.
  • Scans lose detail. A scan is read from at most five pages, sent at detail: "low", which shrinks a page to 512 pixels.
  • Page rendering isn't contained. pdftoppm runs with no timeout, renders every page, and inherits the worker's API keys and database URL.
  • Nothing checks the answer. In the RubyLLM spike, every wrong extraction still looked right.
  • Some models get a request they can't read. The OpenAI-compatible path sends a PDF to servers that refuse it, and page images to models without vision. llama.cpp answers images with a 500, which counts as an outage.

Embeddings and the OpenAI vector store

  • Embeddings skip the shared HTTP stack. They use a hand-built Faraday client with no proxy, no usage rows and no error mapping.
  • The OpenAI vector store adapter has five bugs (spike: "OpenAI vector stores"):
    • it doesn't wait for indexing;
    • a scan indexes as empty and still shows ready;
    • files stay in OpenAI's Files API after the document or the family is gone;
    • results show temp-file names;
    • every search returns something, so a question about one statement gets another as context.

What changes

flowchart TB
  U["Upload (Read as) · import_bank_statement(read_as:) · vault"] --> J["ProcessPdfJob on extract_pdf's lane"]
  J --> R["Ai::PdfReading: Auto from the last way that passed<br/>for this account + model"]
  R --> W{"way"}
  W -- "PDF (documents, within limits)" --> G
  W -- "Text layer" --> G
  W -- "Images (vision)" --> P["Pdf::PageImages<br/>hardened pdftoppm"] --> G
  W -- "OCR (from PR 7)" --> O["transport.ocr"] --> G
  G["ReadPdf · ExtractBankStatement<br/>Ai::Batch, no page limit"] --> C{"checks"}
  C -- pass --> OK["rows ready"]
  C -- fail --> NEXT["next way"] --> R
  C -- "nothing passes" --> FLAG["best kept, flagged:<br/>publishing asks to confirm"]
flowchart LR
  V["vault upload"] --> GATE{"Ai.available?(:embed, user)<br/>and the user's AI switch"}
  GATE --> IJ["IndexAccountStatementJob (embed lane)"]
  IJ --> PG["pgvector: Ai::Embeddings → transport.embed"]
  IJ --> OA["OpenAI store via Ai::Transport::Http<br/>processing → ready / unreadable / error"]
  Q["search_family_files"] --> SA{"search_documents?"}
  SA -- yes --> S["search, score ≥ 0.3, readable_by(user)"]
  SA -- no --> MD["#3422's metadata search + the router's reason"]

Transports. These calls come with their first callers (§7):

  • Request#attachments. Files go inline through RubyLLM, with page images at high detail.
    • A transport refuses images to a model without vision, and a PDF to one without documents, before anything is sent.
    • It also refuses a PDF over the preset's inline limit, since uploading to a provider's Files API stays off.
    • .ai events record each file's name and size, never its bytes.
  • transport.embed. It checks what RubyLLM 2.1.1 doesn't: one vector per text (#1269), each of the model's dimensions.
  • transport.ocr.
    • A local OCR model is read through chat, with its own prompt folder (unlimited_ocr_2, markdown). Special tokens that llama-server leaks are stripped.
    • Mistral and Cohere go through RubyLLM.ocr, one page image per request.

PDF reading (§8.1). Ai::PdfReading is the one input step before two generations: ReadPdf says what a document is, and ExtractBankStatement reads a statement's rows.

  • Ways of reading: the PDF itself, the text layer, page images, or OCR then the text model.

  • Auto tries them in that order, skips a way the route can't do, and starts from the way that last passed for the same account and model.

  • "Read as" picks one way. It's on the upload form, with the ways the route can't do greyed out, and is an optional argument of import_bank_statement. "Read again as…" reads an import another way before anything is published.

  • Checks need no answer key:

    • reconciles, using the balances printed in the text first (#4054);
    • amounts_in_source;
    • dates_anchored.

    On the spike's recordings they passed all 14 right extractions and failed all 12 wrong ones.

  • A failed extraction is never dropped. Auto tries the next way; if none passes, the best one is kept and flagged. The import page lists the failed checks, publishing asks for confirmation, and the email says so.

  • No page limit. Pages and text chunks are costed, batched by Ai::Batch and split on overflow. Rows repeated at a batch boundary are dropped (#846).

  • Pdf::PageImages keeps #3275's pdftoppm and hardens it:

    • an empty environment;
    • a process group killed after 30 s;
    • CPU and memory limits;
    • a page range;
    • a 25-megapixel guard before rendering, and a 1×1 check after.

Vector stores (§5.5).

  • pgvector embeds through Ai::Embeddings:
    • documents are indexed under embed and queries under search_documents;
    • it uses the route's first embedding model, with no failover;
    • the vector size comes from the embed route's model.
  • The OpenAI adapter, with the spike's fixes:
    • its client comes from Ai::Transport::Http;
    • files are uploaded under their own filename;
    • a document is processing until VectorStore::IndexStatusJob sets it ready, unreadable for an empty index, or error;
    • removing a document, or deleting the family, deletes the files from OpenAI.
  • Both stores drop matches scoring under 0.3.

#3422 on the plumbing (§5.5, §14).

  • IndexAccountStatementJob runs on embed's lane and is queued only when embed is available to the uploader and the uploader's AI switch is on.
  • search_family_files stays listed. Without search_documents it falls back to the vault's metadata, giving the router's reason.
  • get_document_text's note on a scan names the "Read as" way this install can read it with, or says none can.

Deletes.

  • Provider classes and concerns:
    • the four PDF and statement workers;
    • both usage recorders;
    • Openai::Concerns::JsonMode and Anthropic::Concerns::StructuredOutput;
    • the providers' PDF methods and Anthropic's structured-output helpers.
  • Their Langfuse traces and tests.
  • Provider::Registry.preferred_llm_provider. Chat's two checks ask Assistant.builtin_provider until PR 6.
  • Provider::Openai::UsageCost stays, because chat uses it.
  • 2,939 lines deleted in that commit.

Decisions (calls by @josh-sanders during development of PR #4440)

  1. OCR ships as code and tests, configurable from PR 7. There's no new ENV or setting (§4.7), so "Read as: OCR" is greyed out until then, and scans are read as page images on a vision model.
  2. Mistral and Cohere OCR ship with stubbed tests, marked untested live. Cohere has since been recorded with a trial key (below); Mistral's live test is skipped until someone records it with a key.
  3. Files that earlier removals left in OpenAI's Files API get a release note, not a clean-up task.
  4. OPENAI_SUPPORTS_PDF_PROCESSING=false keeps turning PDF import off, as today. An admin sets it per model from PR 7.
  5. The search score threshold stays 0.3 by default, calibrated on OpenAI's vector store. From PR 7 it's a setting per embedding model for both stores. The hosting guide says so now.
  6. PR 7 resolves an embedding model whose dimensions don't match the chunks table. Until then 2e sends no dimensions, as today, and fails a mismatch clearly (InvalidOutput).
  7. A provider whose strict mode refuses part of a schema is handled in PR 7, where each preset carries its schema dialect. Cohere refuses nullable objects and integer minimum. 2c's auto fallback stays as it is.

Reviewer guide (reading order)

  1. app/models/ai/pdf_reading.rb
  2. app/models/ai/generations/extract_bank_statement.rb, then read_pdf.rb and pdf_reading/pages.rb
  3. app/models/pdf/page_images.rb
  4. app/models/ai/transport/base.rb and compatible.rb: attachments, embed, ocr
  5. app/models/vector_store/openai.rb and app/jobs/vector_store/index_status_job.rb
  6. app/models/pdf_import.rb, app/jobs/process_pdf_job.rb and the views
  7. The merge-resolution commit 825731239 and 21d7e5edc, which move #3422's pieces onto the plumbing

Upgrade notes

  • Let the AI queues drain before upgrading, as for 2c (#4775).
  • Run the migration 20261107090000_add_pdf_reading_to_imports. It adds four nullable columns to imports.
  • PDF import reads every page, and scans go at high detail, so a scan costs more tokens on a cloud vision model.
  • On the deprecated ENV, PDF import ignores the 2,048-token baseline, as today: pages go in one request and text in 3,000-character chunks, split only if the server says it's too long. With LLM_CONTEXT_WINDOW set, batches fit that window.
  • OpenAI-compatible servers get the text layer or page images, never the PDF file. Only Anthropic and OpenAI's own API get the PDF.
  • OPENAI_SUPPORTS_PDF_PROCESSING=false still turns PDF import off, as does an OpenAI model without vision. PDF import now shows as not configured instead of failing after the upload.
  • An extraction that fails its checks is flagged, and publishing it asks for confirmation.
  • OpenAI vector store: documents show processing until indexed, and scans show unreadable. Removing a document or the family deletes its files from OpenAI. Files that earlier removals left there can't be found by Sure. List them in OpenAI's dashboard (Storage → Files, purpose assistants).
  • Searches drop matches scoring under 0.3. That's calibrated on OpenAI's vector store. On pgvector the scores depend on the embedding model: unrelated text scored 0.47 on Gemini and 0.75 on granite, so the floor rarely filters there.
  • Vault statements are indexed only for users with AI on, as #3422 does.

Validation

Run on 2026-11-07; the full suite last at be385fa05.

  • Full suite: bin/rails test gives 14,972 runs and 13 failures, all in 2d's baseline (#4765) and also failing on main: Wise*, BinanceItems, Budget, Demo::FinancekitGenerator. (Settings::HostingsControllerTest's market-data cron check, which races other workers on the shared Redis, failed once in an earlier run.)

  • System tests: imports, PDF reading, drag-and-drop import, bills, chats, rules and category rules pass, 46 runs, with PARALLEL_WORKERS=1 on Selenium.

  • Linters and scans: RuboCop (including Sure/NoAiEnv, whose 2e allowlist entries are gone), erb_lint, Biome and Brakeman are clean, and Pipelock's git scan-diff returns [].

  • New tests:

    • in test/architecture/: ai_transport_attachments_test, ai_transport_embed_test, ai_transport_ocr_test, ai_documents_test;
    • in test/models/: pdf/page_images_test (hardening, with stand-in pdftoppm scripts), ai/pdf_reading_test, ai/generations/{extract_bank_statement,read_pdf}_test (the checks on the spike's BAC sample statement), pdf_import_reading_test;
    • test/jobs/vector_store/index_status_job_test;
    • test/system/pdf_import_reading_test.
  • Live cassettes:

    • embed_live_test: venus llama.cpp, granite-embedding-small-english-r2. Gives 384 dimensions, a vector per text and a usage row.
    • generate_live_test on qwen3.6 was recorded on 2c (#4775) and merged forward.
  • Live PDF reading on the two sample statements (a throwaway test, not committed):

    StatementModelWayRowsChecks
    BAC, text layerqwen3.6 (venus, local)Text, chosen by Auto13/13 exactpass
    BACgemini-3.5-flash-lite (compatible API)Text, chosen by Auto; Images13/13 exactpass
    Impact, scannedqwen3.6 (no vision)——Unavailable (no_text_layer), nothing sent
    Impactgemini-3.5-flash-liteImages, chosen by Auto21/21pass
    ImpactOpenRouter nemotron-3.5-super-vl:free, dots-3-note-preview:freeImages22: adds the row the two pages disagree onreconciles fails → flagged

    read says what each statement is: a bank statement, with its institution or account holder.

  • ProcessPdfJob end to end, on the deprecated ENV (an OpenAI-compatible URL pointed at Gemini):

    • It reads the scan as images in one request. Two of three runs gave 21 rows and passed; one added the disputed row and was flagged.
    • With OPENAI_SUPPORTS_PDF_PROCESSING=false, PDF import shows as not configured.
  • Local OCR (venus llama.cpp, unlimited-ocr-2):

    • ocr_live_test recorded: the scan's first page, with both amounts.
    • "Read as: OCR" then Gemini (text only) read BAC 13/13 exact, and the checks passed.
    • The scan's second page sends this server's OCR model into a loop of empty table cells until its token limit, at any temperature. The spike's run on another conversion of the model read it. The extraction from that transcription had no amount in the source and was flagged.
  • Ollama in the dev pod (0.40.12, gpt-oss-20b from a local GGUF), set up through OPENAI_URI_BASE as a user does today:

    • categorize, merchant detection and bill setup answer in the schema (10–40 s on CPU);
    • ProcessPdfJob reads BAC 13/13 through the text layer, and the checks pass;
    • the scan is refused with the "no model here can read scanned pages" message.
  • OpenClaw in the dev pod (2026.10.8), with Sure's MCP server and Sure booted inside a test (Puma in the test environment, never rails server):

    • Probe: openclaw mcp probe lists Sure's 35 tools.
    • On Gemini: the agent answers accounts and net worth through get_accounts. Asked to import a processed statement, it calls get_accounts then import_bank_statement, and 2e's reading gives 13 rows with the checks passed. Document search takes the metadata fallback.
    • On Ollama's gpt-oss-20b: the same accounts answer, in 274 s on CPU.
    • Sure's external assistant mode: a Sure chat goes to OpenClaw, which calls Sure's get_balance_sheet over MCP, and the reply is saved to the chat.
  • pgvector search, end to end:

    • Indexing: IndexAccountStatementJob indexes a vault statement through Ai::Embeddings. It was tested on Gemini's gemini-embedding-001 at its native 3,072 dimensions and on venus's granite at 384, with the test database's chunk column resized for each.
    • Search: search_family_files finds the statement.
    • Through the agent: OpenClaw answers "did I pay for petrol in February 2019?" correctly (£24.50 and £40.00) from one search_family_files call over MCP.
    • Embedding dimensions: a model asked for 1,024 that returns 3,072 fails clearly (InvalidOutput, "expected 1024 dimensions, got 3072") instead of storing wrong-size vectors. Sure doesn't send dimensions, as today, since some models refuse it.
    • The threshold: relevant text scored 0.63 on Gemini and 0.85 on granite, and unrelated text 0.47 and 0.77, so 0.3 filters nothing on pgvector.
  • Anthropic, with a key that has no credit. Anthropic checks credit before it validates a request, even on count_tokens, so these tell nothing about decision 7 or PDF document blocks.

    • Probes: the model-list probe passes. The chat probe is NoCredit.
    • Generating: NoCredit after one request, though the endpoint allows two retries. The usage row records status failed with the error. The same happens on Haiku 4.5 and 5.5, Sonnet 5.5, Opus 5.5 and Fable 5.1.
    • A wrong key is Unauthorized.
    • Failover: on a [Claude, Gemini] route, categorize fails over to Gemini and answers.
    • PDF import with only ANTHROPIC_API_KEY routes to claude-sonnet-4-6 with documents. It fails with Anthropic's own message, after the fix below.
  • Cohere, with a trial key:

    • OCR through RubyLLM.ocr (parse-v5.0, one page per request): ocr_live_test is recorded. The test's default model was cohere-parse-v1, which Cohere doesn't have.
    • The scan through Auto: Cohere OCR, then command-a-03-2025 on Cohere's OpenAI-compatible API, read 21/21 rows, and the checks passed. It's the first OCR read of the scan that passed.
    • BAC read as OCR: 13/13 exact, and the checks passed.
    • Generations on command-a: categorize, merchant detection and bill setup answer in the schema.
    • Strict schemas: Cohere refuses nullable objects (statement_period) and integer minimum (bill setup's day_of_month). JSON mode auto then retries once in none (2c's #3605 rule), so the answer is unenforced. BAC's text layer came back as non-JSON after 292 s, InvalidOutput, and was reported, not imported.
    • pgvector on embed-v4.0 (1,536 dimensions): relevant text scored 0.52 and 0.38, and unrelated text had no hits, so 0.3 filters here, unlike on Gemini and granite.
  • OpenAI, with a key that has no credit:

    • Generation and embeddings: chat completions, the Responses API and embeddings are NoCredit after one request. The model-list probe passes.

    • PDF import on OPENAI_ACCESS_TOKEN alone: routes to gpt-4.1 (Responses API, PDF sent as a file). It fails with OpenAI's message.

    • The OpenAI vector store fixes, live (Files and vector stores work without credit):

      • an upload is processing, then IndexStatusJob sets it ready;
      • the scan becomes unreadable;
      • files keep their own names;
      • search returns the statement at 0.908, and the unrelated query has no hits;
      • removing a document deletes its file;
      • deleting the store deletes the store and its files.

      Nothing was left in the account.

  • Proxy, live, through a logging forward proxy, with HTTPS_PROXY only, HTTP_PROXY only, a NO_PROXY CIDR and a NO_PROXY host:

    • These follow Sure's resolver: RubyLLM's compatible client (Gemini, venus, Ollama), Anthropic and OpenAI (Responses) generation, and Http.openai_client (ruby-openai). Loopback is never proxied, and plain HTTP to venus is proxied.
    • Exception, now fixed: Anthropic's model-list probe used the anthropic gem, which ignores HTTPS_PROXY. Fixed on 2a (#4773) and merged forward; re-run live, it uses the proxy under every setting.
  • Tracing, live against a self-hosted Langfuse v4:

    • Content mode: each call is a span plus a generation under the job's session, with the model, usage, input and output. The no-credit call is an ERROR. Embeddings show counts only.
    • Metadata mode: OTLP spans to Langfuse under the session, with model and usage, and empty input and output.
    • Flush, now fixed: without an explicit flush at exit the spans never arrived. Fixed on 2a (#4773); re-run live, they arrive.
  • Reasoning effort, live in strict mode:

    • Ollama's gpt-oss: low and high are honoured (37 and 732 tokens). none is accepted and ignored.
    • OpenRouter (Nemotron VL, free): none sends reasoning: {effort: "none"} and turns reasoning off (0 reasoning tokens).
    • Gemini: low and high work. none is a 400 that names neither the effort nor the JSON mode. It wasn't retried, so the call failed. Fixed on 2c (#4775); re-run live, it succeeds on the retry without the effort.
  • A real overflow: Ollama with a 4,096-token window refused 120 transactions (5,244 tokens) as ContextTooLong. Ai::Generation split them 60 + 60 on the same route, and all 120 were answered once. A refused port is Unreachable, and a 2 s timeout is Timeout.

  • Ollama embeddings: granite on Ollama gives the same vectors as venus (cosine 1.0). Ai::Embeddings works on an Ollama route, and a dimension mismatch is InvalidOutput.

  • The migrations, on a copy of main (a throwaway database: main's schema, the full demo data, plus a row for each case each migration rewrites):

    • All six run in under 0.05 s each, and the app reads the result through its models.
    • Family documents: a valid id links to its account, in either case; an unknown id or junk stays empty.
    • Usage rows: a row with an error becomes failed.
    • Prompt overrides: the categorizer keys collapse to OpenAI's text and log Anthropic's as dropped; the merchant key moves.
    • The only family's Jev choice becomes the instance setting.
    • Comparisons move with category ids, keeping names the family doesn't have and the probabilities.
    • The import columns and their index are added.
    • Rolling back restores each table. The only losses are the documented ones: the dropped override text, and the Jev setting staying behind.
    • Migrating up again gives the same result as the first time.
    • Two notes:
      • #3422's migration (20260905120000) is dated before main's latest, so db:rollback STEP=6 reverts one of main's migrations instead. db:migrate is unaffected.
      • The dumped schema matched schema.rb apart from the imports columns' order, now fixed (2e0026f74), and main's newer sync_schedules table, which arrives with the next merge from main.
  • llama.cpp's thinking switch, on Qwen3.6-35B-A3B in the dev pod (the ghcr.io/ggml-org/llama.cpp:server build of 2026-11-06):

    • Preset llama_cpp with effort none: sends chat_template_kwargs: {enable_thinking: false}. No thinking, 15 tokens, 1.5 s, against 995 tokens and 90 s with thinking on.
    • This build also honours a plain reasoning_effort: "none", which the spike's build ignored, so the preset's mapping is now a safeguard for older servers.
    • low and high aren't distinct on Qwen3.6.
    • On venus's Gemma 4 (26B-A4B with an MTP draft, served with LLAMA_ARG_REASONING=off): every effort is accepted through Caddy with no error, and the server's setting wins (no thinking). Strict JSON works.
  • PDF reading on venus's Gemma 4 (its 16k window): BAC 13/13 exact through the text layer, Auto included, and the checks passed. read identifies the statement. The scan is refused as having no text layer: Gemma here is text-only, with no vision projector.

  • OpenJev (venus llama.cpp, openjev-27b) isn't a System One server: /v1/systemone answers 501 "This model is not a decision model", and Sure reports the failure. Using it needs a lettered-options adapter, which isn't in this PR.

  • Found by live testing, fixed here:

    • text chunking built a regex that Ruby refuses above about a 57k-token window (62671e238);
    • the deprecated ENV's 2,048-token baseline read a scan one page per request (3ebdc4931);
    • the pdftoppm hang test raced an unreaped child under a parallel run (235399afe).
    • an outage on a later way of reading (Ollama's 500 for images) dropped the extraction already in hand; it's now kept and flagged (7951fc2e9);
    • llama.cpp's and Ollama's 500 "image input is not supported" counted as an outage; it's now Refused (7951fc2e9, and c94c9fc85 for RubyLLM's error class);
    • inline page images in cassettes tripped Pipelock's secret scan; AI cassettes now record <FILE> in their place (9973b4bb7).
    • a failed PDF import showed the error's class ("Processing failed: NoCredit") where main shows the provider's message; it shows the message again (d69281531).
    • on 2e itself, Http.anthropic_client lost its last caller and is removed (be385fa05).
  • Not run yet:

    • Funded OpenAI and Anthropic keys: the PDF-file way and 2c's decision-7 check. Both keys available have no credit.
    • LM Studio: not in the dev pod.
    • Mistral OCR: untested live, by decision 2.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ

Summary by CodeRabbit

  • New Features
    • Choose PDF reading as text, images, OCR, or automatically during import; eligible imports can be reread using another available method.
    • Review extraction warnings and failed checks before publishing statement transactions.
    • PDF reading can try alternate methods and indicate when scanned pages could not be read.
    • Document search and statement indexing respect AI availability and document access.
    • OCR now supports additional services, with improved handling of PDF attachments.
  • Bug Fixes
    • Improved guidance when a suitable PDF-reading method is unavailable.
    • Added indexing status updates and clearer handling of indexing failures.
    • Improved search results by filtering weaker matches and widening searches when needed.
    • Better handling of duplicate drafts and conflicting publish or reread attempts.
    • Prevented publishing transactions with missing dates.