AI plumbing 3a-windowing: linear AI generation runs (#5077)

Merged
JO
4d ago
+682-111

Linear AI generation runs (part of #4419; the quadratic from #5077, comment 6). Top of the GitHub stack on refactor/ai-plumbing: 3a (#5501) ← 3a-tidy (#5502) ← 3a-tests (#5503) ← this PR.

Problem

A run of N transactions takes about N/B Ai::GenerationJobs. Every one of them:

  • rebuilt the requester from every remaining id;
  • loaded and mapped every remaining row;
  • passed every remaining id to the next job.

Each job sent only one batch, but the run did O(N²/B) work in total and pushed O(N²/B) bytes through Redis. Measured with UUID ids and B = 25:

NPayload per jobRedis bytes, whole chain
10,000380 KB78 MB
100,0003.8 MB7.8 GB

Ai::Generation wasn't the cause. The analysis, and why ActiveJob::Continuable and RubyLLM Workbench don't fit, are in the plan doc: ai-generation-windowing.md.

What changes

flowchart LR
  R["Rule::ActionExecutor<br/>Enhancer.enhance_later"] -->|"ids, once"| S["Ai::GenerationRun.enqueue<br/>insert_all, positions 0..N-1"]
  S --> J["Ai::GenerationJob(feature,<br/>{ run_id, cursor, pending })"]
  J --> W["Window: pending, then<br/>chunks from the cursor"]
  W --> Q["requester's scope_for(chunk)<br/>until a batch's worth match"]
  Q --> G["Ai::Generation#call(batches: 1)<br/>unchanged"]
  G --> A["apply_ai over the window"]
  A -->|"more left"| N["perform_later(cursor:, pending: remaining_ids)"]
  A -->|"run exhausted"| F["ai_finished, then the run is deleted"]
  N --> J

The ids go into a table. ai_generation_runs has one row per run, and ai_generation_run_items holds (run_id, position, item_id).

  • Ai::GenerationRun.enqueue writes the ids once and queues the first job. If that job can't be queued, it deletes the run again.
  • Family#auto_*_later and ProviderMerchant::Enhancer.enhance_later call it.
  • A job carries run_id, cursor and pending, the batch's unanswered ids, at most one batch.

Each job reads one window. Ai::GenerationRun::Window yields the pending ids first, then chunks from the cursor. It stops once a batch's worth match the requester's scope. The first chunk is one batch's worth, and the chunk doubles after each one that comes back short, up to 500.

  • The batch size is Ai::Config#window_for, the largest batch_size among the feature's routes.
  • Ids that are already categorised, locked or gone are counted as handled.
  • A stretch where nothing matches is passed over within the same job.

Requesters filter only the ids they're given. In RuleRun::AiProgress, Family::AutoCategorizer and Family::AutoMerchantDetector:

  • scope becomes scope_for(ids).
  • Rows are loaded for the matching ids only, and the unused :category preload is gone.
  • apply_ai locks only the decided ids that belong to the window.
  • release_unhandled also releases the ids no job read, so a run that gives up halfway still brings transactions_awaiting_ai to 0.

The run is deleted when it ends. finish and give_up delete it once the requester has heard. A job whose run is gone is dropped, as one whose family is gone already was. DataCleanerJob sweeps runs older than a week.

The rest doesn't change. Ai::Generation, Ai::Batch, failover, escalation, token-budget splitting, the one-batch-per-job fairness and the retry policy all stay as they were. retry_on replays the same arguments, so it reads the same window.

Behaviour changes

  • Items reach the model in the order they were queued, not in database order.
  • The categoriser's "cache used" and "blocked by enrichment protection" debug logs are written once per window rather than once per run. They cover the same ids.
  • ai_failed logs the examined ids, plus outstanding_count.
  • The merchant enhancer takes its snapshot when the user clicks. Before, the first job took it. Logo backfill doesn't change website_url, so the only difference is merchants assigned between the click and the first job. They wait for the next click.
  • Ai::ShadowJob builds its requester with from_shadow_job(ids:, family_id:).

Upgrade: none needed. Ai::GenerationJob's ids: arguments exist only on the unreleased refactor/ai-plumbing, and 2c's upgrade note already covers jobs queued by main's old classes. That leaves no old-format job to forward.

The migration creates two tables. Per the repo rules, it isn't run automatically.

Verification

On feat/ai-3a-test-trim @ 4cee0be7e, Ruby 3.4.13, 2026-11-22:

  • test/architecture/ai_generation_linear_test.rb runs 200 and 2,000 transactions with a stubbed transport. Per job, both sizes load at most 88 records (the same number at 200 and at 2,000) and carry about 280 bytes. There are N/B jobs, every transaction is applied and the run's rows are gone at the end.

  • Benchmark (stubbed transport, B = 25, test database, one family):

    JobsMax records per jobMax payloadPer-job time, first → last decile
    Before, 2,000 transactions804,05778 KB272 → 164 ms (falls as the remaining list shrinks)
    After, 2,00080108282 B161 → 225 ms
    After, 10,000400108282 B209 → 273 ms (191 → 250 ms after ANALYZE)
    • The time per job doesn't grow with the size of the run. The residual drift comes from rows updated inside the benchmark's single test transaction.
    • The chunk doubling is there because of the benchmark. A version that always read 500 ids sometimes hit a bad plan for the categoriser's existing scope: a nested loop over index_entries_on_entryable_type, picked from near-empty planner stats. That took up to 9 s per job late in a 4,000-transaction run. Reading one batch's worth first keeps each match query small.
  • New tests:

    • Ai::GenerationRun and the window: insert slices, order, pending first, passing over a stretch that doesn't match, outstanding count, sweep, family cascade;
    • the job: cursor and pending in the next job, the retry reads the same window, a stray job, run deletion;
    • the categoriser: a rule run over several windows with locked and already-categorised transactions; giving up halfway releases what no job read;
    • the enhancer: the snapshot at the click.
  • Full bin/rails test: 18,407 runs, 2 failures. Both are in Account::ProviderImportAdapterTest and fail the same way on feat/ai-3a-test-trim without this PR. They are date-dependent and failed when the local and UTC dates differed (06:58 AEST).

  • AI_E2E=1 bin/rails test test/e2e/ai: 12 runs, 0 failures, against live models.

  • bin/rubocop, erb_lint --lint-all, Biome and Brakeman: clean.

  • The migration ran up, down and up again.

🤖 Generated with Claude Code


Summary by cubic

Makes AI generation runs linear: each job now reads a fixed-size window instead of every remaining item, so a run's work and Redis payload no longer grow quadratically with its size.

The ids a run works through are written once to two new tables (ai_generation_runs, ai_generation_run_items) when it's queued. Each Ai::GenerationJob carries just the run id, a position cursor, and the last batch's unanswered ids, and the run's window feeds it about one batch's worth of matching items. Requesters build from scope_for(ids) rather than loading every remaining row; already-categorized, locked, and gone items count as handled. A run is deleted once the requester reports the end, with DataCleanerJob sweeping runs no job has touched in a week.

Behavior changes

  • The merchant enhancer takes its snapshot of unenhanced merchants at the click, so merchants assigned before the first job runs wait for the next click.
  • Items reach the model in the order queued, not database order.
  • A run that gives up releases the ids no job read, so transactions_awaiting_ai still reaches zero; a window that raises partway releases what it read as well.
  • No upgrade needed; the old ids: job argument exists only on this unreleased stack.

Verification

  • Tests cover 200 and 2,000 transactions with a stubbed transport: per job, records load and payload bytes stay flat, every transaction applies, and the run's rows are gone.
  • A job naming another family's run is dropped without reading it, and each job touches its run so the sweep keeps a run that is still moving.
  • Ai::Generation, batching, failover, escalation, one-batch fairness, and the retry policy are unchanged; a retry replays the same arguments and reads the same window.
  • Migration creates the two tables and isn't run automatically.

Summary by CodeRabbit

  • New Features
    • AI-powered transaction categorization, merchant detection, and merchant enhancement now process large sets of items in batches, allowing work to continue across multiple background jobs.
  • Bug Fixes
    • Processing now focuses on items that still match the requested criteria, reducing unnecessary work when items change while a job is running.
    • Generation runs are cleaned up after completion or failure, and abandoned runs are removed automatically.