forge
Explore
Log in

Don't you dare go Hollow

Draft exams hidden until published

Browse files at this commit

d8fdbf0513a6b37ad98d8df259b42620e3d48e4fAhmet Kaan GümüşParent: 73d4367
  • feat
    • draft exams hidden until published
Show full message
✨ feat(exams): draft exams hidden until published

Exam prep is long work: draft: true keeps an exam private to its
course's managers while it's written. Students get 404s (not 403/409 —
existence must not leak) on get/attempt/ws and filtered lists; sitting
and grading are blocked. Publish via PATCH draft: false; re-drafting is
409 once attempts or results exist. grade now holds an EXAM_LOCK read
lease so a mark can't race a re-draft. Modeless exams renamed
offline-graded/unscheduled everywhere — "draft" now means only this.
Old rows backfill published at boot.
README.mdmodified+31 -17
@@ -30,7 +30,9 @@ fixed window), **async** (start anytime inside the window, with a personal
30 time budget), or **open** (sit anytime, optionally timed per attempt);30 time budget), or **open** (sit anytime, optionally timed per attempt);
31 students *sit* them via attempts — retakes metered by a per-exam limit31 students *sit* them via attempts — retakes metered by a per-exam limit
32 (`0` = unlimited), leaving the exam room governed by a teacher-controlled32 (`0` = unlimited), leaving the exam room governed by a teacher-controlled
33-rejoin door. Questions can carry **images**: any question may hold one33+rejoin door. Writing an exam takes a while, so it can be saved as a
34+**draft** — invisible to students, unsittable, ungradable — and published
35+when it's ready. Questions can carry **images**: any question may hold one
34 illustration (a map above the prompt), and each option of a choice question36 illustration (a map above the prompt), and each option of a choice question
35 may be a picture of its own (pick the right city off the map) — raster37 may be a picture of its own (pick the right city off the map) — raster
36 uploads capped by the same `max_file_bytes` policy as note files. Teachers38 uploads capped by the same `max_file_bytes` policy as note files. Teachers
@@ -203,7 +205,7 @@ effect on the user's very next call (no re-login).
203 | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` |205 | View **any** user's pomodoro log | teacher | Study oversight — same shape as `/pomodoro/me`, incl. the unpaged `total_focus_ms` |
204 | Read **own** attendance report | student | |206 | Read **own** attendance report | student | |
205 | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all |207 | Read another user's attendance report | teacher | Narrowed to the caller's managed courses; `manager`+ sees all |
206-| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all) |208+| View **visible** courses/exams and a course's subjects; read **own** result, courses, mark report | student | Visible = enrolled (teachers: + created; `manager`+: all); exam **drafts** show only to the course's managers |
207 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |209 | Sit a sittable exam (`sync`/`async`/`open`): start / resume / retake / read / submit **own** attempt | student | **Students only** — staff never sit; must be enrolled; window (where one exists) and `max_attempts` enforced by the server |
208 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |210 | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off |
209 | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |211 | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt |
@@ -344,13 +346,13 @@ their existing shapes: the student exam-room reads
344 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |346 | POST | `/sessions/{id}/attendance` | teacher | `{status, user_id}` — roll call: session teacher/course manager mark **enrolled students** (students only); the teacher's own row needs manager+ |
345 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |347 | GET | `/sessions/{id}/attendance` | teacher | List the session's roll call (session teacher or course manager) · paged |
346 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |348 | DELETE | `/sessions/{id}/attendance/{user}` | teacher | Remove a roll-call row (same rights as marking) |
347-| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?}` — add an exam (course manager); its weight comes from the kind |349+| POST | `/courses/{id}/exams` | teacher | `{title, description?, kind, mode?, starts_at?, ends_at?, duration_ms?, max_attempts?, allow_rejoin?, draft?}` — add an exam (course manager); its weight comes from the kind; `draft: true` keeps it hidden while it's written |
348-| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+) · paged |350+| GET | `/courses/{id}/exams` | student | List the course's exams (enrolled, creator, or manager+; drafts appear to course managers only) · paged |
349-| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all) · paged |351+| GET | `/exams` | student | The caller's visible exams: their courses' (manager+: all; drafts of managed courses only) · paged |
350-| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+) |352+| GET | `/exams/{id}` | student | Get exam (enrolled, creator, or manager+; a draft is a `404` for everyone but its course's managers) |
351-| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin` (course manager; `course` immutable, `mode` frozen once attempted — the rest stays live) |353+| PATCH | `/exams/{id}` | teacher | Edit exam incl. `kind` (re-weights it), schedule, `max_attempts`, `allow_rejoin`, `draft` (course manager; `course` immutable, `mode` frozen once attempted, re-drafting frozen once attempts/results exist — the rest stays live) |
352 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question images (course manager) |354 | DELETE | `/exams/{id}` | teacher | Delete exam + its results, attempts, questions, answers, and question images (course manager) |
353-| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only) |355+| POST | `/exams/{id}/results` | teacher | `{mark, user_id}` — grade an **enrolled student** (upsert; course manager; students only; drafts can't be graded, `409`) |
354 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |356 | GET | `/exams/{id}/results` | teacher | List every result for the exam (course manager) · paged |
355 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |357 | GET | `/exams/{id}/result` | student | The caller's **own** result (`404` until graded) |
356 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |358 | DELETE | `/exams/{id}/results/{user}` | teacher | Remove a student's result (course manager) |
@@ -535,10 +537,21 @@ keeps every school's data physically isolated.
535 537
536 ## Exam modes, attempts, retakes, rejoin & live monitoring538 ## Exam modes, attempts, retakes, rejoin & live monitoring
537 539
538-An exam is a **draft** by default (all schedule fields `null`) — graded540+Preparing an exam is slow work, so an exam can be created as a **draft**
539-offline; attempts on it are a `409` ("nothing to sit"). Making it sittable541+(`draft: true`): only the course's managers see it (to students it's a `404`
540-means giving it a `mode`, as one consistent unit (validated together on542+that might as well not exist — lists, direct reads, and attempts all hide
541-create and after every `PATCH` merge):543+it), nobody can sit it, and grading it is a `409`. The teacher builds the
544+questions in peace and publishes with `PATCH /exams/{id}` `{"draft": false}`.
545+An exam can go back into hiding the same way — but only while it has **no
546+attempts and no results**; after that, re-drafting is a `409` (students never
547+lose sight of an exam they've sat or been graded on). Existing exams (and
548+those created without the flag) are published from the start.
549+
550+Separately from drafts, a published exam without a `mode` (all schedule
551+fields `null`) is **offline-graded** — a paper exam whose marks are entered
552+by hand; students see it and their marks, but attempts on it are a `409`
553+("nothing to sit"). Making an exam sittable means giving it a `mode`, as one
554+consistent unit (validated together on create and after every `PATCH` merge):
542 555
543 - `mode: "sync"` + `starts_at` + `ends_at` — everyone sits inside one window;556 - `mode: "sync"` + `starts_at` + `ends_at` — everyone sits inside one window;
544 every attempt's deadline is `ends_at`.557 every attempt's deadline is `ends_at`.
@@ -587,8 +600,8 @@ construction):
587 Deadlines are **recomputed from the exam's current schedule on every read**,600 Deadlines are **recomputed from the exam's current schedule on every read**,
588 never stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)601 never stored: a teacher who `PATCH`es `ends_at` (or a `duration_ms`)
589 while the exam runs moves every running deadline instantly. What's frozen once602 while the exam runs moves every running deadline instantly. What's frozen once
590-anyone has started is only `mode` (including back to a draft) — swapping the603+anyone has started is only `mode` (including back to unscheduled) — swapping
591-deadline rules mid-sitting would be a different exam (`409`).604+the deadline rules mid-sitting would be a different exam (`409`).
592 605
593 The course's manager (its creator, or manager+) watches it all live:606 The course's manager (its creator, or manager+) watches it all live:
594 `GET /exams/{id}/live` returns one snapshot —607 `GET /exams/{id}/live` returns one snapshot —
@@ -707,9 +720,10 @@ suggestion to read while grading, never written anywhere.
707 720
708 **The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed721 **The exam room (WebSocket)** — `GET /exams/{id}/attempt/ws`, cookie-authed
709 like everything else; REST above remains the full fallback. Gates run before722 like everything else; REST above remains the full fallback. Gates run before
710-the upgrade: unknown exam `404`, draft with no mode `409`, not a student `403`,723+the upgrade: unknown or draft exam `404`, unscheduled (no mode) `409`, not a
711-not enrolled `403`, no attempt yet `404` (start it first), submitted/expired724+student `403`, not enrolled `403`, no attempt yet `404` (start it first),
712-`409`, left while rejoin is closed `409`. Then JSON text frames:725+submitted/expired `409`, left while rejoin is closed `409`. Then JSON text
726+frames:
713 727
714 | direction | frame |728 | direction | frame |
715 |-----------|-------|729 |-----------|-------|
src/database.rsmodified+5 -0
@@ -169,6 +169,7 @@ const MIGRATION: &str = "
169 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;169 DEFINE FIELD IF NOT EXISTS duration_ms ON exam TYPE option<int>;
170 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;170 DEFINE FIELD IF NOT EXISTS max_attempts ON exam TYPE int DEFAULT 1;
171 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;171 DEFINE FIELD IF NOT EXISTS allow_rejoin ON exam TYPE bool DEFAULT true;
172+ DEFINE FIELD IF NOT EXISTS draft ON exam TYPE bool DEFAULT false;
172 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;173 DEFINE INDEX IF NOT EXISTS exam_course ON exam FIELDS course;
173 174
174 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;175 DEFINE TABLE IF NOT EXISTS exam_attempt SCHEMAFULL;
@@ -240,6 +241,10 @@ const BACKFILL: &str = "
240 241
241 UPDATE course SET kind = 'course' WHERE kind = NONE;242 UPDATE course SET kind = 'course' WHERE kind = NONE;
242 243
244+ -- Exams predate the draft flag (2026-07-19): everything already out there
245+ -- was live for its course, so it stays published.
246+ UPDATE exam SET draft = false WHERE draft = NONE;
247+
243 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};248 UPDATE event SET audience = { kind: 'school' } WHERE audience = NONE OR audience = {};
244 249
245 -- Questions written before subjects existed (2026-07-17) are destroyed, not250 -- Questions written before subjects existed (2026-07-17) are destroyed, not
src/domain/exam.rsmodified+15 -1
@@ -159,7 +159,7 @@ impl ExamAttemptLimit {
159 /// hand always satisfies:159 /// hand always satisfies:
160 ///160 ///
161 /// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded161 /// - no mode → no `starts_at`/`ends_at`/`duration_ms` (an offline-graded
162-/// draft; attempts are rejected),162+/// exam; attempts are rejected),
163 /// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is163 /// - `sync` → `starts_at` + `ends_at`, no duration (everyone's deadline is
164 /// `ends_at`),164 /// `ends_at`),
165 /// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts165 /// - `async` → `starts_at` + `ends_at` + `duration_ms` (a student who starts
@@ -258,6 +258,10 @@ pub struct Exam {
258 // migration (limit 1, rejoin open), so reads never see them missing.258 // migration (limit 1, rejoin open), so reads never see them missing.
259 max_attempts: ExamAttemptLimit,259 max_attempts: ExamAttemptLimit,
260 allow_rejoin: bool,260 allow_rejoin: bool,
261+ // Work-in-progress marker: a draft is visible only to its course's
262+ // managers, cannot be sat, and cannot be graded. Rows predating the
263+ // column are backfilled published (`false`).
264+ draft: bool,
261 }265 }
262 266
263 impl Exam {267 impl Exam {
@@ -311,6 +315,12 @@ impl Exam {
311 self.allow_rejoin315 self.allow_rejoin
312 }316 }
313 317
318+ /// Whether the exam is still being prepared — hidden from students, not
319+ /// sittable, not gradable, until published.
320+ pub fn is_draft(&self) -> bool {
321+ self.draft
322+ }
323+
314 /// The stored schedule as the validated bundle (for merge-on-update).324 /// The stored schedule as the validated bundle (for merge-on-update).
315 /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,325 /// Bypasses `try_new`: the fields were written through an `ExamSchedule`,
316 /// so the invariants already hold.326 /// so the invariants already hold.
@@ -340,6 +350,7 @@ impl Exam {
340 schedule: ExamSchedule,350 schedule: ExamSchedule,
341 max_attempts: ExamAttemptLimit,351 max_attempts: ExamAttemptLimit,
342 allow_rejoin: bool,352 allow_rejoin: bool,
353+ draft: bool,
343 db: &Database,354 db: &Database,
344 ) -> Result<Exam, AppError> {355 ) -> Result<Exam, AppError> {
345 let exam = Exam {356 let exam = Exam {
@@ -355,6 +366,7 @@ impl Exam {
355 duration_ms: schedule.duration_ms,366 duration_ms: schedule.duration_ms,
356 max_attempts,367 max_attempts,
357 allow_rejoin,368 allow_rejoin,
369+ draft,
358 };370 };
359 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;371 let created: Option<Exam> = db.create(exam.id.record()).content(exam).await?;
360 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))372 created.ok_or_else(|| AppError::Internal("failed to create exam".into()))
@@ -413,6 +425,7 @@ impl Exam {
413 schedule: ExamSchedule,425 schedule: ExamSchedule,
414 max_attempts: ExamAttemptLimit,426 max_attempts: ExamAttemptLimit,
415 allow_rejoin: bool,427 allow_rejoin: bool,
428+ draft: bool,
416 db: &Database,429 db: &Database,
417 ) -> Result<Exam, AppError> {430 ) -> Result<Exam, AppError> {
418 self.title = title;431 self.title = title;
@@ -424,6 +437,7 @@ impl Exam {
424 self.duration_ms = schedule.duration_ms;437 self.duration_ms = schedule.duration_ms;
425 self.max_attempts = max_attempts;438 self.max_attempts = max_attempts;
426 self.allow_rejoin = allow_rejoin;439 self.allow_rejoin = allow_rejoin;
440+ self.draft = draft;
427 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;441 let updated: Option<Exam> = db.update(self.id.record()).content(self).await?;
428 updated.ok_or(AppError::NotFound)442 updated.ok_or(AppError::NotFound)
429 }443 }
src/domain/exam_attempt.rsmodified+1 -0
@@ -366,6 +366,7 @@ mod tests {
366 .unwrap(),366 .unwrap(),
367 ExamAttemptLimit::try_new(max_attempts).unwrap(),367 ExamAttemptLimit::try_new(max_attempts).unwrap(),
368 true,368 true,
369+ false,
369 db,370 db,
370 )371 )
371 .await372 .await
src/lib.rsmodified+1 -1
@@ -46,7 +46,7 @@ use crate::state::AppState;
46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),46 (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
47 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),47 (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints"),
48 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),48 (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates"),
49- (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is an offline-graded draft — attempts on it are a 409. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),49+ (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol"),
50 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"),50 (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings)"),
51 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"),51 (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). Read: any authenticated user; edit: manager+"),
52 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"),52 (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, manager+); edit follows course management rights"),
src/web/courses.rsmodified+17 -5
@@ -91,7 +91,7 @@ struct CreateExamInCourse {
91 kind: String,91 kind: String,
92 /// `sync` (one fixed window for everyone), `async` (each student starts92 /// `sync` (one fixed window for everyone), `async` (each student starts
93 /// inside the window and gets `duration_ms`), or `open` (no window — sit93 /// inside the window and gets `duration_ms`), or `open` (no window — sit
94- /// anytime). Omit for an offline-graded draft that cannot be sat.94+ /// anytime). Omit for an offline-graded exam that cannot be sat.
95 #[schema(example = "sync")]95 #[schema(example = "sync")]
96 mode: Option<String>,96 mode: Option<String>,
97 /// Window open, UTC unix-milliseconds. Required for `sync`/`async`,97 /// Window open, UTC unix-milliseconds. Required for `sync`/`async`,
@@ -112,6 +112,10 @@ struct CreateExamInCourse {
112 /// Whether a student who left the exam room may come back in and keep112 /// Whether a student who left the exam room may come back in and keep
113 /// answering. Defaults to `true`; editable live while the exam runs.113 /// answering. Defaults to `true`; editable live while the exam runs.
114 allow_rejoin: Option<bool>,114 allow_rejoin: Option<bool>,
115+ /// Save as a work-in-progress draft: visible only to the course's
116+ /// managers, not sittable, not gradable, until published via
117+ /// `PATCH /exams/{id}` with `draft: false`. Defaults to `false`.
118+ draft: Option<bool>,
115 }119 }
116 120
117 #[derive(Serialize, ToSchema)]121 #[derive(Serialize, ToSchema)]
@@ -555,12 +559,14 @@ async fn unenroll(
555 559
556 /// Create an exam inside a course. Requires teacher+ and course management560 /// Create an exam inside a course. Requires teacher+ and course management
557 /// rights; the exam's marks count into the course average with its kind's561 /// rights; the exam's marks count into the course average with its kind's
558-/// weight (`GET /settings`). Omit `mode` for an offline-graded draft nobody562+/// weight (`GET /settings`). Omit `mode` for an offline-graded exam nobody
559 /// can sit; `sync`/`async` take a window (async also `duration_ms`), `open`563 /// can sit; `sync`/`async` take a window (async also `duration_ms`), `open`
560 /// is sittable anytime with an optional per-attempt `duration_ms`.564 /// is sittable anytime with an optional per-attempt `duration_ms`.
561 /// `max_attempts` (default 1, `0` = unlimited) meters retakes and565 /// `max_attempts` (default 1, `0` = unlimited) meters retakes and
562 /// `allow_rejoin` (default `true`) is the exam-room door — both stay editable566 /// `allow_rejoin` (default `true`) is the exam-room door — both stay editable
563-/// while the exam runs.567+/// while the exam runs. Send `draft: true` to keep the exam private while
568+/// it's still being written: only the course's managers see it, and sitting
569+/// and grading are blocked until it's published (`PATCH` `draft: false`).
564 #[utoipa::path(570 #[utoipa::path(
565 post,571 post,
566 path = "/{id}/exams",572 path = "/{id}/exams",
@@ -618,6 +624,7 @@ async fn create_exam_in_course(
618 schedule,624 schedule,
619 max_attempts,625 max_attempts,
620 req.allow_rejoin.unwrap_or(true),626 req.allow_rejoin.unwrap_or(true),
627+ req.draft.unwrap_or(false),
621 &st.db,628 &st.db,
622 )629 )
623 .await?;630 .await?;
@@ -626,7 +633,8 @@ async fn create_exam_in_course(
626 633
627 /// List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of634 /// List a course's exams, paged via `?limit=&offset=` (omit `limit` for all of
628 /// them). Visible to the course's enrolled users, its creator, and635 /// them). Visible to the course's enrolled users, its creator, and
629-/// managers/admins. Returns a `{items, total, limit, offset}` envelope.636+/// managers/admins — but drafts appear only to the course's managers.
637+/// Returns a `{items, total, limit, offset}` envelope.
630 #[utoipa::path(638 #[utoipa::path(
631 get,639 get,
632 path = "/{id}/exams",640 path = "/{id}/exams",
@@ -657,7 +665,11 @@ async fn list_course_exams(
657 "only enrolled users, the course creator, or a manager/admin can view this course",665 "only enrolled users, the course creator, or a manager/admin can view this course",
658 ));666 ));
659 }667 }
660- let exams = Exam::list_for_course(course.get_id(), &st.db).await?;668+ let mut exams = Exam::list_for_course(course.get_id(), &st.db).await?;
669+ // Drafts are the managers' workbench — enrolled students don't see them.
670+ if !can_manage_course(&course, &user) {
671+ exams.retain(|exam| !exam.is_draft());
672+ }
661 let total = exams.len() as i64;673 let total = exams.len() as i64;
662 let items = paginate(&exams, limit, offset)674 let items = paginate(&exams, limit, offset)
663 .iter()675 .iter()
src/web/dto.rsmodified+6 -2
@@ -239,7 +239,7 @@ impl SessionResponse {
239 239
240 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`240 /// Public shape of an exam. Shared by `exams` (CRUD/results) and `courses`
241 /// (in-course creation and listing). The schedule fields are all `null` for an241 /// (in-course creation and listing). The schedule fields are all `null` for an
242-/// offline-graded draft (no mode); see the create/update endpoints for the242+/// offline-graded exam (no mode); see the create/update endpoints for the
243 /// rules tying them together.243 /// rules tying them together.
244 #[derive(Serialize, ToSchema)]244 #[derive(Serialize, ToSchema)]
245 pub struct ExamResponse {245 pub struct ExamResponse {
@@ -251,7 +251,7 @@ pub struct ExamResponse {
251 /// The assessment form. Its weight in the course average is school policy:251 /// The assessment form. Its weight in the course average is school policy:
252 /// `GET /settings` maps each kind to a weight.252 /// `GET /settings` maps each kind to a weight.
253 pub kind: String,253 pub kind: String,
254- /// `sync`, `async`, or `open`; `null` for an offline-graded draft254+ /// `sync`, `async`, or `open`; `null` for an offline-graded exam
255 /// (not sittable).255 /// (not sittable).
256 #[schema(example = "sync")]256 #[schema(example = "sync")]
257 pub mode: Option<String>,257 pub mode: Option<String>,
@@ -268,6 +268,9 @@ pub struct ExamResponse {
268 /// Whether a student who left the exam room may come back in and keep268 /// Whether a student who left the exam room may come back in and keep
269 /// answering. Teachers can flip this live.269 /// answering. Teachers can flip this live.
270 pub allow_rejoin: bool,270 pub allow_rejoin: bool,
271+ /// Still being prepared: visible only to the course's managers, not
272+ /// sittable, not gradable. Publish by `PATCH`ing `draft: false`.
273+ pub draft: bool,
271 }274 }
272 275
273 impl ExamResponse {276 impl ExamResponse {
@@ -285,6 +288,7 @@ impl ExamResponse {
285 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),288 duration_ms: exam.get_duration_ms().map(|d| d.as_millis()),
286 max_attempts: exam.get_max_attempts().as_i64(),289 max_attempts: exam.get_max_attempts().as_i64(),
287 allow_rejoin: exam.get_allow_rejoin(),290 allow_rejoin: exam.get_allow_rejoin(),
291+ draft: exam.is_draft(),
288 }292 }
289 }293 }
290 }294 }
src/web/exam_ws.rsmodified+7 -9
@@ -63,7 +63,8 @@ use crate::error::AppError;
63 use crate::state::AppState;63 use crate::state::AppState;
64 use crate::web::CurrentUser;64 use crate::web::CurrentUser;
65 use crate::web::exams::{65 use crate::web::exams::{
66- EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_student, save_answer_in, writable_attempt,66+ EXAM_LOCK, check_rejoin, ensure_enrolled, ensure_sittable, ensure_student, save_answer_in,
67+ writable_attempt,
67 };68 };
68 69
69 /// Serializes every presence transition with its matching `left_at` write:70 /// Serializes every presence transition with its matching `left_at` write:
@@ -98,9 +99,10 @@ enum ClientMessage {
98 99
99 /// Upgrade into the caller's exam room. All gates run *before* the upgrade so100 /// Upgrade into the caller's exam room. All gates run *before* the upgrade so
100 /// a rejected client gets a proper HTTP status instead of an instant close:101 /// a rejected client gets a proper HTTP status instead of an instant close:
101-/// unknown exam (404), draft with no mode (409), not a student (403), not102+/// unknown or draft exam (404), unscheduled with no mode (409), not a student
102-/// enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt` first),103+/// (403), not enrolled (403), no attempt yet (404 — `POST /exams/{id}/attempt`
103-/// submitted or expired (409), left the room while rejoin is closed (409).104+/// first), submitted or expired (409), left the room while rejoin is closed
105+/// (409).
104 ///106 ///
105 /// The rejoin gate here is a read-only fast-fail for a proper 409; the107 /// The rejoin gate here is a read-only fast-fail for a proper 409; the
106 /// authoritative clear of `left_at` happens inside the room task, under108 /// authoritative clear of `left_at` happens inside the room task, under
@@ -117,11 +119,7 @@ pub async fn attempt_ws(
117 let exam = Exam::read(&ExamId::from_key(&id), &st.db)119 let exam = Exam::read(&ExamId::from_key(&id), &st.db)
118 .await?120 .await?
119 .ok_or(AppError::NotFound)?;121 .ok_or(AppError::NotFound)?;
120- if exam.get_mode().is_none() {122+ ensure_sittable(&exam)?;
121- return Err(AppError::Conflict(
122- "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
123- ));
124- }
125 ensure_student(&user)?;123 ensure_student(&user)?;
126 ensure_enrolled(&exam, user.get_id(), &st.db).await?;124 ensure_enrolled(&exam, user.get_id(), &st.db).await?;
127 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;125 let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?;
src/web/exams.rsmodified+86 -26
@@ -50,13 +50,15 @@ use super::{
50 /// Serializes the exam subsystem's cross-record check-then-writes, which50 /// Serializes the exam subsystem's cross-record check-then-writes, which
51 /// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`.51 /// `BEGIN…COMMIT` cannot (write skew) — same reasoning as `REGISTER_LOCK`.
52 /// Read side: the answer saves (REST and the exam room), holding the sheet52 /// Read side: the answer saves (REST and the exam room), holding the sheet
53-/// open from the writable-attempt gate through the upsert; saves stay53+/// open from the writable-attempt gate through the upsert, and the grade
54-/// concurrent with each other. Write side: attempt starts (the max-attempts54+/// write (draft gate through the result upsert); these stay concurrent with
55-/// count and the retake's answer wipe) and the structural teacher writes55+/// each other. Write side: attempt starts (the max-attempts count and the
56-/// whose 409 guards read attempt or question rows first — exam mode/schedule56+/// retake's answer wipe) and the structural teacher writes whose 409 guards
57+/// read attempt, question, or result rows first — exam mode/schedule/draft
57 /// updates, question create/update/delete, subject delete. So a save can58 /// updates, question create/update/delete, subject delete. So a save can
58-/// never land on a sheet a retake just wiped, and a first attempt can never59+/// never land on a sheet a retake just wiped, a first attempt can never
59-/// slip between a freeze-gate read and the write it was meant to freeze.60+/// slip between a freeze-gate read and the write it was meant to freeze,
61+/// and a mark can never land on an exam mid-flight into hiding.
60 // ponytail: global RwLock, shard per-exam if save latency ever matters.62 // ponytail: global RwLock, shard per-exam if save latency ever matters.
61 pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());63 pub(crate) static EXAM_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(());
62 64
@@ -113,8 +115,8 @@ struct UpdateExam {
113 /// settings-configured weight.115 /// settings-configured weight.
114 kind: Option<String>,116 kind: Option<String>,
115 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`117 /// `sync`, `async`, or `open`. Omit to keep the current mode; send `null`
116- /// to turn the exam back into an offline draft. Frozen once anyone has118+ /// to turn the exam back into an offline-graded one. Frozen once anyone
117- /// started an attempt. Switching to `open` requires clearing119+ /// has started an attempt. Switching to `open` requires clearing
118 /// `starts_at`/`ends_at` in the same request.120 /// `starts_at`/`ends_at` in the same request.
119 #[serde(default, deserialize_with = "set_or_clear")]121 #[serde(default, deserialize_with = "set_or_clear")]
120 #[schema(value_type = Option<String>)]122 #[schema(value_type = Option<String>)]
@@ -143,6 +145,10 @@ struct UpdateExam {
143 /// Whether students who left the exam room may come back in. Omit to145 /// Whether students who left the exam room may come back in. Omit to
144 /// keep. Editable live — the teacher's door handle for the running room.146 /// keep. Editable live — the teacher's door handle for the running room.
145 allow_rejoin: Option<bool>,147 allow_rejoin: Option<bool>,
148+ /// `false` publishes a draft (students can now see and sit it); `true`
149+ /// pulls a published exam back into hiding — allowed only while nobody
150+ /// has attempted it and nothing is graded (`409` otherwise). Omit to keep.
151+ draft: Option<bool>,
146 }152 }
147 153
148 #[derive(Deserialize, ToSchema)]154 #[derive(Deserialize, ToSchema)]
@@ -201,7 +207,8 @@ async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> {
201 // Exams are created inside a course: `POST /courses/{id}/exams`.207 // Exams are created inside a course: `POST /courses/{id}/exams`.
202 208
203 /// List the exams visible to the caller: every exam for manager+, otherwise209 /// List the exams visible to the caller: every exam for manager+, otherwise
204-/// the exams of the courses they created or are enrolled in. Paged via210+/// the exams of the courses they created or are enrolled in — minus other
211+/// people's drafts (a draft shows only to its course's managers). Paged via
205 /// `?limit=&offset=` (omit `limit` for the full list); returns a212 /// `?limit=&offset=` (omit `limit` for the full list); returns a
206 /// `{items, total, limit, offset}` envelope.213 /// `{items, total, limit, offset}` envelope.
207 #[utoipa::path(214 #[utoipa::path(
@@ -227,7 +234,16 @@ async fn list_exams(
227 } else {234 } else {
228 let courses = visible_courses(&user, &st.db).await?;235 let courses = visible_courses(&user, &st.db).await?;
229 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();236 let ids: Vec<_> = courses.iter().map(|c| c.get_id().clone()).collect();
230- Exam::list_for_courses(&ids, &st.db).await?237+ // Drafts show only where the caller manages the course (as its
238+ // creator — the manager+ path above already saw everything).
239+ let managed: Vec<&str> = courses
240+ .iter()
241+ .filter(|c| can_manage_course(c, &user))
242+ .map(|c| c.get_id().key())
243+ .collect();
244+ let mut exams = Exam::list_for_courses(&ids, &st.db).await?;
245+ exams.retain(|exam| !exam.is_draft() || managed.contains(&exam.get_course().key()));
246+ exams
231 };247 };
232 let total = exams.len() as i64;248 let total = exams.len() as i64;
233 let items = paginate(&exams, limit, offset)249 let items = paginate(&exams, limit, offset)
@@ -238,7 +254,9 @@ async fn list_exams(
238 }254 }
239 255
240 /// Fetch a single exam by id. Visible to its course's enrolled users, the256 /// Fetch a single exam by id. Visible to its course's enrolled users, the
241-/// course creator, and managers/admins.257+/// course creator, and managers/admins — except drafts, which only the
258+/// course's managers see (everyone else gets a `404`, as if the exam doesn't
259+/// exist yet — because it doesn't, officially).
242 #[utoipa::path(260 #[utoipa::path(
243 get,261 get,
244 path = "/{id}",262 path = "/{id}",
@@ -249,7 +267,7 @@ async fn list_exams(
249 (status = 200, description = "The exam", body = ExamResponse),267 (status = 200, description = "The exam", body = ExamResponse),
250 (status = 401, description = "Not authenticated", body = ErrorResponse),268 (status = 401, description = "Not authenticated", body = ErrorResponse),
251 (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse),269 (status = 403, description = "Not enrolled in the exam's course, not its creator, and not a manager/admin", body = ErrorResponse),
252- (status = 404, description = "Not found", body = ErrorResponse),270+ (status = 404, description = "Not found (or a draft the caller may not see)", body = ErrorResponse),
253 ),271 ),
254 )]272 )]
255 async fn get_exam(273 async fn get_exam(
@@ -266,6 +284,11 @@ async fn get_exam(
266 "only enrolled users, the course creator, or a manager/admin can view this exam",284 "only enrolled users, the course creator, or a manager/admin can view this exam",
267 ));285 ));
268 }286 }
287+ // A draft doesn't exist for anyone but its course's managers — 404, not
288+ // 403, so its existence never leaks to the students it's hidden from.
289+ if exam.is_draft() && !can_manage_course(&course, &user) {
290+ return Err(AppError::NotFound);
291+ }
269 Ok(Json(ExamResponse::new(&exam)))292 Ok(Json(ExamResponse::new(&exam)))
270 }293 }
271 294
@@ -276,6 +299,9 @@ async fn get_exam(
276 /// `mode` is frozen once anyone has started an attempt — times, duration,299 /// `mode` is frozen once anyone has started an attempt — times, duration,
277 /// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be300 /// `max_attempts`, and `allow_rejoin` stay editable so a running exam can be
278 /// extended, granted retakes, or have its rejoin door opened live.301 /// extended, granted retakes, or have its rejoin door opened live.
302+/// `draft: false` publishes a draft; `draft: true` re-hides an exam, but only
303+/// while it has no attempts and no results (`409` otherwise) — students never
304+/// lose sight of an exam they've already sat or been graded on.
279 #[utoipa::path(305 #[utoipa::path(
280 patch,306 patch,
281 path = "/{id}",307 path = "/{id}",
@@ -289,7 +315,7 @@ async fn get_exam(
289 (status = 401, description = "Not authenticated", body = ErrorResponse),315 (status = 401, description = "Not authenticated", body = ErrorResponse),
290 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),316 (status = 403, description = "Not the course creator (and not a manager/admin)", body = ErrorResponse),
291 (status = 404, description = "Not found", body = ErrorResponse),317 (status = 404, description = "Not found", body = ErrorResponse),
292- (status = 409, description = "Mode change after attempts started", body = ErrorResponse),318+ (status = 409, description = "Mode change after attempts started, or re-drafting an exam that has attempts or results", body = ErrorResponse),
293 ),319 ),
294 )]320 )]
295 async fn update_exam(321 async fn update_exam(
@@ -362,10 +388,11 @@ async fn update_exam(
362 None => exam.get_max_attempts(),388 None => exam.get_max_attempts(),
363 };389 };
364 let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());390 let allow_rejoin = req.allow_rejoin.unwrap_or_else(|| exam.get_allow_rejoin());
391+ let draft = req.draft.unwrap_or_else(|| exam.is_draft());
365 392
366- // Switching sync <-> async <-> open (or back to a draft) would silently393+ // Switching sync <-> async <-> open (or back to unscheduled) would
367- // rewrite the deadline rules under students who already sat down;394+ // silently rewrite the deadline rules under students who already sat
368- // extending times, the attempt limit, and the rejoin door are the395+ // down; extending times, the attempt limit, and the rejoin door are the
369 // supported live adjustments instead. Gate read and write share one396 // supported live adjustments instead. Gate read and write share one
370 // writer lease of [`EXAM_LOCK`], so a first attempt can't land in the397 // writer lease of [`EXAM_LOCK`], so a first attempt can't land in the
371 // gap and leave a sat exam's mode flipped under it.398 // gap and leave a sat exam's mode flipped under it.
@@ -377,6 +404,20 @@ async fn update_exam(
377 "cannot change the exam mode after attempts have started",404 "cannot change the exam mode after attempts have started",
378 ));405 ));
379 }406 }
407+ // Re-drafting hides the exam — never out from under a student who already
408+ // sat it or holds a mark on it. Same writer lease: a first attempt or an
409+ // in-flight grade (readers) can't slip between this gate and the write.
410+ if draft && !exam.is_draft() {
411+ let sat = ExamAttempt::any_for_exam(exam.get_id(), &st.db).await?;
412+ let graded = !ExamResult::list_for_exam(exam.get_id(), &st.db)
413+ .await?
414+ .is_empty();
415+ if sat || graded {
416+ return Err(AppError::Conflict(
417+ "cannot turn a published exam back into a draft after attempts or results exist",
418+ ));
419+ }
420+ }
380 421
381 let updated = exam422 let updated = exam
382 .update(423 .update(
@@ -386,6 +427,7 @@ async fn update_exam(
386 schedule,427 schedule,
387 max_attempts,428 max_attempts,
388 allow_rejoin,429 allow_rejoin,
430+ draft,
389 &st.db,431 &st.db,
390 )432 )
391 .await?;433 .await?;
@@ -437,7 +479,8 @@ async fn delete_exam(
437 /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and479 /// Record (or overwrite) a student's mark for an exam. Requires teacher+ and
438 /// management rights over the exam's course; the target must be a student and480 /// management rights over the exam's course; the target must be a student and
439 /// enrolled. Only students carry marks; students never grade — and nobody481 /// enrolled. Only students carry marks; students never grade — and nobody
440-/// grades themselves.482+/// grades themselves. A draft can't be graded (`409`) — a mark would point at
483+/// an exam its student can't see.
441 #[utoipa::path(484 #[utoipa::path(
442 post,485 post,
443 path = "/{id}/results",486 path = "/{id}/results",
@@ -451,6 +494,7 @@ async fn delete_exam(
451 (status = 401, description = "Not authenticated", body = ErrorResponse),494 (status = 401, description = "Not authenticated", body = ErrorResponse),
452 (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),495 (status = 403, description = "Not the course creator (and not a manager/admin), or attempted to grade yourself", body = ErrorResponse),
453 (status = 404, description = "Exam not found", body = ErrorResponse),496 (status = 404, description = "Exam not found", body = ErrorResponse),
497+ (status = 409, description = "The exam is a draft", body = ErrorResponse),
454 ),498 ),
455 )]499 )]
456 async fn grade(500 async fn grade(
@@ -460,6 +504,11 @@ async fn grade(
460 Json(req): Json<GradeResult>,504 Json(req): Json<GradeResult>,
461 ) -> Result<Json<ExamResultResponse>, AppError> {505 ) -> Result<Json<ExamResultResponse>, AppError> {
462 let exam_id = ExamId::from_key(&id);506 let exam_id = ExamId::from_key(&id);
507+ // Reader lease of [`EXAM_LOCK`] from the exam read through the result
508+ // write: the draft gate below must be judged against the same row the
509+ // mark lands under, or a concurrent re-draft (a writer, which checks for
510+ // results) could slip between them and leave a mark on a hidden exam.
511+ let _guard = EXAM_LOCK.read().await;
463 // Exam must exist.512 // Exam must exist.
464 let exam = Exam::read(&exam_id, &st.db)513 let exam = Exam::read(&exam_id, &st.db)
465 .await?514 .await?
@@ -470,6 +519,11 @@ async fn grade(
470 "only the course creator or a manager/admin can grade this exam",519 "only the course creator or a manager/admin can grade this exam",
471 ));520 ));
472 }521 }
522+ if exam.is_draft() {
523+ return Err(AppError::Conflict(
524+ "this exam is a draft — publish it before grading",
525+ ));
526+ }
473 527
474 let mark = Mark::try_new(req.mark)?;528 let mark = Mark::try_new(req.mark)?;
475 let target = UserId::from_key(&req.user_id);529 let target = UserId::from_key(&req.user_id);
@@ -781,11 +835,16 @@ async fn attempt_progress(
781 Ok((answered, question_count))835 Ok((answered, question_count))
782 }836 }
783 837
784-/// A 409 unless the exam can be sat at all: it needs a mode (`sync`, `async`,838+/// Rejects sitting an exam that can't be sat. A draft is a `404`, not a
785-/// or `open`) — a modeless exam is an offline-graded draft. Enrollment and839+/// `409` — sitting is a student act, drafts are invisible to students, and a
786-/// window checks for the caller are the caller's own state — hence `Conflict`840+/// state-specific error would leak the existence this feature hides. A
787-/// (a state problem), not validation.841+/// modeless (offline-graded) exam is a `409`: visible, just nothing to sit.
788-fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {842+/// Enrollment and window checks for the caller are the caller's own state —
843+/// also `Conflict`, not validation.
844+pub(crate) fn ensure_sittable(exam: &Exam) -> Result<(), AppError> {
845+ if exam.is_draft() {
846+ return Err(AppError::NotFound);
847+ }
789 if exam.get_mode().is_none() {848 if exam.get_mode().is_none() {
790 return Err(AppError::Conflict(849 return Err(AppError::Conflict(
791 "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",850 "this exam is not scheduled — there is nothing to sit (give it a mode: sync, async, or open)",
@@ -818,8 +877,8 @@ async fn attempts_used(exam: &ExamId, user: &UserId, db: &Database) -> Result<u6
818 (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),877 (status = 200, description = "Running attempt resumed (unchanged)", body = AttemptResponse),
819 (status = 401, description = "Not authenticated", body = ErrorResponse),878 (status = 401, description = "Not authenticated", body = ErrorResponse),
820 (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),879 (status = 403, description = "Not a student, or not enrolled in the exam's course", body = ErrorResponse),
821- (status = 404, description = "Exam not found", body = ErrorResponse),880+ (status = 404, description = "Exam not found (drafts are invisible here)", body = ErrorResponse),
822- (status = 409, description = "Draft exam, outside the window, or no attempts remaining", body = ErrorResponse),881+ (status = 409, description = "Unscheduled (offline-graded) exam, outside the window, or no attempts remaining", body = ErrorResponse),
823 ),882 ),
824 )]883 )]
825 async fn start_attempt(884 async fn start_attempt(
@@ -830,8 +889,9 @@ async fn start_attempt(
830 // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the889 // Writer lease of [`EXAM_LOCK`] from the exam read through the start: the
831 // sittable/window gates must be judged against the same exam row the890 // sittable/window gates must be judged against the same exam row the
832 // attempt lands under (the mirror of `update_exam`'s re-derive — without891 // attempt lands under (the mirror of `update_exam`'s re-derive — without
833- // it, a mode change at legally-zero attempts could slip between this892+ // it, a mode change or re-draft at legally-zero attempts could slip
834- // gate and the insert, leaving an attempt on a draft exam). The lease893+ // between this gate and the insert, leaving an attempt on an unsittable
894+ // exam). The lease
835 // also keeps the max-attempts count and the retake's wipe-and-create895 // also keeps the max-attempts count and the retake's wipe-and-create
836 // from interleaving with an in-flight answer save (a reader). Dropped896 // from interleaving with an in-flight answer save (a reader). Dropped
837 // before the response reads — they only describe the row.897 // before the response reads — they only describe the row.
tests/integration.rsmodified+141 -0
@@ -10502,3 +10502,144 @@ async fn question_image_edits_follow_the_choices() {
10502 );10502 );
10503 }10503 }
10504 }10504 }
10505+
10506+// --- exam drafts ---------------------------------------------------------
10507+
10508+#[tokio::test]
10509+async fn draft_exams_hide_from_students_until_published() {
10510+ let (app, db) = app_and_db().await;
10511+ let teacher = login_as(&app, &db, "draft_t", "teacher").await;
10512+ let student = login(&app, "draft_s").await;
10513+ let student_id = me_id(&app, &student).await;
10514+ let course = create_course(&app, &teacher, "history").await;
10515+ enroll(&app, &teacher, &course, &student_id).await;
10516+
10517+ // Saved as a draft: an open (sittable-were-it-published) exam.
10518+ let res = create_exam_with(
10519+ &app,
10520+ &teacher,
10521+ &course,
10522+ json!({ "title": "wip final", "kind": "final", "mode": "open", "draft": true }),
10523+ )
10524+ .await;
10525+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
10526+ assert_eq!(res.body["draft"], true);
10527+ let exam = id_of(&res.body);
10528+
10529+ // The manager sees it everywhere, flagged.
10530+ let mine = send(&app, "GET", "/exams", Some(&teacher), None).await;
10531+ assert_eq!(common::items(&mine.body).len(), 1);
10532+ assert_eq!(common::items(&mine.body)[0]["draft"], true);
10533+
10534+ // The enrolled student sees nothing: not in either list, a 404 on direct
10535+ // read, and a 404 (not a telltale 409) on sitting.
10536+ let listed = send(&app, "GET", "/exams", Some(&student), None).await;
10537+ assert_eq!(common::items(&listed.body).len(), 0);
10538+ let in_course = send(
10539+ &app,
10540+ "GET",
10541+ &format!("/courses/{course}/exams"),
10542+ Some(&student),
10543+ None,
10544+ )
10545+ .await;
10546+ assert_eq!(common::items(&in_course.body).len(), 0);
10547+ for (method, path) in [
10548+ ("GET", format!("/exams/{exam}")),
10549+ ("POST", format!("/exams/{exam}/attempt")),
10550+ ] {
10551+ let res = send(&app, method, &path, Some(&student), None).await;
10552+ assert_eq!(res.status, StatusCode::NOT_FOUND, "{method} {path}");
10553+ }
10554+
10555+ // Grading a draft is refused — a mark must never point at a hidden exam.
10556+ let res = send(
10557+ &app,
10558+ "POST",
10559+ &format!("/exams/{exam}/results"),
10560+ Some(&teacher),
10561+ Some(json!({ "mark": 90, "user_id": student_id })),
10562+ )
10563+ .await;
10564+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
10565+
10566+ // Publish. The student now sees and sits it.
10567+ let res = send(
10568+ &app,
10569+ "PATCH",
10570+ &format!("/exams/{exam}"),
10571+ Some(&teacher),
10572+ Some(json!({ "draft": false })),
10573+ )
10574+ .await;
10575+ assert_eq!(res.status, StatusCode::OK);
10576+ assert_eq!(res.body["draft"], false);
10577+ let listed = send(&app, "GET", "/exams", Some(&student), None).await;
10578+ assert_eq!(common::items(&listed.body).len(), 1);
10579+ let res = send(
10580+ &app,
10581+ "POST",
10582+ &format!("/exams/{exam}/attempt"),
10583+ Some(&student),
10584+ None,
10585+ )
10586+ .await;
10587+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
10588+
10589+ // Once sat, the exam can't be pulled back into hiding.
10590+ let res = send(
10591+ &app,
10592+ "PATCH",
10593+ &format!("/exams/{exam}"),
10594+ Some(&teacher),
10595+ Some(json!({ "draft": true })),
10596+ )
10597+ .await;
10598+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
10599+}
10600+
10601+#[tokio::test]
10602+async fn results_alone_also_freeze_re_drafting() {
10603+ let (app, db) = app_and_db().await;
10604+ let teacher = login_as(&app, &db, "redraft_t", "teacher").await;
10605+ let student = login(&app, "redraft_s").await;
10606+ let student_id = me_id(&app, &student).await;
10607+ let course = create_course(&app, &teacher, "geo").await;
10608+ enroll(&app, &teacher, &course, &student_id).await;
10609+
10610+ // A published offline-graded exam (no mode, no attempts — marks by hand).
10611+ let exam = create_exam(&app, &teacher, &course, "field trip report", "project").await;
10612+ let res = send(
10613+ &app,
10614+ "POST",
10615+ &format!("/exams/{exam}/results"),
10616+ Some(&teacher),
10617+ Some(json!({ "mark": 75, "user_id": student_id })),
10618+ )
10619+ .await;
10620+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10621+
10622+ // No attempts exist, but the graded result freezes re-drafting too.
10623+ let res = send(
10624+ &app,
10625+ "PATCH",
10626+ &format!("/exams/{exam}"),
10627+ Some(&teacher),
10628+ Some(json!({ "draft": true })),
10629+ )
10630+ .await;
10631+ assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body);
10632+
10633+ // Ungraded siblings still re-draft freely.
10634+ let other = create_exam(&app, &teacher, &course, "map quiz", "quiz").await;
10635+ let res = send(
10636+ &app,
10637+ "PATCH",
10638+ &format!("/exams/{other}"),
10639+ Some(&teacher),
10640+ Some(json!({ "draft": true })),
10641+ )
10642+ .await;
10643+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
10644+ assert_eq!(res.body["draft"], true);
10645+}
tests/persistence.rsmodified+82 -0
@@ -929,3 +929,85 @@ async fn stale_staff_enrollments_are_swept_on_boot() {
929 "the real student's row survives"929 "the real student's row survives"
930 );930 );
931 }931 }
932+
933+/// Exam rows written before the draft flag existed (2026-07-19) backfill to
934+/// published (`draft = false`) on the next boot — an old volume's exams stay
935+/// exactly as visible as they were.
936+#[tokio::test]
937+async fn legacy_exams_backfill_to_published() {
938+ let dir = tempfile::tempdir().unwrap();
939+ let cfg = config_at(&dir);
940+ let teacher_creds = json!({ "username": "ali", "password": "secret1" });
941+ let student_creds = json!({ "username": "ayse", "password": "secret1" });
942+ let exam_id;
943+
944+ // First boot: a normal exam — then strip `draft` the way an old binary's
945+ // schema would have left it.
946+ {
947+ let db = database::init(&cfg).await.expect("first open");
948+ let app = build_router(state(db.clone(), &cfg));
949+ for creds in [&teacher_creds, &student_creds] {
950+ assert_eq!(
951+ send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
952+ .await
953+ .status,
954+ StatusCode::CREATED
955+ );
956+ }
957+ set_role(&db, "ali", "teacher").await;
958+ let teacher = send(
959+ &app,
960+ "POST",
961+ "/auth/login",
962+ None,
963+ Some(teacher_creds.clone()),
964+ )
965+ .await
966+ .cookie
967+ .unwrap();
968+ let student = send(
969+ &app,
970+ "POST",
971+ "/auth/login",
972+ None,
973+ Some(student_creds.clone()),
974+ )
975+ .await
976+ .cookie
977+ .unwrap();
978+ let student_id = me_id(&app, &student).await;
979+ let course = create_course(&app, &teacher, "algebra").await;
980+ enroll(&app, &teacher, &course, &student_id).await;
981+ exam_id = create_exam(&app, &teacher, &course, "midterm", "midterm").await;
982+
983+ db.query(
984+ "REMOVE FIELD IF EXISTS draft ON TABLE exam;
985+ UPDATE exam SET draft = NONE;",
986+ )
987+ .await
988+ .expect("strip draft")
989+ .check()
990+ .expect("strip draft check");
991+ }
992+
993+ // Second boot re-runs the migration: the legacy exam reads back published
994+ // and the enrolled student still sees it.
995+ let db = reopen(&cfg).await;
996+ let app = build_router(state(db, &cfg));
997+ let student = send(&app, "POST", "/auth/login", None, Some(student_creds))
998+ .await
999+ .cookie
1000+ .unwrap();
1001+ let res = send(
1002+ &app,
1003+ "GET",
1004+ &format!("/exams/{exam_id}"),
1005+ Some(&student),
1006+ None,
1007+ )
1008+ .await;
1009+ assert_eq!(res.status, StatusCode::OK, "{}", res.body);
1010+ assert_eq!(res.body["draft"], false);
1011+ let listed = send(&app, "GET", "/exams", Some(&student), None).await;
1012+ assert_eq!(common::items(&listed.body).len(), 1);
1013+}