Skip to content

Add background job for ai hint request - #1135

Merged
cocomarine merged 11 commits into
mainfrom
1932-add-background-job-for-AiHint-request
Nov 30, 2026
Merged

cocomarine merged 11 commits into
mainfrom
1932-add-background-job-for-AiHint-request

Conversation

@cocomarine

@cocomarine cocomarine commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Status

Moves AI hint generation off the request thread.
editor-ui PR: RaspberryPiFoundation/editor-ui#1790
The client creates a hint, gets an ID straight away, and polls until the hint is ready.

Performance considerations

  • Web threads aren't blocked. The inference call can take up to 15s, and it now runs in the background, so POST /api/ai_hints returns 202 straight away.
  • AI hints have their own queue. The ai_hints queue runs up to 5 jobs at a time. A burst of hint requests can't hold up other jobs and vice versa.
  • Hints that are already too late fail straight away. If a hint has waited more than 15s in the queue, the job marks it failed without calling inference. This avoids spending inference calls on hints the client will never collect.
  • The worker has a bigger DB pool. The GoodJob queues add up to 22 threads, so the worker now sets DB_POOL=25 to stop threads waiting for a connection. Web dynos keep using RAILS_MAX_THREADS.
  • Polling is cheap. GET /api/ai_hints/:id reads one row by primary key and returns only status and hint.
  • Rows stay small. input, which can be up to 100 KB, is cleared once a hint completes or fails.
  • Staging connection limits: staging's main DB allows only 20 connections, compared with 200 in production, so the worker's pool and thread counts are now configurable per app:
    • Staging, with WORKER_DB_POOL=8 set (see below TODO before merging section), gets DB_POOL=8
      • 2 Puma x 5 + spare (2) -> 8 left for the worker out of total 20
    • Production, with it not set, gets DB_POOL=25

🤖 Generated with help of Claude Code

What's changed?

  • AiHint model and migration:
    • Has user_id, input, status (pending / completed / failed) and hint. input is cleared once the hint completes or fails.
  • Api::AiHintsController:
    • POST /api/ai_hints validates the payload (requires message, trace, runtime and code; 100 KB max), creates a pending hint, queues the job and returns 202 with the id.
    • GET /api/ai_hints/:id returns status and hint, only for the hint's owner.
    • Both are behind the feature flag.
  • GenerateAiHintJob runs on a new ai_hints GoodJob queue with 5 threads. It calls FriendlyErrorMessagesInferenceClient and marks the hint completed or failed.
  • A hint that waited more than 15s in the queue is failed straight away: editor-ui polls for about 30s and inference can take up to 15s, so it couldn't finish in time.
  • DB pool: database.yml now reads DB_POOL first and falls back to RAILS_MAX_THREADS. The worker in the Procfile sets DB_POOL=25 so the extra queue threads don't run out of connections.
  • Added weekly cleanup job for old AI hints.

Relationship to existing FriendlyErrorMessagesController

  • Its endpoint POST /api/friendly_error_messages stays as it is in this PR.
  • The new AiHintsController for the similar job of running the inference in the background will eventually replace it.
  • Both endpoints stay live until editor-ui has switched over to the new endpoints. After that, we should remove the existing controller and its routes and specs.

TODO before merging

  • Add these to the config_vars map in terraform.tfvars:
  ...
  WORKER_DB_POOL               = "8"
  GOOD_JOB_QUEUES              = "create_students_job:1;import_schools_job:1;salesforce_sync:2;default:1;ai_hints:2"
  ...

Steps to perform after deploying to production

  • 🏃‍♀️ Runs a migration (create_ai_hints).
  • 🛻 Needs the worker dyno to restart to pick up DB_POOL and the new queue.
  • 🧹 Once editor-ui has switched over to use new routes, remove FriendlyErrorMessagesController and its routes and specs.

Clearing input when either sucessfully completed or failed getting Ai hint.
This controller will replace the existing controller, FriendlyErrorMessagesController, once polling is enabled in editor-ui and deployed.
@cla-bot cla-bot Bot added the cla-signed label Nov 24, 2026
Comment thread app/jobs/generate_ai_hint_job.rb Fixed
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Test coverage

94.23% line coverage reported by SimpleCov.
Run: https://github.com/RaspberryPiFoundation/editor-api/actions/runs/45866818248

@cocomarine
cocomarine temporarily deployed to editor-api-p-1932-add-b-guix33 November 26, 2026 11:21 Inactive
Comment thread app/jobs/generate_ai_hint_job.rb Dismissed
@cocomarine
cocomarine marked this pull request as ready for review November 26, 2026 11:48
@macroscopeapp

macroscopeapp Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Approvability

Verdict: Needs Human Approval

Macroscope's review found this PR requires human approval — The new AI-hint flow is feature-gated and clears processed inputs, but also changes shared worker concurrency and database pooling. Confirm deployed connection headroom and overrides, plus the intended retention policy for newly persisted code/error inputs.

Needs human approval because:

  • approvability is in preview mode for this repository, so Macroscope does not approve PRs here

You can add or adjust custom eligibility rules. Learn more.

@cocomarine
cocomarine temporarily deployed to editor-api-p-1932-add-b-guix33 November 26, 2026 12:53 Inactive
@cocomarine
cocomarine temporarily deployed to editor-api-p-1932-add-b-guix33 November 26, 2026 12:53 Inactive
Comment thread config/initializers/good_job.rb Resolved
Comment thread app/jobs/generate_ai_hint_job.rb Resolved

@zetter-rpf zetter-rpf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Run below script:
heroku config:set -a editor-api-staging
WORKER_DB_POOL=8
GOOD_JOB_QUEUES='create_students_job:1;import_schools_job:1;salesforce_sync:2;default:1;ai_hints:2'

We normally configure env vars using terraform

@zetter-rpf

Copy link
Copy Markdown
Contributor

We need to make a decision on how long hints are kept: assuming that this table won't be used for other use (such as event tracking, quality checks etc.), perhaps we can set a cron job to clean up the table regularly.

That's a good idea since we have separate logging in place and don't need to keep them. Maybe we have a weekly job that runs with Good Job cron that deletes hint rows older than a day?

@zetter-rpf zetter-rpf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice one, I've added a couple of suggestions

@adrian-rpf

Copy link
Copy Markdown
Contributor

@cocomarine please can you put extra steps also into #1995

@cocomarine
cocomarine temporarily deployed to editor-api-p-1932-add-b-guix33 November 26, 2026 16:51 Inactive
@cocomarine
cocomarine temporarily deployed to editor-api-p-1932-add-b-guix33 November 26, 2026 17:20 Inactive
@cocomarine
cocomarine merged commit 79ac4a0 into main Nov 30, 2026
10 checks passed
@cocomarine
cocomarine deleted the 1932-add-background-job-for-AiHint-request branch November 30, 2026 10:43
cocomarine added a commit to RaspberryPiFoundation/editor-ui that referenced this pull request Nov 30, 2026
> [!WARNING]  
> Merge after [the editor-api
PR](RaspberryPiFoundation/editor-api#1135) is
merged.


## Status

- Part of
RaspberryPiFoundation/digital-editor-issues#1932
- Depends on
RaspberryPiFoundation/editor-api#1135 (must be
merged first)


Switches AI hints to the new async endpoints. The client creates a hint,
then polls until it's ready, instead of holding one request open while
inference runs.

## What's changed?

- Added new endpoints `createAiHint` (`POST /api/ai_hints`) and
`getAiHint` (`GET /api/ai_hints/:id`), each with a 5s timeout, and
removes `getAiErrorHint`.
- Added `pollAiHint` helper:
- Polls every 1s for up to 30s, in step with [`MAX_QUEUE_WAIT` in
editor-api](https://github.com/RaspberryPiFoundation/editor-api/pull/1135/changes#diff-08d4a8b75698c6d53065036fc5ea482e3e12bf9125b38829a5aef5d451ba3969).
- Resolves with the hint, or rejects with an `AiHintPollError` whose
`reason` is `failed`, `timeout` or `aborted`.
- A 4xx client error fails straight away whereas network errors and 5xx
are retried.
- `AiErrorMessage`:
- Uses create-and-poll. It's aborted when the error changes or the
component unmounts, so polling stops instead of carrying on in the
background.

This branch was previously deployed

1 inactive deployment
editor-api-p-1932-add-b-guix33 — 84b6c6cf Deployed Nov 26, 2026 by cocomarine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants