The Ollama OCR timeout is set on a vision client nothing calls

paperless-gpt titles, tags and OCRs paperless-ngx documents with five LLM providers, and already caps retries so a document that keeps erroring stops costing money.
≈ 34,000 tokens per 1,000 calls, sent and generated by Ollama OCR requests that run with no timeout estimate
Audited with leanprompt 0.1.0-dev.15
Estimates, not measurements. Every figure on this page is an estimate from reading the code, not a measurement of the app in use.
- Repository
- icereed/paperless-gpt
- Commit audited
1d07ced- leanprompt version
- 0.1.0-dev.15
- Audit date
- Status
- The maintainers have been told about this audit; no response yet.
- Maintainers
- the issue
- How it ran
- Unattended audit: nobody was asked during the run, so priority, volume and prices were left open; the questions for the owner are listed at the end.
A Go and React service that titles, tags and OCRs paperless-ngx documents with an LLM. OLLAMA_TIMEOUT_SECONDS is set on a vision client the app never uses, so Ollama OCR still runs with no timeout, and the tag and correspondent lists are sent in a different order for every document. Figures are estimates from the code.
leanprompt read the code at commit 1d07ced and found 4 places where its LLM calls could use fewer tokens, 4 the project already knows about, plus 6 other problems, not scored. Static score: 87 of 100 (an estimate from the findings, leaving out what the project already knows about). The code may have changed since.
Findings
-
LP-PC-04Fixed tool order and JSON key orderapp_llm.go:721· severity medium · saves prefill · size is assumedWhat happens. The tag list in the tag prompt is built by ranging over a Go map (app_llm.go:721), so its order is random and differs for every document. The tag prompt puts that list right after the fixed instructions and before the document (tag_prompt.tmpl:13-15), so the part every document shares is never the same bytes twice.
The change. Sort availableTagNames (slices.Sort) at the end of the tag block in prepareSuggestionGenerationContext.
Why it helps. Automatic prefix caching (OpenAI and OpenAI-compatible hosts from 1,024 tokens, Gemini implicit caching, vLLM, and Ollama's reuse of the previous request's prompt) can only reuse an identical start. With a random order, every tag call prefills the whole tag list again.
Estimate about 150k prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. tag calls are 125 of 1,000 calls; in half of installs the instructions plus tag list exceed the 1,024-token minimum (about 300 tags) and about 1,200 tokens of it could be reused; documents are processed one after another, well inside the cache lifetime
How big. how many tokens the tag list takes in a real install (number of tags in paperless-ngx), and cached_tokens on two consecutive tag calls before and after sorting
-
LP-PC-04Fixed tool order and JSON key orderapp_llm.go:735· severity medium · saves prefill · size is assumedWhat happens. The correspondent list is also built from a Go map (app_llm.go:735). With CORRESPONDENT_PROMPT_LIMIT at its default 0 (main.go:832) filterCorrespondentsForPrompt returns it unsorted, so the list after the 560-token instructions (correspondent_prompt.tmpl:33-35) is in a new order for every document.
The change. Sort availableCorrespondentNames in prepareSuggestionGenerationContext (the limited path already sorts by score, then name).
Why it helps. Same as the tag list: the stable start of every correspondent prompt is reshuffled, so no prefix cache can reuse it.
Estimate about 82k prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. correspondent calls are 125 of 1,000 calls; in 60% of installs the instructions plus list exceed 1,024 tokens and about 1,100 tokens could be reused
How big. number of correspondents in a real install and CORRESPONDENT_PROMPT_LIMIT; cached_tokens on two consecutive correspondent calls
-
LP-GE-04Stream long outputs; timeouts that match generation timeocr/llm_provider.go:443· severity medium · saves prefill and generation · how often is assumedWhat happens. Vision OCR through Ollama runs on a client with no request timeout. OLLAMA_TIMEOUT_SECONDS (PR #1070) is only passed to createVisionLLM (main.go:1461), whose result App.VisionLLM is never read; the OCR provider is built separately in createOllamaClient, which passes no HTTP client when OLLAMA_HEADERS is unset (and a header client without a timeout when it is set). README.md:707 and env_registry.go:99 say the timeout covers OCR.
The change. In createOllamaClient, give the client the same timeout: build it with the OLLAMA_TIMEOUT_SECONDS value (default 300 s, 0 disables) when OLLAMA_HEADERS is unset, and set Timeout on the header client when it is set. Delete createVisionLLM and App.VisionLLM, which nothing uses.
Why it helps. A vision model that loops on a page (#875) keeps generating until someone restarts the container, and because OCR runs first in the single background loop (background.go:76-84), auto-tagging stops too.
Estimate about 30k output tokens per 1,000 calls generated by OCR requests that never return (estimate)
Assumptions. call mix of 3 OCR pages and 5 suggestion calls per document; 0.5% of Ollama OCR pages loop and generate about 16k tokens before a restart; local Ollama only, so the cost is GPU time and a stalled queue, not money
How often. how many Ollama vision OCR requests run longer than OLLAMA_TIMEOUT_SECONDS (300 s) or never return, from the Ollama server log or the paperless-gpt log stopping mid-document
-
LP-GE-05Retry only retryable errors; never retry a truncation unchangedllm_client.go:181· severity high · saves prefill and generation · how often is assumedWhat happens. RateLimitedLLM.GenerateContent retries every error three times with backoff, including errors that cannot succeed on a resend: a 400 for a prompt over the context window (TOKEN_LIMIT is unset by default), a 400 for an unsupported parameter, a 401 or a 404 for a retired model. AUTO_TAG_MAX_RETRIES then re-runs the whole document on the next poll, so a permanent error is sent up to 12 times, each time after repeating the calls that had already succeeded.
The change. Retry only 429, 5xx and network errors (the OCR path at ocr/llm_provider.go:206 already filters this way); return other errors at once.
Why it helps. Each resend of a permanent error pays the full prompt again, and the earlier successful calls of the document are bought again on every poll.
Estimate about 12k prompt tokens per 1,000 calls (estimate)
Assumptions. 0.5% of documents hit a permanent error on the first call; 3 polls x 4 attempts of about 1,600 prompt tokens
How often. how many suggestion calls fail with a 4xx other than 429 (400 context length or invalid parameter, 401, 404 model not found), from the log line 'all retry attempts failed'
Already known to the project
The project’s own issues, pull requests or docs already cover these, so they are not counted above and are left out of the static score.
-
LP-GE-02Batch independent questions about one contextapp_llm.go:795· severity high · saves prefill and generationWhat happens. With the defaults, every document is sent to the model five times (title, tags, correspondent, document type, created date; custom fields make six), each time with the whole document and with TOKEN_LIMIT unset, untruncated.
The change. Ask for the fields together in one structured call (the open PR #1072), or at least start every template with the document so the five calls share a prefix.
Why it helps. The document text is the largest part of each prompt and is prefilled five times per document.
In progress. open PR: opt-in LLM_METADATA_GROUPING generates the title first, then tags, correspondent, document type and date in one call (5 to 2 calls on their benchmark). https://github.com/icereed/paperless-gpt/pull/1072
Estimate about 487k prompt tokens per 1,000 calls (estimate)
Assumptions. 125 documents per 1,000 calls, about 1,300 tokens of content each, three of the five copies saved by grouping
-
LP-GE-05Retry only retryable errors; never retry a truncation unchangedocr/llm_provider.go:229· severity high · saves prefill and generation · how often is assumedWhat happens. A page answer that stopped at the output limit is stored as the page text; the stop reason is only logged when the text is empty. On Anthropic with VISION_LLM_MAX_TOKENS unset, langchaingo sends max_tokens 2048, which a dense page can exceed.
The change. Read StopReason and treat length/max_tokens as a truncation (#1251's proposal).
Why it helps. The cut-off page has to be OCRed again once someone notices, and until then the document's text and every suggestion made from it are incomplete.
Already reported. open: LLM OCR stores truncated or empty responses as complete text; proposes OCR_FAIL_ON=truncated,empty. https://github.com/icereed/paperless-gpt/issues/1251
Estimate about 15k output tokens per 1,000 calls (estimate)
Assumptions. 2% of OCR pages stop at the limit
How often. how often OCR answers stop at the limit (Anthropic stop_reason max_tokens, OpenAI finish_reason length, Ollama done_reason length)
-
LP-GE-04Stream long outputs; timeouts that match generation timeocr/llm_provider.go:321· severity medium · saves prefill and generationWhat happens. The OpenAI-compatible client (OpenAIHTTPClient, used for suggestions and OCR), and the Anthropic and Mistral clients, are created without a timeout, and the background loop's context has no deadline, so one request that never returns stops all processing.
The change. Give every provider client a timeout (one LLM_REQUEST_TIMEOUT for hosted providers, default a few minutes), or wrap each GenerateContent call in context.WithTimeout.
Why it helps. A stalled hosted request blocks the single background loop until the container restarts; the requests behind it are not sent at all.
Already reported. open: LLM request hangs indefinitely when the Anthropic API does not respond; asks for LLM_REQUEST_TIMEOUT. PR #972 (open) adds a timeout only to the /api/generate-suggestions HTTP handler, not to the background loop. https://github.com/icereed/paperless-gpt/issues/937
Estimate no tokens of its own; a stalled queue
Assumptions. known upstream as #937
-
LP-PC-10Stable image and attachment placementocr/llm_provider.go:159· severity low · saves prefill · costs no tokens todayWhat happens. Each OCR request puts the page image before the fixed OCR instructions, so nothing the pages share comes first.
The change. Put the instructions first (PR #1204).
Why it helps. The fixed instructions are about 120 tokens, below every hosted provider's minimum, so this matters only for local engines.
In progress. open PR: move the OCR prompt before the image data. https://github.com/icereed/paperless-gpt/pull/1204
Estimate close to zero on hosted providers
Assumptions. default OCR prompt
Other problems the audit found
Problems read in the code that cost no tokens of their own, such as a cost meter or an error path. Not scored.
-
OCR retries miss Gemini and Ollama errors, so one 429 fails the whole document
What happens. The OCR retry treats an error as transient only if its text contains 'status code: 429' or 'status code: 5'. That is langchaingo's OpenAI and Anthropic wording. Gemini's error reads 'Error 429, Message: ...' (google.golang.org/genai APIError.Error) and Ollama's reads '503 Service Unavailable: ...' (langchaingo ollamaclient StatusError), so rate limits and overload on those providers are never retried: the page fails, the document fails, and OCR_MAX_RETRIES later OCRs every page again.
The change. Classify by status code instead of text: check errors.As for genai.APIError (Code) and the Ollama status error, or extend the match to both formats.
To check. A retry test with errors.New("Error 429, Message: quota, Status: RESOURCE_EXHAUSTED, Details: []") retries like the existing 'status code: 429' cases in ocr/llm_provider_retry_test.go.
-
VISION_LLM_MAX_TOKENS and VISION_LLM_TEMPERATURE have no effect with googleai
ocr/google_ai_client.go:149·LP-GE-17Send the output cap the owner set, on every path · severity mediumWhat happens. GoogleAIProvider.GenerateContent ignores its opts: the genai config carries only the thinking budget, so the output limit and temperature set for OCR are never sent to Gemini, and the finish reason is not read.
The change. Apply llms.CallOptions to genai.GenerateContentConfig (MaxOutputTokens, Temperature) and return the candidate's FinishReason as StopReason.
To check. A test with a fake genai transport sees maxOutputTokens in the request body when VISION_LLM_MAX_TOKENS is set.
-
OcrLimitHit compares prompt plus output tokens with the output limit
What happens. limitHit uses GenerationInfo TotalTokens, which langchaingo fills with prompt plus completion tokens for OpenAI and Ollama. The page image alone is often 800 to 1,500 tokens, so a page can be flagged as cut off when its output was short, while Anthropic (no TotalTokens) falls back to a tokenizer estimate.
The change. Use the stop reason (length / max_tokens), or CompletionTokens / OutputTokens, instead of TotalTokens.
Already reported. #1251 notes OcrLimitHit is only computed when VISION_LLM_MAX_TOKENS is set and is not acted on; the TotalTokens comparison is not mentioned. https://github.com/icereed/paperless-gpt/issues/1251
To check. For an OpenAI page with prompt 1,200 and completion 300 tokens and VISION_LLM_MAX_TOKENS=1024, OcrLimitHit is false.
-
LLM_MAX_RETRIES=0 still retries three times
What happens. NewRateLimitedLLM replaces 0 or a negative MaxRetries with 3, so the documented setting cannot turn retries off for suggestions (for OCR, VISION_LLM_MAX_RETRIES=0 does disable them, per the README).
The change. Treat 0 as no retries and keep 3 only as the default when the variable is unset (getRateLimitConfig already defaults to 3).
To check. With LLM_MAX_RETRIES=0 and a failing mock, one request is sent.
-
README examples name a model retired on 2026-11-30 and snapshots shut down on 2027-01-14
README.md:253·LP-GE-13Default to a model the provider still serves · severity lowWhat happens. The README suggests claude-sonnet-4-5 (lines 253, 263, 674; docs/openai_compatible_providers.md:46), which Anthropic retires on 2026-11-30 (model deprecations page, checked 2026-11-27), and gpt-4o (lines 225, 263, 354, 392), whose snapshots gpt-4o-2024-08-06 and -11-20 shut down on 2027-01-14 (OpenAI deprecations page, checked 2026-11-27). LLM_MODEL has no code default, so only new setups copied from the README are affected.
The change. Replace the examples with current models (claude-sonnet-5-5; an active OpenAI model), keeping the note that any vision model works.
To check. A new install from the README example starts and its first suggestion call returns 200.
-
Ad-hoc analysis returns a cut-off answer as complete
app_http_handlers.go:1171·LP-GE-12Read the finish reason before using an answer · severity mediumWhat happens. analyzeDocumentsHandler calls app.LLM.Call, which returns only the text; the stop reason is lost. On Anthropic, langchaingo sends max_tokens 2048 when none is set, so a table over many documents can stop mid-row and is shown as the result.
The change. Call GenerateContent, check Choices' StopReason, and tell the user when the answer was cut off (or pass a larger max tokens).
To check. With a mock returning stop_reason max_tokens, the response carries a truncation flag or error.
The maintainers’ response
No response from the maintainers yet.
How this was made
The llm-call-audit skill read the code and wrote findings.json; nothing was run against the project’s providers. The full audit page is what leanprompt report --html writes from the same findings.
Corrections and takedown: email info@podwarden.com or open an issue.