Count each AI rule job once, and stop retrying AI failures that can't pass
Fixes #5546.
Problem
A rule run with AI actions can end with the wrong count, or never end. There are three ways it happens.
The count is written too late. Rule::Runner sets pending_jobs_count from Rule#apply's result after every action has queued its jobs. A job that finishes first (nothing to do, or a fast model) drains a count of zero, then the runner sets the count, and the run stays pending for good.
A retry counts again. RuleRun#fail_job! takes one off the count on every attempt of the same job. With two AI batches, batch A failing twice brings the count to 0 while B is still running. The tests didn't catch it: "fail_job is retry-safe" starts at 1, where the count can't go below 0, and "deduplicates repeated error messages" accepts 0 with three jobs, one of which never reported.
Failures that can't pass are retried. AutoCategorizeJob and AutoDetectMerchantsJob had no retry_on/discard_on, so a rejected key, a 4xx or a response that doesn't parse got Sidekiq's 25 retries, each one a paid call. A transient failure that later passed still left the run failed. Family::AutoMerchantDetector swallowed provider failures (return 0), so merchant detection never retried a timeout and the run said success.
What changes
RuleRun#await_jobs!counts a rule's AI jobs atomically before any is queued, andRule#applyqueues them after its last action (Rule::ActionExecutor.queue_ai_jobs_after), so no job can finish the run before every AI action has counted its own. A batch that can't be queued counts as a failed job, and the batches after it are still queued even if recording that failure raises. The runner no longer writes the count or the status of an async run.RuleRun#complete_job!and#fail_job!take thejob_idand record it insettled_job_idsunder the row lock. A job that reports again (an ActiveJob retry, or Sidekiq running it again after a restart) changes nothing. New column, default[].- Both jobs share
RuleAiJob, which reports to the run once, when the job is done for good: on success, on a discard, or when retries run out. - Deleting a rule deletes its runs, so a job whose run is gone sends nothing, and one already calling the model when the rule goes ends without raising, so Sidekiq doesn't send the batch again (
RuleRun#settle_jobsettles nothing for a run that's gone). - Failures map onto
Ai::Errorthrough the cause chain. Timeouts, 429, 5xx, unreachable servers, deadlocks and lost database connections get 5 attempts with:polynomially_longer. 401/403, no credit, a missing model, a context overflow and other 4xx are discarded after one call. Anything else (no provider, no categories, a response that doesn't parse, a bug) ends the batch, and it's recorded on the run and inRails.error. Sidekiq keeps 3 retries only for what escapes the job (the run failing to settle when the job gives up, a retry that can't be queued); they reuse thejob_id, so the run still counts the job once. Provider::Errorkeeps the client error it wraps ascause.with_provider_responsereturns errors instead of raising them, so the HTTP status never reached the job.Provider::Sophtron::Errorforwards the new keyword.Family::AutoMerchantDetectorraises on a provider failure, asFamily::AutoCategorizerdoes.RuleJobraises the applied rule's own error (Rule::Runner#error_for), not the last one recorded, so a run failed by a batch that couldn't be queued doesn't raisenil.
A retry doesn't resend what an earlier attempt applied: applied transactions are locked, and both enrichers skip locked ones.
The two tests that hid the double decrement now use two or more jobs. "A retry that succeeds after the run's only job failed" is gone, since a job no longer reports a failure before its last attempt.
It also corrects what the AI routing table declares for categorization and merchant detection, and the guide table generated from it (bin/rails ai:routes_doc): categorization listed bank-suggested categories, which nothing sends, and both left out transaction notes, with merchant names missing from categorization and amounts from merchant detection. A test now maps every field those payloads send to a declared item. The family AI notice lists the same data in every locale, and Norwegian, which had no family notice, gets one.
When #5521/#5608 reach main
Ai::GenerationJob replaces RuleAiJob and both jobs, and #5608 item 4 replaces await_jobs! and the deferred queuing with its own await_ai! and queue_ai_jobs_after, which follow the same design.
The 5-attempt budget and the split stay the same: rate limits, timeouts, 5xx and unreachable servers are retried; auth, no credit, missing model, context overflow, invalid output and other refusals are discarded.
On that branch the transport maps errors to Ai::Error itself, so the cause-chain lookup and Provider::Error#cause aren't needed there. It counts transactions (transactions_awaiting_ai) rather than jobs, and #5608 item 7 claims each job step on ai_generation_runs, so settled_job_ids has no counterpart there and can be dropped when the plumbing replaces these jobs.
One difference: here a batch that can't be queued fails the run and the rest are still queued, while #5608 gives back its count and those of the jobs after it, and raises, so the runner records the rule as failed.
Summary by cubic
Counts a rule's AI jobs on the run before any is queued, and queues them only after all actions have run, so a fast job can no longer finish the run before later jobs are counted. Stops retrying AI failures that can't succeed, and makes the consent levels and data disclosures match what actually runs and sends.
- Records the
job_ideach job settles under the row lock, so a retried or re-delivered job is counted once instead of draining the pending count again. - Replaces both AI jobs with a shared
RuleAiJob: timeouts, 429s, 5xx errors, unreachable servers, and deadlocks get 5 attempts; deterministic failures (auth, no credit, missing model, context overflow, invalid output) fail immediately. - A lost database connection is retried like a deadlock; Sidekiq catches the few failures that escape the job, such as the run failing to settle when it gives up.
- A batch that can't be queued fails the run, and the other batches are still queued even when recording that one fails.
- Retrying the record of an unqueued batch uses one
job_id; a job whose run can't be loaded on any attempt is handed to Sidekiq, which reuses the samejob_id. - An
Ai::Errorthat is neither retried nor discarded ends its batch after one call, and the batch's applied count survives retries of its report. Family::AutoMerchantDetectornow raises on provider failure instead of logging and returning 0, so retries actually happen. The wrapped client error stays ascauseonProvider::Errorso jobs can classify it.
Consent
- AI features use the consent level the routing table declares: chat, bills, and document search need the user's own switch; background categorization and merchant detection need a family admin with AI on.
- Uploading a PDF for import is itself the request, so reading it and the upload's search copy need no switch; document search still does.
- The routing table now lists exactly what categorization and merchant detection send — transaction notes, amounts, merchant and category names, and whether each transaction is income or an expense — replacing the bank-suggested-categories field nothing sends; an architecture test ties each payload field to a declared item.
- The consent screen no longer says data goes "as they are" — it now says nothing is anonymized — and in every locale the family notice names the transaction notes, category names and income/expense direction that background AI sends; Norwegian gets both new strings.
Migration
- Requires
rule_runs.settled_job_ids(array, default[]); the migration is included.
Summary by CodeRabbit
- Reliability
- AI-assisted categorization and merchant detection retry temporary provider and database issues; permanent failures are recorded on the rule run.
- Rule run progress and completion results remain accurate when jobs are retried or report outcomes more than once.
- If scheduling a batch fails, the failure is recorded while other batches can continue to be queued.
- Provider errors retain their underlying cause, providing clearer failure details.
- Transparency
- AI consent notices clarify that transaction notes and category names may be shared with the AI provider. One notice also clarifies that messages, transactions, and documents are sent unchanged.