Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(quiz): weight generation toward an approaching exam (#555) by AndresL230 · Pull Request #573 · SaplingLearn/Sapling · GitHub
Skip to content

feat(quiz): weight generation toward an approaching exam (#555) - #573

Merged
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity
Aug 22, 2026
Merged

feat(quiz): weight generation toward an approaching exam (#555)#573
AndresL230 merged 2 commits into
mainfrom
feat/555-exam-proximity

Conversation

@AndresL230

Copy link
Copy Markdown
Collaborator

Closes#555. Workstream H3 of epic #537.

assignments.due_date is plaintext and indexed, and nothing anywhere computed "exam in N days" — so a quiz taken the night before a midterm was generated exactly like one taken in week two.

Dates only

No grade value is read, stored, or prompted on this path. Proximity is a property of the calendar, not of performance; the points columns are encrypted (#521) and nothing here selects them. The audit flags that the current ToS and privacy policy don't clearly cover feeding grades to a model — this feature doesn't need to test that boundary, so it doesn't.

The heuristic is extracted, not re-written

As the issue asks. services/exam_proximity.py::is_exam is now the single definition and routes/study_guide.py calls it. A second copy would drift — which is the failure #557 spent a workstream undoing, one issue earlier in this same workstream.

Shape of the answer

  • 0 means the exam is TODAY, and is deliberately distinct from None ("no upcoming exam, or we couldn't tell"). Collapsing them — or writing if exam_days_away: — drops the single most actionable value the feature produces. Pinned by test on both the prompt string and the stored row.
  • Resolved once per generation, then both prompted and stored. Computing it twice could report one number to the model and a different one to the analytics row if an exam were entered between the reads.
  • min() over upcoming exams, not "first row of a due_date.asc query". The ordering is requested, but relying on it makes the answer wrong-and-silent if it's ever dropped or degraded, and the minimum costs nothing here.
  • Never raises. It runs inline on the generation path; one optional prompt line is not worth failing a generation over.

The prompt line

States the deadline and lets the model decide what it implies. It deliberately does not say "make it harder" — that would contradict the difficulty the student actually chose, and adaptive mode already owns that decision. When proximity is unknown the line is omitted entirely rather than spending tokens to say "unknown".

Migration

20260822090747 adds a nullable exam_days_away to quiz_attempts, because the issue's point is to be able to ask later whether deadline-aware quizzes perform differently — a value that only reached a prompt leaves nothing to measure.

No DEFAULT: 0 would make every legacy row and every unknown look like exam day.

Applied to staging and verified before this code shipsinteger, is_nullable = YES, no default, 2 existing rows NULL. The write omits the key when unknown (mirroring apply_graph_update's rule), so an environment that takes the code first keeps generating instead of 400ing on a column PostgREST's schema cache doesn't have.

Verification

Hermetic 2200 passed / 9 skipped, ruff clean, oracles 0 findings, integration 56 passed, Playwright 46 passed.

Two failures, neither from this PR: landing-drag-field.spec.ts:332 (#566, red on main, fixed by #568) and gradebook.spec.ts:35 (#569, the intermittent — 0 failures across 4 clean-main full-suite runs and 6 isolated runs).

🤖 Generated with Claude Code

`assignments.due_date` is plaintext and indexed, and nothing anywhere
computed "exam in N days" — so a quiz taken the night before a midterm was
generated exactly like one taken in week two.
**Dates only.** No grade VALUE is read, stored or prompted on this path.
Proximity is a property of the calendar, not of performance; the points
columns are encrypted (#521) and this code never selects them. The audit
flags that the current ToS and privacy policy don't clearly cover feeding
grades to a model, and this feature does not need to test that.
The exam heuristic is EXTRACTED rather than re-implemented, as the issue
asks: `services/exam_proximity.py::is_exam` is now the single definition and
`routes/study_guide.py` calls it. Writing a second copy is the failure #557
spent a workstream undoing, one issue earlier in this same workstream.
Shape of the answer:
* `0` means the exam is TODAY and is deliberately distinct from `None`
("no upcoming exam, or we could not tell"). Collapsing them — or writing
`if exam_days_away:` — drops the single most actionable value the feature
produces. Pinned by test on both the prompt and the stored row.
* Resolved ONCE per generation and then both prompted and stored: computing
it twice could report one number to the model and a different one to the
analytics row if an exam were entered between the reads.
* `min()` over the upcoming exams rather than "first row of a due_date.asc
query" — the ordering is asked for, but relying on it makes the answer
wrong-and-silent if it is ever dropped or degraded, and the minimum costs
nothing to compute here.
* Never raises: it runs inline on the generation path, and one optional
prompt line is not worth failing a generation over.
The prompt line states the deadline and lets the model decide what it
implies. It deliberately does NOT say "make it harder" — that would
contradict the difficulty the student actually chose, and adaptive mode
already owns that decision. When proximity is unknown the line is omitted
entirely, rather than spending tokens to say "unknown".
Migration `20260822090747` adds a nullable `exam_days_away` to
`quiz_attempts`, because the issue's point is to be able to ASK LATER whether
deadline-aware quizzes perform differently — a value that only reached a
prompt leaves nothing to measure. No DEFAULT: `0` would make every legacy row
look like exam day. Applied to staging and verified before this code ships
(nullable, no default, 2 existing rows NULL); the write omits the key when
unknown, so an environment that takes the code first keeps generating.
Hermetic 2200 passed / 9 skipped, ruff clean.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pagesBot commented Aug 22, 2026

Copy link
Copy Markdown

Deploying with Cloudflare Workers Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

StatusNameLatest CommitPreview URLUpdated (UTC)
✅ Deployment successful!
View logs
frontend-staging47d5555Commit Preview URL

Branch Preview URL
Aug 22 2026, 09:26 AM

@supabase

supabaseBot commented Aug 22, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project ybgqdonkoqftwrmweuyv because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

Comment threadbackend/tests/test_exam_proximity.py Fixed
@coderabbitai

coderabbitaiBot commented Aug 22, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@AndresL230, you've reached your PR review limit, so we couldn't start this review.

Next review available in:3 minutes

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

Wait for the limit to reset, then comment @coderabbitai review or push new commits to the PR.

An organization admin can change what happens after included review limits in Billing.

How do review limits work?

CodeRabbit enforces per-developer PR review limits within each organization.

For paid Pro and Pro+ reviews, CodeRabbit uses a developer's included PR review attempts over the past 7 days to set the current hourly allowance. At typical activity levels, the full plan allowance applies. Higher sustained activity can lower the allowance until earlier attempts leave the 7-day window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 7be65e6e-d910-4ed9-9433-f3d34991f6e4

📥 Commits

Reviewing files that changed from the base of the PR and between e139954 and 47d5555.

📒 Files selected for processing (6)
  • backend/db/migrations/20260822090747_quiz_attempts_exam_days_away.sql
  • backend/routes/quiz.py
  • backend/routes/study_guide.py
  • backend/scripts/benchmark_quiz.py
  • backend/services/exam_proximity.py
  • backend/tests/test_exam_proximity.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

CI was red: I ran `ruff check` BEFORE adding the wiring tests and reported it
clean in the previous commit message. Three violations in the new test file
(two dead imports and an unused `Quiz`); the repeated agent-run construction
is hoisted into a helper rather than rebuilt per test.
**The heuristic was too loose for a decision.** `is_exam` was written for a
user-visible picker, where a false positive costs one extra row. Reused
verbatim it drove a prompt AND `quiz_attempts.exam_days_away` — so a course
with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester,
and "Final draft - essay 2" is a final. That poisons the exact question the
column exists to answer, because the treatment group becomes "any course with
weekly quizzes". Added `is_exam_strict` for the decision path: no "quiz"
keyword, word-anchored matching, `assignment_type == "exam"` still wins. The
picker keeps the loose form, which is right for a list.
**No proximity horizon.** A final dated 87 days out put "there is an exam
coming, weight toward what an exam tests" on EVERY quiz for the semester —
no proximity signal, and it steers week-two practice toward exam questions,
which is what the code comment claims to be avoiding. The prompt line is now
bounded by `PROMPT_HORIZON_DAYS`; the stored column is deliberately NOT
clamped, because the analytics want the real distance.
**Four serial round-trips, fully additive, outside the safety net.** The
lookup ran before the try block and before the existing gather, so its
latency added to every generation and a failure there consumed a rate-limit
slot with no refund. It is now the third leg of the gather that already runs
grounding and the recently-asked read concurrently — it is best-effort
context exactly like those two. `_quiz_via_agent` returns a `GeneratedQuiz`
so the value it used for the prompt is the one stored on the attempt, rather
than being resolved twice.
**The attempt insert could 500 a quiz that already ran.** Omit-when-None does
not make a pre-migration environment safe: it protects the no-exam case and
breaks precisely the students the feature is for, so it presents as a random
partial outage. And it lands after the agent has been billed — quiz lost, no
attempt row, no `quiz.generation_failed`, no refund. `_insert_attempt` retries
once without the key and re-raises anything else, so a genuine write failure
still surfaces.
Also: UTC (`_today` was naive local time, a day out from study_guide/calendar
on any non-UTC deployment, and off-by-one for the analytics); `datetime`
checked before `date` in `_parse_date` (datetime subclasses date, so the
obvious order returned it unconverted and the later subtraction raised into
the outer catch, silently degrading the lookup); enrollment resolution via
`services/academics.py::user_enrollment_ids`, which CLAUDE.md names as its
single home and which had already read those rows a line earlier.
Hermetic 2207 passed / 9 skipped, ruff clean — verified after the tests, this
time.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@AndresL230

Copy link
Copy Markdown
CollaboratorAuthor

Review round — eight findings, all fixed in 47d5555d

Starting with the one that was my fault twice over: CI was red and my "ruff clean" claim was stale. I ran ruff checkbefore adding the wiring tests and then reported it clean in the commit message. Three violations in the new test file. Fixed, and the repeated agent-run construction is hoisted rather than rebuilt per test.

Two findings changed behaviour materially:

The heuristic was too loose for a decision.is_exam was written for a user-visible picker, where a false positive costs the student one extra row to look at. Reused verbatim, it drove a prompt andquiz_attempts.exam_days_away — so a course with weekly "Quiz 3"/"Quiz 4" rows has an "exam" within a week all semester, and "Final draft — essay 2" is a final. That poisons the exact question the column exists to answer, because the treatment group for "do deadline-aware quizzes perform differently?" silently becomes "any course with weekly quizzes". Added is_exam_strict for the decision path (no quiz keyword, word-anchored, assignment_type == "exam" still wins); the picker keeps the loose form, which is correct for a list.

No proximity horizon. A final dated 87 days out put "there is an exam coming, weight toward what an exam tests" on every quiz for the whole semester — no proximity signal at all, and it steers week-two practice toward exam-style questions, which is what my own comment claimed to be avoiding. The prompt line is bounded by PROMPT_HORIZON_DAYS now; the stored column is deliberately not clamped, because the analytics want the real distance.

The rest:

  • Four serial round-trips, fully additive, outside the safety net. The lookup ran before the try block and before the existing gather, so its latency added to every generation and a failure there consumed a rate-limit slot with no refund. It's now the third leg of the gather that already runs grounding and the recently-asked read concurrently — it is best-effort context exactly like those two. _quiz_via_agent returns a GeneratedQuiz so the value used for the prompt is the one stored on the attempt, rather than resolved twice.
  • The attempt insert could 500 a quiz that already ran. Omit-when-None does not make a pre-migration environment safe — it protects the no-exam case and breaks precisely the students the feature is for, so it presents as a random partial outage. And it lands after the agent has been billed: quiz lost, no attempt row, no quiz.generation_failed, no refund. _insert_attempt retries once without the key, and re-raises anything else so a genuine write failure still surfaces.
  • UTC._today was naive local time — a day out from study_guide/calendar on any non-UTC deployment, and off-by-one for the analytics.
  • datetime before date in _parse_date: datetime subclasses date, so the obvious order returned it unconverted and the later subtraction raised into the outer catch, silently degrading the lookup to None.
  • Enrollment resolution through services/academics.py, which CLAUDE.md names as its single home — and which had already read those rows one line earlier.

Also fixed the return-type ripple the review didn't flag: scripts/benchmark_quiz.py returned _quiz_via_agent(...) straight through to a list[dict] caller, which a NamedTuple would have broken silently — no test covers that offline script.

Verification

Hermetic 2207 passed / 9 skipped, ruff clean (verified after the tests this time), oracles 0 findings, integration 56 passed, Playwright 47 passed — the one failure is #566, fixed by #568. CI green.

@AndresL230
AndresL230 merged commit 8626903 into mainAug 22, 2026
7 checks passed
Sign up for freeto 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.

quiz H3: exam proximity from assignments.due_date (dates only, no grade values)

1 participant

@AndresL230