Skip to content

feat(exams): limit exam generation per user - #364

Open
fredygerman wants to merge 6 commits into
developmentfrom
feat/exam-generation-rate-limit
Open

fredygerman wants to merge 6 commits into
developmentfrom
feat/exam-generation-rate-limit

Conversation

@fredygerman

Copy link
Copy Markdown
Member

Summary

Adds a configurable per-user quota for NECTA exam generation.

Why

Exam generation is expensive. This caps successful generation per teacher while retaining an adjustable limit as usage patterns become clearer.

What Changed

  • Count a user's generated exams in PostgreSQL before retrieval or LLM work begins.
  • Block generation when the configured quota is reached.
  • Add EXAM_GENERATION_LIMIT and EXAM_GENERATION_WINDOW_DAYS, defaulting to 5 exams over 7 days.
  • Add database and tool-level tests for quota, time-window, and blocked-request behavior.

How To Test

  • Run:

    .venv/bin/pytest -q tests/database/test_generated_exam_count.py tests/tools/test_generate_exam_rate_limit.py tests/services/test_messaging_service.py tests/services/test_exam_delivery_service.py tests/tools/test_exam_generator.py

@fredygerman fredygerman self-assigned this Oct 16, 2026
@fredygerman fredygerman linked an issue Oct 16, 2026 that may be closed by this pull request
@fredygerman fredygerman changed the title Feat/exam generation rate limit feat(exams): limit exam generation per user Oct 16, 2026
@fredygerman
fredygerman requested a review from adricalm October 16, 2026 08:10
@jurmy24

jurmy24 commented Oct 16, 2026

Copy link
Copy Markdown
Member

Nice, note that when we raise funds (hopefully soon) we should raise these limits significantly.

@fredygerman

Copy link
Copy Markdown
Member Author

Nice, note that when we raise funds (hopefully soon) we should raise these limits significantly.

Of course, I think the default values are very low, so we can agree on the values to keep when deploying and when we get more funding.

@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Adds rate limiting to exam generation feature.

The PR appears safe to merge, with non-blocking improvements for shared quota enforcement and blocked-request notifications.

Findings

  1. P2 App instances can exceed quotas ▶
  2. P2 Blocked requests promise an exam ▶

Summary

Adds a configurable per-teacher exam quota, defaulting to five exams over seven days.

  • Exam requests stop when a teacher reaches the recent-generation limit.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Teacher requests an exam] --> B[Agent sends generation notice]
  B --> C[Count teacher's saved exams in the window]
  C --> D{Quota reached?}
  D -->|Yes| E[Return quota refusal]
  D -->|No| F[Retrieve content and generate exam]
  F --> G[Save exam]
  E --> H[Assistant replies to teacher]
  G --> I[Deliver exam and solution]
Loading

Reviews (1) · Last reviewed commit: "feat(exams): configure generation limits" · Reviewed by Greptile

Comment on lines +41 to +44
if (
await db.count_generated_exams_since(user_id, window_start)
>= settings.exam_generation_limit
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 App instances can exceed quotas

If two app instances share the database, both can see four completed exams, generate another, and save six against a limit of five. The quota check is separate from saving the exam, and the current per-user lock protects only one app process.

Add a shared per-user lock or reserve a slot before generation, releasing it on failure, so adding app instances does not weaken the quota.

Comment on lines +50 to +58
return json.dumps(
{
"status": "rate_limited",
"message": message,
"limit": settings.exam_generation_limit,
"window_days": settings.exam_generation_window_days,
},
ensure_ascii=False,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Blocked requests promise an exam

A teacher who reaches this branch has already received the notification promising an exam in around 10 minutes. AgentClient._observe sends that notification before calling the tool, so every blocked request first gets a false progress message.

Send the exam-start notification only after the quota check passes, and cover the quota refusal with a messaging test.

@Nuh0804

Nuh0804 commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

Hello Thanks for this, I would like to raise a few issues:

  1. Concurrent requests can get past the limit
    The check counts only exams that are already saved, and an exam is saved only after about 10 minutes of generation. Each WhatsApp message is a separate webhook request. The per-user lock in AgentClient holds back follow-up messages, but it lives in memory and only works within one process, so requests that reach different workers aren't blocked. A user at 4/5 who sends several requests close together can pass the check every time. In practice the limit is "5 plus whatever is in progress."
    Suggestion: reserve a slot before generating. One way is to insert a pending row first and mark it complete afterwards. Another is an atomic counter in Redis, which rate_limit_service already uses.

  2. A rate-limited user is first told to wait 10 minutes
    _observe sends the "📝 Generating a NECTA-style exam… takes around 10 minutes, please wait" notification before the tool runs. A user who is over the limit gets that message and then the rate-limit reply. Either do the limit check before the notification is sent, or change the notification wording.

Minor:

  1. The tool result shape doesn't match. Other tools return {"error": ...}, and tool_manager and resolve_delivery_marker both check for that key. This PR introduces status instead. The system prompt also doesn't tell the LLM what to do with rate_limited, so whether the message reaches the user as written depends on the model.

Nice to have: we can say when the user can try again (oldest exam in the window plus the window length) instead of just "later."
Happy to pair on the slot reservation.

@Nuh0804 Nuh0804 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this, and for the tests. I tested it with the branch merged into the latest development, EXAM_GENERATION_LIMIT=1, and a teacher with no previous exams (I checked generated_exams). The check itself fires: once the teacher had one exam, the next generation call was refused. But the way it was triggered is a serious failure, and the points from my earlier comment are still open.

0. Sync with development

No textual conflicts, but development has moved a lot since this branch was cut: #359 (conversational onboarding), #370 (local WhatsApp transport), #374 (model fallback) and #375 (log redaction). Please merge it in and rerun the tests.

1. A teacher's own exam counted against them and was never delivered (blocker)

Time What happened
21:44:11 Teacher asks for a Form 2 Geography exam on climate. The "around 10 minutes" notice is sent and the tool starts.
21:44:38 While waiting, the teacher sends "what is a map scale?". It is buffered.
21:51:37 Persisted generated exam. The agent writes "Your NECTA-style exam is ready" with the delivery marker.
21:51:41 New messages buffered during processing. Discarding response and reprocessing batch. The reply, and with it the PDF delivery, is thrown away.
21:51:59 The batch is rerun and the agent calls generate_necta_style_exam again. The count now includes the exam saved 20 s earlier: 1 ≥ 1.
21:52:05 After 8 minutes the teacher gets "I've reached the limit…". The exam is in the database but was never sent.

The discard-and-rerun is existing behaviour in AgentClient.generate_response on development, not something this PR added, and it needs its own fix. Without this PR it silently generates a second exam (about 7 more minutes and double the cost). With the limit, it becomes a refusal. Teachers will often send something during a 10-minute wait, so this will happen in production.

Suggested fix in this PR: make the tool safe to call again. Before counting, look for an exam this user generated for the same class, subject and topics in the last few minutes. If there is one, return it (the normal success payload with its exam_id) instead of generating again or refusing. That fixes the false refusal and the double generation whatever the agent does. Inline comment on the check.

2. Over-limit teachers are first told to wait 10 minutes (still open)

AgentClient._observe sends the "takes around 10 minutes" notice before the tool runs, so a teacher over the limit is told to wait and then refused. Either run the limit check before the notice is sent, or reword the notice.

3. The quota can be exceeded with requests close together (still open)

The count only sees exams that are already saved, and saving happens about 10 minutes after the check. Requests close together, or handled by different workers, all pass. Reserving a slot before generating (a pending row, or a Redis counter like rate_limit_service) would fix this, and would also give point 1 a natural "same request" key.

4. Result shape and wording (minor)

Inline comments.

Comment on lines +38 to +44
window_start = datetime.now(timezone.utc) - timedelta(
days=settings.exam_generation_window_days
)
if (
await db.count_generated_exams_since(user_id, window_start)
>= settings.exam_generation_limit
):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Point 1: make a repeated call return the existing exam. In my test this check counted the teacher's own exam from 20 seconds earlier. The agent had rerun the turn after a new message arrived, so the first result was never delivered.

Rough idea:

recent = await db.get_recent_generated_exam(
    user_id, class_id, subject, topics, since=now - timedelta(minutes=30)
)
if recent:
    return json.dumps({...success payload..., "exam_id": recent.id})

Please add a test where the tool runs twice with the same arguments and generates only one exam.

days=settings.exam_generation_window_days
)
if (
await db.count_generated_exams_since(user_id, window_start)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Point 3: this counts only exams that are already saved, and saving happens about 10 minutes later. Two requests close together, or on different workers, both see the same count and both generate. Reserving a slot here (a pending generated_exams row, or a Redis INCR with expiry like rate_limit_service) and releasing it on failure would close the gap.

Comment on lines +50 to +58
return json.dumps(
{
"status": "rate_limited",
"message": message,
"limit": settings.exam_generation_limit,
"window_days": settings.exam_generation_window_days,
},
ensure_ascii=False,
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Other tools return {"error": ...}, and both tool_manager and resolve_delivery_marker check for that key. status: rate_limited is new, and the system prompt doesn't say what to do with it. In my test the agent reworded the refusal as "I've reached the limit for generating full exam papers this week", which is wrong because the window is a rolling 7 days. Suggest returning {"error": message, ...} with the exact text to relay, plus the date the teacher can try again.

Comment thread app/assets/strings/english.yml Outdated
notification: "📑 Generating exercises from the course content, please hold..."
generate_necta_style_exam:
notification: "📝 Generating a NECTA-style exam. This takes around 10 minutes, so please be patient and wait for the message with your exam and solution."
rate_limited: "You have reached the limit of {limit} generated exams in {window_days} days. Please try again later."

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice to have: say when the teacher can try again instead of "later". The date is the oldest exam in the window plus window_days, e.g. "You can generate a new exam from {next_available_date}."

A repeated call for the same exam (e.g. after the agent reruns a turn)
counted the teacher's own fresh exam and was refused. Requests close
together could also all pass the count before any exam was saved.

- Add exam_generation_reservations: a slot is reserved before
  generation, completed when the exam is saved, failed on error.
- Reserve under a per-user advisory lock, in one transaction.
- The same request completed within EXAM_REUSE_WINDOW_MINUTES returns
  that exam; one still pending returns "still being prepared".
- Pending slots stop counting after EXAM_RESERVATION_TIMEOUT_MINUTES.
The exam notice was sent before the limit check, so a teacher over the
limit was told to wait 10 minutes and then refused at once.

- Add optional tool preflights (TOOL_PREFLIGHT_MAP). AgentClient runs
  them before notifying; a call a preflight answers gets no notice and
  its tool does not run.
- The exam preflight uses a read-only preview of the reservation check:
  limit reached, same exam in progress, or same exam to reuse.
- reserve() stays the authoritative check; a failing preflight is
  logged and the tool runs as usual.
The limit result used its own {"status": "rate_limited"} shape and gave
no retry date, and the agent reworded it (e.g. "this week").

- Return {"error", "error_code": "exam_limit_reached", "limit",
  "window_days", "next_available_at"}, like the other error results.
- next_available_at is when the oldest counted slot leaves the window,
  shown to the teacher in East Africa Time.
- Tell the agent, in the tool description, to reply with the error text
  as written when error_code is set, and not to retry.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Your trial has ended. Reactivate Greptile to resume code reviews.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rate Limit Users on the Exam Generation Tool

3 participants