Repository navigation
feat(exams): limit exam generation per user - #364
fredygerman wants to merge 6 commits into
Conversation
|
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. |
[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. FindingsSummaryAdds a configurable per-teacher exam quota, defaulting to five exams over seven days.
|
| if ( | ||
| await db.count_generated_exams_since(user_id, window_start) | ||
| >= settings.exam_generation_limit | ||
| ): |
There was a problem hiding this comment.
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.
| return json.dumps( | ||
| { | ||
| "status": "rate_limited", | ||
| "message": message, | ||
| "limit": settings.exam_generation_limit, | ||
| "window_days": settings.exam_generation_window_days, | ||
| }, | ||
| ensure_ascii=False, | ||
| ) |
There was a problem hiding this comment.
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.
|
Hello Thanks for this, I would like to raise a few issues:
Minor:
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." |
Nuh0804
left a comment
There was a problem hiding this comment.
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.
| 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 | ||
| ): |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
| return json.dumps( | ||
| { | ||
| "status": "rate_limited", | ||
| "message": message, | ||
| "limit": settings.exam_generation_limit, | ||
| "window_days": settings.exam_generation_window_days, | ||
| }, | ||
| ensure_ascii=False, | ||
| ) |
There was a problem hiding this comment.
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.
| 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." |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Your trial has ended. Reactivate Greptile to resume code reviews.
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
EXAM_GENERATION_LIMITandEXAM_GENERATION_WINDOW_DAYS, defaulting to 5 exams over 7 days.How To Test
Run: