Fix eight #5077 follow-ups: credentials, rule-run accounting, JSON mode, eval errors
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:
-
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_TOKENstill falls back as it always has. -
An inherited OpenAI URL gets
/v1for embeddings (P2 from #4774). It's normalized as the chat client normalizes it.EMBEDDING_URI_BASEstays as written. Same commit as 1. -
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, andAi::Transport::Http::ProxyNetHttp, the adapter every RubyLLM request goes through, drops the header. Jev's transport is unchanged. -
A rule run counts its AI job before the job is queued.
Rule::Runnerused to writepending_jobs_countafter 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 onmainbefore the plumbing. -
The merchant eval reports errored samples.
samples_erroredanderror_ratewere missing, soEval::Reporters::Recommendationsaw no errors in any merchant run. -
Evals send
OPENAI_EXTRA_HEADERSonly to the configured server.Provider::Openai.newnow takesextra_headers:, which defaults to the environment value.Eval::ProviderFactorypasses the headers only when the run is on the configured server, or on OpenAI's when no server is configured. -
Each AI generation job step commits once (rule-run progress across a replayed job). Before:
- A replayed
Ai::GenerationJobsubtracted 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 itsAi::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. Migration20261122130000addsstepandnext_jobtoai_generation_runs, a table this stack introduced (#5521). - A replayed
-
Bill setup and PDF import ask a compatible server for
json_object, as onmain(found in luis-ibanez's slice review; tracked in #5077). Onmain, an OpenAI-compatible server gotjson_object, with no schema, for these two, and a strict schema for categorize and merchants. The stack's oneautochain gave every feature strict first, so a server that refuses strict schemas cost bill setup and PDF theirjson_object. Inauto,Ai::LegacyEnvConfignow sets those two route entries' JSON mode tojson_object, then no format on a 400, as before. Categorize and merchants keepauto, and an explicitLLM_JSON_MODEapplies 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_objectmode now fails after one request where the stack walked on to no format: PDF import ends failed and bill setup returnsInvalidOutput. A server that accepts strict schemas also getsjson_objectfor these two. Both matchmain. 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_basekeeps a path with a/v1segment 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=abcno 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
Authorizationfor 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'sembedding_model, which adds item 2's/v1, and itssame_server?, which compares throughAi::Transport::Http.same_url?. #5659'sserver_ofgoes, sincesame_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/v1test stays.- The request-level test: #5659's check of the
Authorizationheader actually sent now runs throughAi::Embeddings, the plumbing's embedding entry point, intest/models/ai/embeddings_test.rb.VectorStore::Embeddable#embedno 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 testafter the merge ofmainthrough #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_HEADERSstays 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_BASEis used as written. Keyless endpoints send noAuthorizationheader. A separate embedding server that needs a key must setEMBEDDING_ACCESS_TOKENorOPENAI_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 forjson_object, then no format on a 400; an explicitLLM_JSON_MODEstill 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
anyOfthe 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.