AI plumbing 2d: Jev and shadow runs

Merged
JO
8d ago
+2834-2027

Part 2d 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 before 2e (#4771) and 2f (#4892). Merge them in that order. Until 2c merges, this diff includes its changes.

Part 2d of the AI plumbing redesign proposed in #4440. 2a to 2c used to be in this PR too. They're now their own PRs, so the parts can be reviewed one at a time. Implementation plan:
pr-2d-jev-and-shadow-runs.md; its place in the series is in
§19.

Part of #4419 (Ollama in the Decision Model preview). It doesn't close it: 2d accepts a self-hosted Jev-compatible server over http (the jev_local preset, §7), but not Ollama's own API, which needs a separate adapter.

Problem

After 2c, Jev was the one categorization path still off the plumbing: Provider::Jev (416
lines) had its own Faraday client, retries, parsing and 8-thread pool, recorded no usage, and was
called through 2c's JevCall bridge, with no failover or down marks. Shadow comparisons ran
inline in the primary job, holding its AI thread for a second model's answer (drift bug 8), were
symmetric through Family#shadow_categorization_provider, and wrote CategorizationComparison,
which only categorization could use.

What this adds

flowchart TB
  J["Ai::GenerationJob(:categorize)"] --> G["Ai::Generations::CategorizeTransactions<br/>judged_by CategorizeTransaction"]
  G --> L{"route.judge?"}
  L -- no --> GEN["prompt → transport.generate → Ai::Schema"]
  L -- yes --> JU["Ai::Judgements::CategorizeTransaction"]
  JU --> TJ["Ai::Transport::Jev#judge<br/>pool of parallel_requests<br/>RubyLLM judge (typesafe)"]
  GEN --> RES["Ai::Result(value, route)"]
  TJ --> RES
  RES --> AP["apply_ai: threshold gates calibrated_confidence models"]
  RES --> SH{"shadow declared, rate hit,<br/>shadow_categorize available?"}
  SH -- yes --> SJ["Ai::ShadowJob(class, family, input sent, primary)"]
  SJ --> EV["compare.ai_shadow"] --> CS["ComparisonSubscriber → Ai::Comparison"]
  • The jev transport over RubyLLM's judge (typesafe provider): one System One request
    per transaction on a pool of the endpoint's parallel_requests (8 on cloud Jev, 1 on a local
    server), each through Sure's retries and instrumenter, so every request writes a usage row with
    its call id. One judge.ai event per batch. A malformed answer fails only its transaction.
    Questions are plain Hashes: RubyLLM 2.1.1's judge builder calls a Kernel method named like an
    option (fixed upstream in #1196).
  • Ai::Judgement and Ai::Judgements::CategorizeTransaction: today's question, opt-out,
    hierarchy hints and confidence clamp, answering in the generation's value shape. A generation
    that declares judged_by builds it on a judge route, so batches, down marks and failover stay
    in one loop and failover from Jev to an LLM switches class.
  • The threshold gates answers from a model with calibrated_confidence (cloud Jev), read off
    the result's route, instead of 2c's calibrated: true flag.
  • Shadow runs for any feature, as their own job. A generation declares shadow compare:, subject:; after a successful call the family's rate (until PR 7) samples it, and
    Ai::ShadowJob runs the same class on shadow_<feature> with every item the primary was sent,
    including those it couldn't answer, so the comparison shows where the shadow does better. Items
    left for a later job (after a failover) are shadowed by that job.
    Its calls are recorded under shadow_categorize and tagged shadow; its answer goes only to
    ComparisonSubscriber, which writes Ai::Comparison rows with category ids. Nothing is applied.
  • One Jev choice for the instance (Setting.categorization_provider, which
    CATEGORIZATION_PROVIDER still overrides), so routes need no per-family condition. The
    deprecated ENV path routes categorize to Jev or the LLM, and shadow_categorize to the other.
  • Evals run Jev through the judgement (Eval::GenerationClient on a Jev endpoint).
  • A live recording of the judgement on OpenCode Zen's free Jev, with its anonymous key, as
    the spike did; ai-live runs it live.

Reviewer guide

  1. app/models/ai/transport/jev.rb and test/architecture/ai_transport_judge_test.rb.
  2. app/models/ai/judgements/categorize_transaction.rb and generation.rb#run (the class switch).
  3. app/models/ai/shadow.rb, app/jobs/ai/shadow_job.rb and
    app/models/ai/instrumentation/comparison_subscriber.rb.
  4. app/models/ai/legacy_env_config.rb (categorize and shadow_categorize) and legacy_env_config/jev.rb.
  5. The two migrations and their tests.

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

  • families.categorization_provider goes in 2d, as §19 says. The Jev choice becomes one
    instance-wide setting until PR 7 lists routes per feature. An instance with one family keeps
    that family's choice; on an instance with several, every family goes back to the LLM.
  • No failover from Jev in the deprecated ENV's route, as today: the categorize route lists
    Jev or the LLM, never both, so a Jev outage never sends a batch to the LLM. Failover across
    classes is tested on the test setup and takes effect once routes are configured (PR 7).
  • From #4440: only TypeSafe-style …/v1/systemone endpoints until RubyLLM 2.2 (PR 5); https for
    cloud endpoints and http for local ones; the shadow rate stays the family's until PR 7.

Deleted

Provider::Jev, Provider::ClassificationConcept, the registry's :jev entry and
:classification concept, Family#shadow_categorization_provider,
Family#effective_categorization_provider, families.categorization_provider,
CategorizationComparison (its table migrates), Ai::Route#condition and :jev_family,
JevCall and the inline shadow run, and their tests.

Upgrade notes

  • Jev endpoints: only TypeSafe-style endpoints ending in /v1/systemone work. Jev through
    OpenRouter stops working until a later release (RubyLLM 2.2); any other path isn't supported.
    Both are left out with a warning, so categorization uses the LLM, and the settings form refuses
    them.
  • The Jev choice is instance-wide. One family: copied. Several: every family goes back to the
    LLM, and choosing Jev applies it to every family.
  • A self-hosted (http) Jev works on any local host, not only loopback; it gets one request at
    a time unless JEV_CONCURRENCY is set, and the confidence threshold doesn't gate it.
  • Jev requests appear on the usage page, a row per transaction, grouped per batch.
  • Shadow runs run as their own job after the primary batch; existing comparisons are kept.
  • A malformed Jev answer leaves that transaction uncategorized (it was withheld with a
    confidence of 0).
  • Migrations MoveCategorizationProviderToSetting and
    MoveCategorizationComparisonsToAiComparisons.

Still on old code

The PDF and statement workers, the usage recorders and preferred_llm_provider move in 2e. Chat
moves in PR 6. Bill setup still runs on the web thread until PR 3. Configuration stays on the
hostings page until PR 7.

Validation

At 4ceaeb24b: the AI, architecture, AI job, family, settings, eval, rules
and 2d migration tests pass (1,166 runs, 0 failures, 8 skips); bin/rubocop (3,400 files) and
erb_lint on the hostings views are clean. The full suite, system tests, Brakeman and Pipelock were
not re-run after the merges below; the list underneath is from the earlier head.

Live on OpenCode Zen's free Jev (jev-1.13-free, anonymous key public) at d0c635c05:
categorize through the deprecated ENV path, Ai::GenerationJob and Family::AutoCategorizer on
10 real transactions in a rule run: 9 categorized, 1 opted out, ~1 s with 8 in flight, rule run
success, 10 usage rows under one call id. A shadow run on shadow_categorize wrote agreement,
disagreement and shadow-only rows, tagged shadow, and applied nothing. This found that Jev
refused every real batch (an entry's amount is a BigDecimal, which RubyLLM's judge rejects);
fixed in d0c635c05, cassette re-recorded.

Run at the last 2d commit before the branch was rebased onto 499bfd87b; after the rebase the
AI, family, job and migration suites and #4768's allocator test pass (723 runs, 0 failures).

  • bin/rails test: 14,920 runs, 0 errors, 14 failures. Each failure also fails on origin/main in the same
    environment: Wise, Binance, budget and FinanceKit-demo date tests, and the allocator test #4768 has since fixed.
    None touches AI code.
  • bin/rubocop, with Sure/NoAiEnv and Sure/NoPromptHeredoc: no offenses
  • bundle exec erb_lint --lint-all: no errors
  • npm run lint (Biome): clean
  • bin/brakeman: no warnings
  • The full system suite: 333 runs, 2 failures, the combobox dark-theme colour checks, which fail the same way on origin/main (remote Chromium; PARALLEL_WORKERS=1, as the standalone browser takes one session). The categorization settings (instance-wide Jev choice, shadow results) and the AI prompts page pass.
  • Pipelock 3.6.0 git scan-diff of origin/main...HEAD, with CI's excludes: no findings
  • Jev's judgement live on OpenCode Zen's free Jev (anonymous key), recorded as a cassette (test/models/ai/live/judge_live_test.rb)
  • The two migrations (MoveCategorizationProviderToSetting, MoveCategorizationComparisonsToAiComparisons) are written and tested in the suite, not run against a development database

Merged forward (2026-11-07)

This branch has a merge of the parts before it, carrying fixes found by live testing on 2e (#4771):

  • From 2a (#4773): Anthropic's models probe through Sure's proxy, and metadata tracing flushed at exit.
  • From 2c (#4775): a 400 to a request that sent a reasoning effort is retried once without it.

Merged forward and reviewed (2026-11-10)

  • 2c's review round (#4775) merged in. Conflicts resolved toward 2d's instance-wide Jev:
    2c's InvalidOutput bisect and unfit logging sit beside 2d's judge path; 2c's reachable-LLM
    walk feeds categorize and shadow_categorize; routes have no position.
  • Rule-run progress (RuleRun#ai_handled!, from 2c) is shared through RuleRun::AiProgress
    and works for Jev too: a withheld low-confidence answer counts as handled, not modified (tested).
  • The shadow's items come from the result (items - result.remaining), so Ai::Generation
    no longer tracks them separately; a test covers an item only the shadow answered.
  • Editor's pass: PR history dropped from comments and from the AI guides (docs/llm-guides/
    no longer say "until PR 7"); Ai::Comparison#category_name without public_send.
  • Upstream: a malformed Jev answer records its usage row with 0 tokens, because RubyLLM's
    System One parser drops the usage the response reported. Reported as crmne/ruby_llm#1614;
    linked from Ai::Transport::Jev.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUWkAjEdyN6aEiqSgDd

Summary by CodeRabbit

  • New Features

    • Added an API endpoint for checking rule-run progress, including queued, AI-awaiting, and modified transaction counts.
    • Added AI comparison results and recent categorization disagreements.
    • Added instance-wide categorization provider settings and support for compatible self-hosted endpoints.
    • Added AI-powered recurring-bill suggestions and merchant website enrichment.
  • Improvements

    • Categorization and merchant detection now run in the background with adaptive batching and clearer progress tracking.
    • Consolidated categorization and merchant prompt customization, with notices for older overrides set aside until settings are saved.
    • Updated AI prompts and improved handling of incomplete results and temporary provider issues.
    • Added automated checks for recorded AI evaluations; live evaluations can be run on labeled pull requests.