Fix eight #5077 follow-ups: credentials, rule-run accounting, JSON mode, eval errors

Merged
JO
4d ago
+681-170

Problem

Eight follow-ups from #5077 in code the stack below introduced or kept. Three send a credential to the wrong server, and one leaves a rule run unfinished for good.

What changes

One commit each:

  1. The saved OpenAI key stays off separate embedding servers (P1 from #4774). The embedding route fell back to the key saved in Settings for any EMBEDDING_URI_BASE, so an Ollama box or another gateway received it. Now the saved key goes only to the OpenAI URL it was saved with. OPENAI_ACCESS_TOKEN still falls back as it always has.

  2. An inherited OpenAI URL gets /v1 for embeddings (P2 from #4774). It's normalized as the chat client normalizes it. EMBEDDING_URI_BASE stays as written. Same commit as 1.

  3. No Authorization: Bearer none (from #4773). RubyLLM requires a key, so a keyless compatible endpoint was given "none", and both the probe and the embeddings sent it. The stand-in is now a constant, and Ai::Transport::Http::ProxyNetHttp, the adapter every RubyLLM request goes through, drops the header. Jev's transport is unchanged.

  4. A rule run counts its AI job before the job is queued. Rule::Runner used to write pending_jobs_count after every action had queued. That caused two failures:

    • A job that finished first left the run unfinished for good.
    • When a second AI action failed to queue, the first action's job was never counted.

    Now RuleRun#await_ai! counts the job along with its transactions, and #release_ai_job! gives both back when queuing fails. The runner no longer writes the count or the status of an async run. This was on main before the plumbing.

  5. The merchant eval reports errored samples. samples_errored and error_rate were missing, so Eval::Reporters::Recommendation saw no errors in any merchant run.

  6. Evals send OPENAI_EXTRA_HEADERS only to the configured server. Provider::Openai.new now takes extra_headers:, which defaults to the environment value. Eval::ProviderFactory passes the headers only when the run is on the configured server, or on OpenAI's when no server is configured.

  7. Each AI generation job step commits once (rule-run progress across a replayed job). Before:

    • A replayed Ai::GenerationJob subtracted its batch from the run's awaited count a second time.
    • A retry after fail_job! deadlocked released the transactions again.
    • A replay after the next batch was queued ran two chains, and both completed the job.

    Now each job carries its step, and one transaction claims the step on its Ai::GenerationRun, applies the batch and saves the next job's arguments. On the last step, the same transaction deletes the run and the requester hears the end; giving up works the same way. A copy that loses the claim rolls back and stops. A replay of a step that already committed queues the saved next job unless that job has started, and reports nothing. Migration 20261122130000 adds step and next_job to ai_generation_runs, a table this stack introduced (#5521).

  8. Bill setup and PDF import ask a compatible server for json_object, as on main (found in luis-ibanez's slice review; tracked in #5077). On main, an OpenAI-compatible server got json_object, with no schema, for these two, and a strict schema for categorize and merchants. The stack's one auto chain gave every feature strict first, so a server that refuses strict schemas cost bill setup and PDF their json_object. In auto, Ai::LegacyEnvConfig now sets those two route entries' JSON mode to json_object, then no format on a 400, as before. Categorize and merchants keep auto, and an explicit LLM_JSON_MODE applies to every feature. PR 7a's tables carry the entry's mode, and 7b lets an admin change it.

    The cost. A compatible server that answers prose in json_object mode now fails after one request where the stack walked on to no format: PDF import ends failed and bill setup returns InvalidOutput. A server that accepts strict schemas also gets json_object for these two. Both match main. PDF import now says the model's answer couldn't be read, not that no model can read the PDF (ce1fbec36).

Also in this PR

  • Nullable enums to Anthropic as anyOf (#5663, luis-ibanez, merged here). Anthropic rejects an enum on a nullable field, so the affected features failed every call with a 400.
  • compatible_base keeps a path with a /v1 segment as given and adds the version to the path, not after the query (912bb5f73, 51f691170). A Cloudflare AI Gateway URL no longer gets a second /v1, and ?api_key=abc no longer becomes ?api_key=abc/v1.
  • The merchant enhancer releases its lock once the run's end commits (part of item 7, 9a9cf04f1), not inside the transaction that might roll back.
  • The models list and vector stores send no Authorization for a keyless endpoint (d9dca931a), as item 3 does for RubyLLM.
  • The Turkish usage-average note names %{with_cost} of %{total} calls (b1024340d, CodeRabbit on #4774).

The cubic summary's "never records more modified than matched" holds from #5744 up, not at this PR's head.

#5659 on main

dgilperez ported the embeddings part of item 1 to main as #5659, leaving item 2's /v1 normalization to this PR. The stack now has main through #5659: main was merged into refactor/ai-plumbing (72e2ba08f) and carried up each layer. Resolving it in this PR (44862c324):

  • Ai::LegacyEnvConfig: this PR's embedding_model, which adds item 2's /v1, and its same_server?, which compares through Ai::Transport::Http.same_url?. #5659's server_of goes, since same_url? makes the same comparison.
  • legacy_env_config_test: #5659's three embedding-key tests are kept, and this PR's three overlapping ones are dropped. This PR's /v1 test stays.
  • The request-level test: #5659's check of the Authorization header actually sent now runs through Ai::Embeddings, the plumbing's embedding entry point, in test/models/ai/embeddings_test.rb. VectorStore::Embeddable#embed no longer exists on the plumbing branch. With item 3, the test expects no header at all for a keyless separate server.
  • docs/hosting/ai.md: both paragraphs joined.

main and this PR now agree on where the saved key goes. On top of that, this PR adds the /v1 normalization (item 2) and drops the header for keyless endpoints (item 3).

Upgrade note

An install with pgvector or Qdrant, EMBEDDING_URI_BASE pointing at its own server, and only a key saved in Settings stops sending that key there. If that server needs a key, set EMBEDDING_ACCESS_TOKEN. docs/hosting/ai.md says so.

Validation

  • Each fix has a test that fails without it and passes with it.
  • bin/rails test after the merge of main through #5659 and item 8: 18,746 runs, 0 failures.
  • bundle exec rspec spec/requests: 489 examples, 0 failures.
  • Rubocop on the changed files, Brakeman and the Pipelock diff scan are clean.
  • No prompt changes. Locale text only: the PDF import message (en) and the Turkish usage note.

Stacked on #5550 (stack #5504). Ticks eight boxes in #5077.
Closes #5546

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUUTovNPgC5oNfUHKhd


Summary by cubic

Fixes eight #5077 follow-ups so credentials and headers stay on their intended servers, rule runs track AI jobs correctly across fast finishes, retries, and mixed actions, and eval metrics report errors.

  • The OpenAI key saved in Settings goes only to the OpenAI URL it was saved with; OPENAI_EXTRA_HEADERS stays on the configured server. URL comparisons ignore scheme/host case and default ports but keep path case.
  • A separate embedding server never receives the saved key or OpenAI headers. An inherited OpenAI URL gains /v1; EMBEDDING_URI_BASE is used as written. Keyless endpoints send no Authorization header. A separate embedding server that needs a key must set EMBEDDING_ACCESS_TOKEN or OPENAI_ACCESS_TOKEN.
  • Rule actions count their AI job (with its transactions) before anything is queued, and the jobs are queued after all actions run. A job that can't be queued gives its count back; a job that finishes immediately still finds itself counted.
  • A rule run keeps its own changes and the AI jobs' apart, and never records more modified than matched.
  • Each AI generation job claims its step of the run in one transaction that also saves the next job's arguments, so reruns and retries report each batch, and the end, once. Migration 20261122130000.
  • In auto, bill setup and PDF import ask compatible servers for json_object, then no format on a 400; an explicit LLM_JSON_MODE still applies to every feature. PDF import now says the model's answer couldn't be read, not that no model can read the PDF.
  • On native Anthropic, a nullable enum is sent as anyOf the enum's values and null, since Anthropic rejects an enum on a nullable field and the affected features failed every call with a 400.
  • Merchant eval metrics now include errored samples and error rate.

Summary by CodeRabbit

  • New Features
    • Evaluation results now include the number and rate of errored samples.
    • AI rule runs more accurately track queued and completed jobs, including when jobs finish before run progress is recorded.
    • OpenAI credentials and extra headers are applied according to the configured server.
  • Bug Fixes
    • AI generation retries better handle duplicate or concurrent jobs, preventing repeated results and preserving runs for retry after failures.
    • Keyless embedding requests no longer send an authorization header.
    • Bill setup and PDF import use compatible JSON response formats, with a fallback when a server does not support them.
  • Documentation
    • Updated AI hosting guidance to explain credential fallbacks and embedding URL behavior.