Record each AI job with its count and deliver it again when lost

Merged
JO
4d ago
+566-294

Second PR in the stack after #5504 (#5477's replica → outbox → 4a → 4b → 4c), based on up/rule-run-modified-count (#5744, the replica of #5477). Plan: ai-generation-outbox.md, with O1–O6 from stack-sequencer-off-the-web-thread.md §3e.

Problem

A rule run counts an AI job, queues it, and gives the count back when queuing fails. That give-back is a second write that can fail too, and then the run waits for good (#5077, "Release a rule run's awaited count when releasing it fails too"; CodeRabbit's last finding on #5608; #5710 finding 1). A job lost after it started, or whose next step couldn't be queued, also left the run with nothing to deliver.

Change

  • One transaction counts and saves. Rule::ActionExecutor.queue_ai_jobs_after collects each AI action's job, then in one transaction calls RuleRun#await_ai! and creates each Ai::GenerationRun with its first job in next_job. The job is queued after the commit (ActiveRecord.after_all_transactions_commit). A failed transaction leaves no count and no run.
  • Nothing is given back. RuleRun#release_ai_job! and AiJob#release! are deleted.
  • next_job stays until the step commits (O1). The job no longer clears it when it starts. A next step the queue refuses is logged and left for delivery, not given up.
  • Ai::GenerationDeliveryJob runs every 15 minutes on scheduled. For each run whose next_job no job has touched for an hour (database clock, O2), it counts a delivery in the same UPDATE … WHERE deliveries < 3 (O3) and queues the step again. After the third delivery the requester hears Ai::GenerationJob::Undelivered through give_up, so a rule run finishes as failed (O4). Each delivery and give-up writes a DebugLogEntry (category ai), and the admin system-health page counts runs awaiting delivery (O5).
  • Merchant enhancement lease. The Enhancer's 10-minute cache lock, which could expire while a run waited for delivery, is replaced by "an unfinished enhance_merchants run exists for the family", checked under the family's row lock (#5077, "Merchant enhancement lease owned by its run").

What it doesn't cover

Two copies of a step that both start before either commits both call the model; one commits and the other stops at its claim (#5608). With O1 this also happens when a replay of the step before queues a step that's still running.

Tests

  • Run and job: the first job is saved in the run and queued only after the commit; a rolled-back transaction queues nothing; a refused or raising queue keeps next_job; a refused next step is delivered; a job killed mid-step is delivered after an hour, not before (O1); a step the queue took twice commits and counts once (O6); three deliveries then one give-up; two deliveries at once pass the cap once (O3).
  • Rules: a refused job stays counted and the run waits; a run that can't be saved leaves no count for any of the rule's AI jobs.
  • Enhancer: a second click waits while the run is unfinished, including while it waits for delivery.
  • SidekiqHealth counts undelivered runs without turning unhealthy.

Validation: bin/rails test, full suite, 19,208 runs, 0 failures. Rubocop clean.

Upgrade

No migration: next_job exists (#5608). Runs queued before the deploy have no next_job, so delivery never touches them; they finish or are swept as before.

🤖 Generated with Claude Code

https://claude.ai/code/session_016zAWUUTovNPgC5oNfUHKhd


Summary by cubic

A rule run that lost an AI job — the queue refused it, or the give-back failed — could wait forever. Counting the job and saving its run now happen in one transaction with the first job saved in next_job, and a delivery job re-queues any step no job has touched for an hour, backing off 2, 4, 8 hours… until a sweep gives up a run idle for a week, so the requester hears Ai::GenerationJob::Undelivered and the run ends failed.

  • Rule runs never give counts back: a failed transaction leaves no count and no run, so nothing can strand a run.
  • Each step's job stays in next_job until the step commits; its job_id owns the step, so a replayed or duplicate copy stops before calling the model, and each delivery names a new owner.
  • A rule whose AI job the queue refuses no longer fails: the run stays pending, counts what its other actions changed, and waits for delivery.
  • A rule whose action raises keeps what the actions before it changed: Rule::ApplyFailed carries the count, and the run fails with the raising error as the cause while counting those changes.
  • The AI's changes are tracked separately as job_transactions_modified; transactions_modified is capped at the matched count, so an AI job and the rule's other actions can't over-report.
  • The give-up runs under the run's row lock after a week idle, so a late start at the same moment can't be lost.
  • Deliveries are logged with their number, queue errors go to DebugLogEntry (category ai), and the admin system-health page counts runs awaiting delivery.
  • The merchant enhancer's 10-minute cache lock becomes an unfinished run for the family, checked under the family's row lock, so it can't expire while a run waits for delivery.

Migration

rule_runs gains job_transactions_modified, backfilled for pending runs; next_job already exists. Runs queued before the deploy have no next_job, so delivery never touches them; they finish or are swept as before.

Summary by CodeRabbit

  • New Features
    • AI generation work that is refused, lost, or interrupted can be retried automatically, with retries limited to three attempts.
    • System health now shows the number of AI runs awaiting redelivery.
  • Bug Fixes
    • Failed job enqueue attempts no longer discard saved AI work; pending work can be delivered later.
    • Rule runs retain accurate pending-work counts when AI jobs cannot be queued immediately.
  • Documentation
    • Updated AI pipeline guidance to describe the revised job delivery and retry process.