AI plumbing 2e: documents
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.
pdftoppmruns 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 withoutdocuments, 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.
.aievents record each file's name and size, never its bytes.
- A transport refuses images to a model without
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.
- A local OCR model is read through chat, with its own prompt folder (
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::Batchand split on overflow. Rows repeated at a batch boundary are dropped (#846). -
Pdf::PageImageskeeps #3275'spdftoppmand 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
embedand queries undersearch_documents; - it uses the route's first embedding model, with no failover;
- the vector size comes from the embed route's model.
- documents are indexed under
- 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::IndexStatusJobsets it ready, unreadable for an empty index, or error; - removing a document, or deleting the family, deletes the files from OpenAI.
- its client comes from
- Both stores drop matches scoring under 0.3.
#3422 on the plumbing (§5.5, §14).
IndexAccountStatementJobruns on embed's lane and is queued only whenembedis available to the uploader and the uploader's AI switch is on.search_family_filesstays listed. Withoutsearch_documentsit 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::JsonModeandAnthropic::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 askAssistant.builtin_provideruntil PR 6.Provider::Openai::UsageCoststays, because chat uses it.- 2,939 lines deleted in that commit.
Decisions (calls by @josh-sanders during development of PR #4440)
- 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.
- 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.
- Files that earlier removals left in OpenAI's Files API get a release note, not a clean-up task.
OPENAI_SUPPORTS_PDF_PROCESSING=falsekeeps turning PDF import off, as today. An admin sets it per model from PR 7.- 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.
- 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). - 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'sautofallback stays as it is.
Reviewer guide (reading order)
app/models/ai/pdf_reading.rbapp/models/ai/generations/extract_bank_statement.rb, thenread_pdf.rbandpdf_reading/pages.rbapp/models/pdf/page_images.rbapp/models/ai/transport/base.rbandcompatible.rb: attachments,embed,ocrapp/models/vector_store/openai.rbandapp/jobs/vector_store/index_status_job.rbapp/models/pdf_import.rb,app/jobs/process_pdf_job.rband the views- The merge-resolution commit
825731239and21d7e5edc, 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 toimports. - 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_WINDOWset, 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=falsestill 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 testgives 14,972 runs and 13 failures, all in 2d's baseline (#4765) and also failing onmain: 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=1on 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-diffreturns[]. -
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-inpdftoppmscripts),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.
- in
-
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_teston qwen3.6 was recorded on 2c (#4775) and merged forward.
-
Live PDF reading on the two sample statements (a throwaway test, not committed):
Statement Model Way Rows Checks BAC, text layer qwen3.6 (venus, local) Text, chosen by Auto 13/13 exact pass BAC gemini-3.5-flash-lite(compatible API)Text, chosen by Auto; Images 13/13 exact pass Impact, scanned qwen3.6 (no vision) — — Unavailable(no_text_layer), nothing sentImpact gemini-3.5-flash-liteImages, chosen by Auto 21/21 pass Impact OpenRouter nemotron-3.5-super-vl:free,dots-3-note-preview:freeImages 22: adds the row the two pages disagree on reconcilesfails → flaggedreadsays what each statement is: a bank statement, with its institution or account holder. -
ProcessPdfJobend 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_testrecorded: 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_BASEas a user does today:- categorize, merchant detection and bill setup answer in the schema (10–40 s on CPU);
ProcessPdfJobreads 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 probelists Sure's 35 tools. - On Gemini: the agent answers accounts and net worth through
get_accounts. Asked to import a processed statement, it callsget_accountsthenimport_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_sheetover MCP, and the reply is saved to the chat.
- Probe:
-
pgvector search, end to end:
- Indexing:
IndexAccountStatementJobindexes a vault statement throughAi::Embeddings. It was tested on Gemini'sgemini-embedding-001at 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_filesfinds 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_filescall 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 senddimensions, 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.
- Indexing:
-
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:
NoCreditafter one request, though the endpoint allows two retries. The usage row records statusfailedwith 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_KEYroutes toclaude-sonnet-4-6withdocuments. It fails with Anthropic's own message, after the fix below.
- Probes: the model-list probe passes. The chat probe is
-
Cohere, with a trial key:
- OCR through
RubyLLM.ocr(parse-v5.0, one page per request):ocr_live_testis recorded. The test's default model wascohere-parse-v1, which Cohere doesn't have. - The scan through Auto: Cohere OCR, then
command-a-03-2025on 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 integerminimum(bill setup'sday_of_month). JSON modeautothen retries once innone(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.
- OCR through
-
OpenAI, with a key that has no credit:
-
Generation and embeddings: chat completions, the Responses API and embeddings are
NoCreditafter one request. The model-list probe passes. -
PDF import on
OPENAI_ACCESS_TOKENalone: routes togpt-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
IndexStatusJobsets 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.
- an upload is processing, then
-
-
Proxy, live, through a logging forward proxy, with
HTTPS_PROXYonly,HTTP_PROXYonly, aNO_PROXYCIDR and aNO_PROXYhost:- 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
anthropicgem, which ignoresHTTPS_PROXY. Fixed on 2a (#4773) and merged forward; re-run live, it uses the proxy under every setting.
- These follow Sure's resolver: RubyLLM's compatible client (Gemini, venus, Ollama), Anthropic and OpenAI (Responses) generation, and
-
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.
- 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
-
Reasoning effort, live in strict mode:
- Ollama's gpt-oss:
lowandhighare honoured (37 and 732 tokens).noneis accepted and ignored. - OpenRouter (Nemotron VL, free):
nonesendsreasoning: {effort: "none"}and turns reasoning off (0 reasoning tokens). - Gemini:
lowandhighwork.noneis 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.
- Ollama's gpt-oss:
-
A real overflow: Ollama with a 4,096-token window refused 120 transactions (5,244 tokens) as
ContextTooLong.Ai::Generationsplit them 60 + 60 on the same route, and all 120 were answered once. A refused port isUnreachable, and a 2 s timeout isTimeout. -
Ollama embeddings: granite on Ollama gives the same vectors as venus (cosine 1.0).
Ai::Embeddingsworks on an Ollama route, and a dimension mismatch isInvalidOutput. -
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 beforemain's latest, sodb:rollback STEP=6reverts one ofmain's migrations instead.db:migrateis unaffected. - The dumped schema matched
schema.rbapart from theimportscolumns' order, now fixed (2e0026f74), andmain's newersync_schedulestable, which arrives with the next merge frommain.
- #3422's migration (
-
llama.cpp's thinking switch, on Qwen3.6-35B-A3B in the dev pod (the
ghcr.io/ggml-org/llama.cpp:serverbuild of 2026-11-06):- Preset
llama_cppwith effortnone: sendschat_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. lowandhigharen'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.
- Preset
-
PDF reading on venus's Gemma 4 (its 16k window): BAC 13/13 exact through the text layer, Auto included, and the checks passed.
readidentifies 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/systemoneanswers 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
pdftoppmhang 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, andc94c9fc85for 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
mainshows the provider's message; it shows the message again (d69281531). - on 2e itself,
Http.anthropic_clientlost its last caller and is removed (be385fa05).
- text chunking built a regex that Ruby refuses above about a 57k-token window (
-
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.