AI plumbing 2f: ruby_llm 2.2.3, Jev via OpenRouter, review fixes

Merged
JO
8d ago
+3605-577

Part 2f of the AI plumbing series. 2a (#4773), 2b (#4774), 2c (#4775) and 2d (#4765) are merged into refactor/ai-plumbing. This PR stacks on 2e (#4771): merge 2e first, then this one. Until 2e merges, this diff includes its changes.

Six things that didn't belong in 2e:

1. ruby_llm 2.1.1 → 2.2.3

The adaptation this gem's changes asked of the transports (whats-new-in-2-2):

  • TLS rides RubyLLM's public config.ssl; Sure's Faraday adapter is back to proxy-forcing only.
  • RubyLLM.with_owner (was with_usage_owner); Ai::CallContext.within deleted — fiber storage carries the owner and the call's identity into Jev's pool threads, so UsageSubscriber reads payload[:owner]/[:workflow_metadata] plainly.
  • Embedding task_type plumbing deleted (2.1.1 dropped it; 2.2 refuses it), EmbedRequest#task_type gone with it, and the vectors count check is 2.2's own.
  • parse_json splits nothing: Chat Completions content arrives with any think block already split out (config.split_think_tags), so Sure's manual strip_thinking is gone — one parsing rule, the gem's. An unterminated think block now yields no answer (→ InvalidOutput), pinned by a test.
  • Responses-API metadata_tracing passes content: false explicitly (2.2's enable(content:) defaults off; Sure states it).
  • 2.2.0 → 2.2.2 (2.2.1, 2.2.2): a Jev judgment that comes back billed but malformed now keeps its tokens and cost on its failed llm_usages row (crmne/ruby_llm#1614, fixed upstream in #1658); ai_transport_judge_test pins it. The other fixes are in parts Sure doesn't use yet (persisted chat, tools, app/skills, Gemini batches); PR 6's chat work picks them up.
  • 2.2.3 ships our upstream fix crmne/ruby_llm#1680: config.log_bodies, streaming through the context's logger, and configured API keys written as [FILTERED] in everything RubyLLM and Faraday log. Sure sets log_bodies = false, so request and response bodies never reach the log, even at debug, and the RubyLlmLogger wrapper that swallowed debug is gone. At debug, RubyLLM still logs the request line and an error's message, with the key filtered. The Gemfile requires ~> 2.2, >= 2.2.3.

2. Enable Jev through OpenRouter's Decisions gateway

ruby_llm 2.2 ships OpenRouter::Judgments: OpenRouter's Decisions gateway speaks System One with the judgments path at …/api/alpha/decisions — the protocol the docs long promised. Jev through OpenRouter works now, not "with a later release":

JEV_API_KEY=or-...                                # your OpenRouter key, not OPENROUTER_API_KEY
JEV_ENDPOINT=https://openrouter.ai/api/alpha/decisions
CATEGORIZATION_PROVIDER=jev
  • Ai::LegacyEnvConfig::Jev accepts any host whose path ends in /alpha/decisions (regional hosts included), with the :jev_openrouter preset; the api_base derives as <prefix>/v1, so the provider's relative judgments path lands back on the decisions URL. Everything else is still refused, the same way, to the settings form and to the eval runner.
  • Ai::Transport::Jev posts through RubyLLM's openrouter provider for the :jev_openrouter preset (openrouter_api_base, app name/url), the typesafe provider otherwise; the judge call passes provider: through. Cloud Jev gets calibrated_confidence as before.
  • The decisions gateway requires non-null criteria: Sure now always sends a criterion per choice — a subcategory of its parent, or the category's own name. Without this, parallel/decisions-fast:free refuses the call outright ("missing or null instructions or criteria").
  • fr/nl/zh-CN also get the translations 2e deleted instead of reworded — restored with the OpenRouter-enabled copy, update.unsupported_jev_endpoint included.
  • Locales en/fr/nl/zh-CN reword model_help and unsupported_jev_endpoint to the two supported dialects.

3. Editor-pass fixes over 2a–2e

  • Ai::Generation#call_batched computed the leftover list with value-equality subtraction (remaining - slice) — value-equal twins (identical bank-statement Units, records with identical given values) were silently dropped instead of the route's positional prefix. Fixed positionally; regression test included.
  • Ai::Shadow had the same subtraction for deciding what the shadow may not be sent; now an object-identity reject, with a test that would fail against it. Fewer units of give-away data in the shadow job's arguments as well.
  • Views: the shadow-results summary ran its batch lookup and category-name resolution in the template; both moved into Settings::HostingsHelper/Ai::Comparison.with_display_names. The two Jev partition views read effective config through the same helper instead of Ai::* class calls.
  • Api::V1::RuleRuns::ProgressesController got its missing 403 Minitest; four missing transport tests (Responses-API 400-on-effort retry, Anthropic max_tokens cut, unclosed fence, unclosed think) added.
  • Audit-driven fixes: a configurable-base URL that contains v1 is now matched in the path, not the host (a proxy v1-proxy.lan:8080 gets /v1 appended); a malformed proxy OPENAI_URI_BASE no longer crashes AI every call; Ai::Comparison no longer 500s on garbage legacy primary_value values; the ComparisonSubscriber now drops non-uuid comparison subjects with a log instead of writing unreachable rows; an embedding refuse is kept when text extraction produced nothing; the vault no longer lists error/unreadable documents in search fallback ordering.

4. once-per-process DebugLogEntry for an unreachable Jev endpoint

The wrong JEV_ENDPOINT (a gateway that doesn't speak the System One dialect, or a path typo) used to surface only on the hostings page or as a Rails log line. The config builder now also writes one error DebugLogEntry per (endpoint, reason) signature per process, with the endpoint redacted of credentials. Everything else in RubyLLM/the judgement path already wrote DebugLogEntry; this closes the loop.

5. The AI features end to end, on every release tag

Unit tests stub the model, the evals replay recorded answers, and the live tests build one transport call by hand. None ran the app's own entry points against a real model. test/e2e/ai/ does, configured through the AI ENV a self-hoster sets (OPENAI_URI_BASE, OPENAI_MODEL, OPENAI_EXTRA_HEADERS, JEV_*, CATEGORIZATION_PROVIDER), on free models: Kilo's kilo-auto/free and OpenCode Zen's jev-1.13-free, which answer without a key (KILO_API_KEY and KILO_ORG_ID, sent as X-KiloCode-OrganizationId, are used when set as repository secrets, for rate limits), and for documents Cohere's embed-v5.0-fast on a free trial key (COHERE_LIVE_API_KEY; EMBEDDING_URI_BASE at Cohere's OpenAI-compatible URL, 2048 dimensions, pgvector).

flowchart LR
  Tag["push v* tag"] --> W["ai-e2e.yml"]
  W --> E["e2e: AI_E2E=1 test/e2e/ai"]
  W --> L["live: AI_LIVE=1, free legs only"]
  E --> C["AI ENV → Ai::LegacyEnvConfig"]
  C --> J["GenerationJob · ShadowJob · ProcessPdfJob<br/>AiSetupSuggester · chat in the browser"]
  J --> K[("Kilo kilo-auto/free")]
  J --> Z[("Zen jev-1.13-free")]
  J --> CO[("Cohere embed-v5.0-fast<br/>→ pgvector")]
TestDrivesAsserts
categorize: Kilo, JevAi::GenerationJob(:categorize)categorized with the family's own categories; Jev leg routed to the judge
categorize: shadowKilo primary, Jev shadow, rate 1one Ai::Comparison per transaction; each keeps the primary's answer
detect merchantsAi::GenerationJob(:detect_merchants)merchants assigned
bill setupAiSetupSuggester#suggest_from_entriesa proposal, a preset frequency
PDF importProcessPdfJob on bac_ocr.pdf, read as textrows extracted, checks recorded
documentsFamily#upload_document ×2 → search_family_filesboth indexed; the right one ranked first
chat (system test)the browser asks; the job answersa complete answer, a tool call, rendered

Assertions check shape, not accuracy (that's the evals' job), plus succeeded llm_usages rows and no error DebugLogEntry. They skip unless AI_E2E=1, so bin/rails test stays offline. ai-e2e.yml runs them on v* tags (and workflow_dispatch), with the free legs of test/models/ai/live (a new kilo/kilo-auto/free route, Jev on Zen, Cohere's OCR); the paid routes stay with the ai-live label. A failure turns the run red without blocking the release, like llm-evals.yml. The documents test and Cohere's OCR skip without COHERE_LIVE_API_KEY (a missing secret arrives empty); everything else needs no key. The e2e job's database is pgvector/pgvector:pg16.

Found by running it live: the free model takes 50–85 s on the statement, so the tests set OPENAI_REQUEST_TIMEOUT=300; and the live route needs max_output_tokens: 8192, since kilo-auto/free routes to reasoning models that spent the test's 1,024 thinking (bill setup failed 3 of 4 runs at 1,024, passed 3 of 3 at 8,192).

Plan: pr-2f-release-e2e.md in #4440's docs.

6. Review hardening of 2e's PDF reading, on 2f's code

Seven CodeRabbit rounds found edge cases in the code this PR changes. 2e's own findings were fixed on 2e and merged here; these are the ones in 2f's code:

  • Claims and recovery: a publish that can't check its claim raises, so the job retries with its token. Cancel, the reaper and a redelivered ProcessPdfJob share one recovery rule (PdfImport#recover_lost_claim!): a publish whose ledger transaction committed completes, a reading lost after it classified the document or cleared a previous reading fails so Read again is offered, and anything else goes back to pending. A PDF publish is marked complete inside its ledger transaction, so one whose rows all matched synced entries isn't published twice.
  • Reconciliation ownership: releasing a reading's marks on reread, account change or revert hands over a mark another reading depends on, leaves another import's mark alone, and re-checks the owner at each write.
  • Reading: each document route takes a PDF within its own limits; a way asked for by name keeps its own reason (a scan over the PDF limits is too_large); Auto's preferred way is keyed by the model it started from; recovery bisects each contiguous pending run separately, so answers keep document order; the OCR path fails over on timeouts too.
  • Statement checks: zero-amount balance lines never reach the import; a space-grouped number's last group isn't an amount of its own, but an amount after a whole one still is; dotted dates and localized month names (multiword ones included) anchor rows.
  • Keeping provider text out of logs: ProcessPdfJob records an AI failure and returns instead of re-raising, so Active Job never logs the provider's message; Jev diagnostics record only the endpoint's scheme, host and port; a provider's image refusal wins over a credit phrase in another field.
  • Assistant and API: the assistant re-checks for a live draft under the source import's lock, and its draft-exists answer says what clears it (delete the draft, or revert a published one and then delete it). Its scan hint suggests Images or OCR only when pdftoppm is installed. The API's enqueue failure returns the saved import_id and says how to resume it.

Declined, with reasons on the threads: fencing stale or concurrent job attempts with per-attempt tokens (a second claim protocol, put to the dev team in #5077), stronger date and duplicate heuristics, and an aggregate byte budget for page images.

Verification

Latest (2026-11-21, head 9854dcf19): full suite 18,256 runs, 201,393 assertions, 0 failures, 0 errors (32 skips); bin/rubocop (3,604 files) and Brakeman clean. 2e at 2b38374d3: 17,236 runs, 0 failures.

Earlier (2026-11-12):

The branch was brought up to date with main by merge (main → 2a → 2b → 2c → 2d → 2e → 2f), since 7c7f78c90.

  • Full suite (PARALLEL_WORKERS=2 bin/rails test): 16,094 runs, 188,992 assertions — 0 AI/2f-related failures. CI on the latest head: green (ci / test_unit and ci / test_system on 43222205673) after a failure on family_test.rb was found, scoped to a test that had pinned "no diagnostic" — updated to assert the new once-per-process entry. 13 pre-existing environmental failures remain in the local-hosted run (Wise/Binance/Budget/Demo); the CI-hosted suite stopped at that one fix.

  • Live tests (bin/rails test test/models/ai/live): 26 runs, 0 failures, 13 skips. Live passes: ai/live/generate_live_test.rb for kilo/~openai/gpt-luna-latest (gpt-6-luna) and kilo/~anthropic/claude-haiku-latest (claude-haiku-5.5) — categorize + bill setup, both through the /responses API with cassettes.

  • Live-Jev (test/models/ai/live/openrouter_jev_live_test.rb): parallel/decisions-fast:free — STARBUCKS under "Coffee Shops" (0.67), PAYROLL under "Salary" (0.99).

  • cassettes re-recorded for kilo (generate_categorize_*, generate_bill_setup_* for both models) and openrouter_jev/judge_categorize.yml. Zero credentials in the cassettes; the keys filter in ai_test_helper.rb AI_CASSETTE_KEYS now includes OPENROUTER_LIVE_API_KEY + KILO_API_KEY + KILO_ORG_ID.

  • bin/rails test test/system/settings/categorization_provider_test.rb — 8 runs, 0 failures.

  • bin/rubocop on all touched files — no offenses; bundle exec erb_lint on the touched views — clean; locale files re-checked for key parity.

  • End to end (AI_E2E=1 DISABLE_PARALLELIZATION=true bin/rails test test/e2e/ai, 2026-11-12): 8 runs, 61 assertions, 0 failures; skips without AI_E2E, and the documents test skips with COHERE_LIVE_API_KEY empty. Free live legs (AI_LIVE=1 … -n "/kilo-auto\/free|test_jev: |test_cohere: /"): 5 runs, 0 failures, Cohere's OCR passing live for the first time. actionlint on ai-e2e.yml and bin/rubocop on the changed files: clean. Full suite after the commit: 16,103 runs, 14 failures, all outside AI (Wise, Budget, Binance, Demo, provider import); they also fail with this commit's one shared line (the test_helper.rb require) removed.

Live checks run on this branch (2026-11-12): Kilo routes — ~openai/gpt-luna-latest (gpt-6-luna) and ~anthropic/claude-haiku-latest (claude-haiku-5.5) — both pass live through the /responses API with cassettes re-verified for credentials scrubbing. OpenRouter parallel/decisions-fast:free STARBUCKS → Coffee Shops 0.67, PAYROLL → Salary 0.99. OpenCode Zen jev-1.13-free STARBUCKS → Coffee Shops 1.0. The paid ~typesafe/jev-latest still returns 402 insufficient_credits. (Gemini Flash Lite verification ran on the spike/ruby-llm branch, not here; Gemini does not ship a live route in this app.)

Closes none; independent of #4771's review and intentionally not part of it.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUUTovNPgC5oNfUHKhd

Summary by CodeRabbit

  • New Features
    • Added PDF reading options for text, page images, and OCR, with automatic selection and rereading for eligible imports.
    • Added statement extraction checks that flag results for review and prompt for confirmation before publishing when checks fail.
    • Added OCR and embedding support, plus clearer document indexing statuses and relevance filtering in document search.
    • Added OpenRouter Decisions endpoint support for Jev, with setup guidance and warnings for unsupported endpoints.
  • Bug Fixes
    • Improved document access and indexing eligibility, and added safeguards for rereading and publishing imports, including clearer handling of missing dates and queue failures.
  • Documentation
    • Updated guidance for AI hosting, document processing, and testing.