AI plumbing 2c: generations

Merged
JO
8d ago
+7191-5677

Part 2c of the AI plumbing series. 2a (#4773) and 2b (#4774) are merged. This PR is one commit on refactor/ai-plumbing; 2d (#4765) and 2e (#4771) follow it on the same branch. Merge them in that order. Until this merges, #4765's diff includes this PR's changes.

Part 2c of the AI plumbing redesign proposed in #4440. Split out of #4765, which held 2a to 2d and now holds 2d only. Implementation plan:
pr-2c-generations.md; its place in the series is in
§19.

Part of #3597 (auto-categorization provenance). It doesn't close it: recording the route and confidence on each enrichment is follow-up work in #5077, and the UI is #3606.

Problem

After 2b every feature asks the router whether it may run, but the calls still go through eight
hand-written workers (Provider::{Openai,Anthropic}::{AutoCategorizer, AutoMerchantDetector, ProviderMerchantEnhancer, BillSetupSuggester}, about 2,230 lines). Each has its own prompt
heredocs, JSON recovery (five copies of parse_json_flexibly), JSON-mode fallback, Langfuse
spans, usage recording and error policy, and they have drifted:

  • a failed OpenAI bill setup records no usage, Anthropic's does (drift bug 2);
  • categorization raises, merchant detection returns 0 silently, merchant enhancement skips the
    batch without a word (drift bug 3);
  • Anthropic batches aren't token-sliced, and bill setup ignores LLM_JSON_MODE;
  • a job holds its AI thread for every sub-batch of a large run.

What this adds

flowchart TB
  D["requester<br/>Family::AutoCategorizer, AutoMerchantDetector,<br/>ProviderMerchant::Enhancer, AiSetupSuggester"] -->|"*_later / controller"| J["Ai::GenerationJob(feature, args)"]
  J --> G["Ai::Generation#call(batches: 1)"]
  G --> L{"next route<br/>not marked down"}
  L --> P["Ai::Prompt<br/>app/prompts/&lt;name&gt;/instructions + input"]
  P --> B["Ai::Batch: batch_size + tokens"]
  B --> T["route.transport.generate"]
  T --> S["Ai::Schema coerce"]
  S -->|ok| RES["Ai::Result(value, route, remaining)"]
  T -->|"timeout, 5xx, 429, refused,<br/>bad key, missing model"| DM["Ai::DownMarks → next route"]
  S -->|"InvalidOutput"| ESC["escalate → next route"]
  T -->|"ContextTooLong / cut at limit"| SPLIT["halve the batch, same route"]
  ESC -->|"every route"| BIS["halve on the first route (twice at most);<br/>skip and log what still fails"]
  RES --> AP["requester.apply_ai"]
  AP -->|"remaining?"| J
  AP -->|done| FIN["requester.ai_finished → RuleRun / lock"]
  • transport.generate: one call per protocol, the schema through RubyLLM's with_schema
    (a strict response_format on chat completions and the Responses API, Anthropic's native
    output_config). Compatible servers follow the route's JSON mode: auto walks strict,
    json_object, none; a 400 about the JSON mode or the effort retries once in none without the
    effort (#3605); any other 400 ends the call. One tolerant parser for <think>, fences and
    prose. Reasoning effort per route entry, with llama.cpp's way of turning thinking off.
  • Ai::Generation: a feature is a declaration (feature, prompt, schema, batch,
    merge, blank_item). It resolves the plan, renders the route's prompt, takes a batch sized for
    the model, generates and coerces; failover marks the smallest broken thing down for 60 s,
    invalid output escalates, an overflow is halved on the same route.
  • Ai::GenerationJob: one batch per job, the rest re-enqueued at the back, so families take
    turns; retried and discarded errors per §9, and the requester hears once, so a rule run never
    stays pending. A job whose family was deleted while it waited is dropped.
  • One job per AI rule action. The rule action queues one job with every transaction, and
    Ai::Batch is the only place a batch is sized. When a batch's answer is unusable on every route,
    it's halved on the first route, twice at most, to find the transactions that break it; those are
    skipped and logged by id, and the run goes on. A model that answers nothing still fails the batch
    after a bounded number of calls.
  • Rule-run progress. rule_runs.transactions_awaiting_ai counts down as each batch is applied,
    the modified count grows per batch, and GET /api/v1/rule_runs/:rule_run_id/progress lets a
    client watch it reach 0 (Minitest, a documentation-only rswag spec, docs/api/openapi.yaml).
  • Four generations (CategorizeTransactions, DetectMerchants, EnhanceMerchants,
    SuggestBillSetup), each with its requester and test file.
  • Prompt folders: today's eleven prompt variants in app/prompts/<name>/, rendered byte for
    byte against golden texts captured from the workers. The one change: Anthropic's four prompts
    lose the sentence naming the tool they answered through.
  • One prompt override per feature, with a data migration and a notice on the prompts page
    where a family's second override was set aside.
  • Evals run the same generations on the run's model (Eval::GenerationClient).
  • CI: ai-evals.yml replays recorded answers on any AI change; the ai-live label runs live
    tests and evals with repository secrets; test/models/ai/live/ holds the cassette tests.
  • Sure/NoPromptHeredoc, and Sure/NoAiEnv's "2c" entries are gone.

Reviewer guide

  1. app/models/ai/generation.rb: the loop, batches, failover, escalation, splitting.
  2. app/models/ai/transport/json_mode.rb and anthropic.rb#run_generate.
  3. One generation and its prompt folder, e.g. ai/generations/detect_merchants.rb and
    app/prompts/detect_merchants_simple/.
  4. app/models/family/auto_categorizer.rb: the requester.
  5. test/architecture/ai_escalation_test.rb, ai_batch_split_test.rb and ai_prompts_test.rb.

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

  • The deprecated ENV lists only the preferred LLM in each generation route, as today's
    preferred_llm_provider picks one: failover never sends a family's data to the other
    provider. Failover and escalation take effect once routes are configured (PR 7). With 2b's
    rule, a preferred provider that can't be built routes nothing, as today's callers raise there.
  • Native OpenAI batches aren't cut to a 2,048-token window unless LLM_CONTEXT_WINDOW is set,
    as on Anthropic; custom OpenAI-compatible servers keep the 2,048 default. Counting the prompt and
    schema against that default would have cut a categorize batch from 16 transactions to 7.
  • Bill setup follows the same JSON policy as the other features.
  • One folder per prompt (instructions.txt.erb, input.txt.erb), as RubyLLM's agents keep
    theirs.
  • The override keys collapse in 2c.
  • No job shims: the old job classes are deleted.
  • with_schema on both protocols, Anthropic through native structured output, which a live
    check with a funded key still has to confirm on every current Claude model (open below).

Deleted

The eight workers, Provider::Openai::BatchSlicer, the providers' auto_categorize,
auto_detect_merchants, enhance_provider_merchants and suggest_bill_setup,
Provider::LlmConcept's four result types and max_items_per_call,
Family#resolved_categorization_provider, AutoCategorizeJob, AutoDetectMerchantsJob and
EnhanceProviderMerchantsJob, and their tests.

Upgrade notes

  • Let the ai_high_priority and ai_low_priority queues drain before upgrading. The old AI job
    classes are gone, so a job still queued under one goes to Sidekiq's dead set, and a rule run
    waiting on it stays pending.
  • Bill setup honours LLM_JSON_MODE, and uses a strict schema on native OpenAI.
  • auto JSON mode tries json_object between strict and none.
  • On native OpenAI, batches hold up to LLM_MAX_ITEMS_PER_CALL items (default 25) unless
    LLM_CONTEXT_WINDOW is set, so a stock install makes fewer, larger calls. On a custom
    OpenAI-compatible server, batches are sized from the actual prompt and schema within
    LLM_CONTEXT_WINDOW (default 2,048), so a small window means smaller batches. Anthropic batches
    are token-sliced when LLM_CONTEXT_WINDOW is set.
  • OPENAI_SUPPORTS_RESPONSES_ENDPOINT=true on a custom server applies to background AI too.
  • Background AI runs one batch per job, so a large rule run takes turns with other work. A rule
    run's pending_jobs_count is 1 per AI action; poll the new progress endpoint to follow it.
  • Failed merchant detection and enhancement now appear in the debug log.
  • Prompt overrides are one per feature; the prompts page shows an override that was set aside.
  • Two migrations: CollapseAiPromptOverrideKeys rewrites families.ai_prompt_overrides, and
    AddTransactionsAwaitingAiToRuleRuns adds the progress column (tested up, down and up on a
    development database).

Still on old code

  • Jev's calls and the inline shadow run: 2d (#4765).
  • The PDF and statement workers, the usage recorders and preferred_llm_provider: 2e (#4771).
  • Chat: PR 6. Configuration stays on the hostings page until PR 7.

Validation

At 2f82159a1 (the current head, after CodeRabbit's reviews of #4775 and #4765):

  • bin/rails test: 16,399 runs, 13 failures. Each also fails without this PR's changes: 10 Wise tests, Binance (binance_items_controller_test.rb:153), budget_test.rb:13 and financekit_generator_test.rb:148
  • bin/rubocop: no offenses
  • test/system/settings/ai_prompts_test.rb: 7 runs, 0 failures (at e73406cd6; the AI prompts page hasn't changed since)

At 06a1e06eb and b54b77ea8 (after the editor's review below):

  • The AI and rule areas (test/architecture, test/models/ai, test/jobs, test/models/family, test/models/rule, test/models/eval, the rule runs API, rules, settings and merchants controllers, test/lib, test/i18n_test.rb): 0 failures
  • bin/rubocop, Biome, bin/brakeman (no warnings), erb_lint on the changed views
  • The rule runs rswag spec (12 examples) and a regenerated docs/api/openapi.yaml
  • CI's full unit suite at 06a1e06eb: 15,517 runs, 1 failure: bisection called size on a generation that takes no list (bill setup), fixed in b54b77ea8 with the suggester's test as its regression test. CI re-runs on b54b77ea8
  • The system tests for the changed AI prompts page (test/system/settings/ai_prompts_test.rb): run at e73406cd6, above

**Earlier, on this branch alone at eae2074e1 (with main at e529f1113 merged in through 2a and 2b), except the system tests:

  • bin/rails test: 15,192 runs, 0 errors, 13 failures. Each also fails on main in the same environment
    (Wise ×10, BinanceItems, Budget and FinanceKit-demo date tests). 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, at the top of the stack (#4765): 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 main...HEAD: no findings
  • Every prompt variant renders byte for byte against the golden texts captured from the workers (test/architecture/ai_prompts_test.rb)
  • Live generate on venus llama.cpp (qwen3.6, JSON mode auto): categorize and bill setup, recorded as cassettes (c150c42b2)
  • Live generate on OpenAI and Anthropic, including decision 7's check that every current Claude model accepts native structured output, and the recorded evals for ai-evals.yml. The keys available on 2026-11-07 had expired or were refused. Still open: decision 7 ships on the stubbed contract tests only; if a current Claude model refuses native structured output, Anthropic falls back to the forced tool and its four prompts get their tool sentence back

Review on this PR

  • @jjmata's note (reuse spec in the router) is fixed in 2b (77b8a8f49) and merged forward.
  • Comments say what the code does, not which PR brings what (AGENTS.md), as on 2a and 2b: 3e63431ac.
  • CodeRabbit's review after it went ready (20 inline, 4 in the summary): fixed in eae2074e1 and 0e16016cb, with
    tests, plus 9a0e844d7 in 2a and 14de1e335 in 2b. Notably: the job tells the requester on any error (a regression
    from main's jobs); answered items are kept when the rest fit no route; a parseable cut answer is split; the shadow
    compares only its batch; evals on the installed endpoint keep its headers and budget; the old job classes stayed as
    forwarders (since deleted, per decision 6, in the editor's review below). Six have replies with reasons (job replay, mcp_only bill setup, the usage
    page's call outcome, eval cassettes, the per-request deadline, the eval protocol option).

Editor's review (2026-11-09)

A local review of 2c as a Rails editor, with fixes and tests:

  • Fixed: a job whose family was deleted while it waited was retried forever; items no route can fit
    are now logged instead of vanishing; native OpenAI's batch size (above).
  • Decided: the old job classes are deleted rather than kept as forwarders (decision 6); one job per
    rule action, with bisection and the progress endpoint (above).
  • Simplified: the prompts page's field takes one prompt (the provider dropdown, its Stimulus target
    and its strings in every locale went); the bill setup suggester stops re-checking what Ai::Schema
    enforces; the enhance lock is taken in ProviderMerchant::Enhancer.enhance_later, not the
    controller; the prompts page loads dropped overrides in the controller; one Ai::Config#batch_size_for
    for the eval runners; the two LLM route rules in Ai::LegacyEnvConfig are stated once, with one table test.
  • Found in 2b, fixed there and merged: the rule confirm page's Jev test (e8f4d0f1e) and an agreement test for a
    preferred provider that can't be built (1c99af0f0).
  • Found, not fixed (as on main): when the preferred LLM can't be built, the insights dig-in check and the
    categorization provider lookup raise instead of answering "unavailable". That's chat's path (PR 6).

Merged in from 2a and 2b

main up to 4f2970b0f, #4815, and the fixes from #4773's and #4774's reviews: the RubyLLM TLS adapter and proxy decision per
request (a port-qualified NO_PROXY was ignored), per-request errors, secrets scrubbed from errors and Langfuse content,
stricter probe checks, the usage backfill's JSON and Unicode-space checks, the vector store nil check, the probes'
API choice and cache key, and from the latest round: a retry's timeout isn't rounded up, NO_PROXY CIDR blocks match a
resolved host, and no LLM is routed after a preferred provider that can't be built.

Fixed after live testing (2026-11-07)

  • A 400 to a request that sent a reasoning effort is retried once without it (75397512f).
    • The cause: Gemini refuses reasoning_effort: "none" with "Request contains an invalid argument". That names neither the effort nor the JSON mode, so the #3605 retry, which matched the wording, didn't run and the call failed.
    • The fix: any 400 to a request that sent an effort now gets that one retry. Without an effort, a 400 that doesn't name the JSON mode still ends the call. Re-run live on Gemini, none succeeds on the retry.
    • It was found on 2e (#4771), and merged forward into 2d and 2e.
  • Also merged in from 2a (#4773): the Anthropic probe's proxy fix and the tracing shutdown at exit.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUV2Sxn9CgsmcUqojAZ

Summary by CodeRabbit

  • New Features
    • Added an API endpoint for tracking rule-run status, queued work, AI processing progress, and completion.
    • AI prompt settings identify overrides that can no longer be applied and retain them until saved.
    • Added recorded and live AI evaluation workflows.
  • Improvements
    • Categorization, merchant detection and enhancement, and recurring-bill suggestions use shared AI workflows.
    • AI processing adapts batches to model limits, retries certain failures, and reports unanswered work.
    • Categorization and merchant-detection prompts are shared across providers and offer selectable variants.
    • AI usage records and traces include correlation IDs.
  • Documentation
    • Expanded guidance for AI configuration, prompts, batching, evaluations, and job progress.