forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

exam_result.rs1095 lines, 43.7 KiBHistoryRawDownload
1//! The `exam_result` table: the mark's claim-riding upsert, the per-sitting
2//! history reads, and the refunding delete. The grade pre-flight (draft, kind,
3//! grader/target walls) lives in
4//! [`crate::service::exam_result`]; the mark newtype and the latest-per-pair
5//! fold live in [`crate::domain::exam_result`].
6
7use crate::constant::HIGH_MARK_MIN;
8use crate::database::{Database, tx_with_retry};
9use crate::domain::class_course::ClassCourseId;
10use crate::domain::exam::ExamId;
11use crate::domain::exam_result::{
12 ExamResult, Mark, draft_error, latest_per_pair, retired_kind_error,
13};
14use crate::domain::term::TermId;
15use crate::domain::timestamp::Timestamp;
16use crate::domain::user::UserId;
17use crate::error::AppError;
18
19/// A single user's result for an exam, if graded — the latest sitting's mark.
20async fn find(db: &Database, exam: &ExamId, user: &UserId) -> Result<Option<ExamResult>, AppError> {
21 // Grade-of-record is the latest sitting's mark: the highest seq wins.
22 Ok(sqlx::query_as!(
23 ExamResult,
24 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
25 mark AS "mark: Mark", graded_by AS "graded_by: UserId"
26 FROM exam_result WHERE exam = $1 AND app_user = $2
27 ORDER BY seq DESC LIMIT 1"#,
28 exam.uuid(),
29 user.uuid(),
30 )
31 .fetch_optional(db)
32 .await?)
33}
34
35/// Record (or overwrite) `user`'s mark for the `seq`th sitting of `exam`.
36/// One row per (exam, user, seq), keyed by the natural composite primary key
37/// `exam_result_exam_user_seq`, so this is a single atomic UPSERT —
38/// concurrent grades for the same sitting converge on one row instead of
39/// racing the unique index into a 500. Grading a retake writes a fresh mark
40/// at the current seq and never touches prior sittings' marks; the latest
41/// seq is the grade-of-record.
42///
43/// `kind` is the exam's kind, and this is where a mark takes its reference
44/// on it — claimed *inside the mark's own transaction*, and only on the
45/// branch that is about to add a row. A kind the school has retired refuses
46/// the claim, which is the same invariant the settings guard enforces from
47/// the other side. Claimed before the write and released after, the pair had
48/// two crash windows either side of the write that leaked a reference (a
49/// kind frozen out of the settings for good) and an exam's `result_count`;
50/// riding the transaction, both counters land exactly when the row does.
51///
52/// The exam's own `result_count` is claimed in the same breath, and it is
53/// what a kind change is refused against: the exam PATCH pins that counter,
54/// so a mark landing while it decides cannot slip past its gate and leave
55/// itself counted under a kind its exam no longer carries. The exam row is
56/// taken `FOR UPDATE` first — which is also what serializes this write with
57/// a concurrent re-draft and with the exam-delete cascade, replacing the
58/// reader lease grading used to hold.
59///
60/// An overwrite (a regrade of a sitting already marked) claims *nothing*:
61/// one mark, one reference, so the branch that finds a row simply leaves
62/// both counters where they are — there is no claim to give back, and so no
63/// window in which a crash could fail to give it.
64///
65/// The grader's `marks_given_total` rides that same first-time branch: a
66/// regrade of a sitting moves it however often it is run, while a retake,
67/// being a distinct `seq` and so a distinct row, counts on its own.
68///
69/// The student's `high_mark_total` cannot ride it, because it is not a
70/// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a
71/// regrade moves a mark across that line without adding or removing a row.
72/// It moves by the difference between the mark about to be stored and the
73/// one already there — `+1` crossing up, `-1` crossing down, nothing at all
74/// when both sides sit on the same side of the line, so an overwrite still
75/// costs the student's row no write unless the answer actually changed.
76/// Decided on the first branch alone it drifted upward without bound: 95
77/// credited, regraded to 40 (no row added, so no move), then deleted, whose
78/// refund reads the *stored* mark and so found nothing to give back — a
79/// counter of one over zero stored high marks, looped into a permanent
80/// badge. Both counters are written field-scoped: a user row also carries
81/// admin-owned data (`role`) that a whole-row save would revert.
82pub async fn grade(
83 db: &Database,
84 exam: &ExamId,
85 user: &UserId,
86 seq: i64,
87 mark: Mark,
88 graded_by: &UserId,
89 kind: &str,
90) -> Result<ExamResult, AppError> {
91 // The "exists" and "not a draft" gates ride in the same transaction as
92 // the mark, the mirror of the re-draft gate on
93 // `crate::db::exam::update_if_unchanged`: between them, a mark and a
94 // re-draft racing each other can only ever leave one of the two applied,
95 // whichever process either ran in. The existence gate is not
96 // redundant with the draft one — a missing row answers the same `404`
97 // the old `exam_missing` THROW answered with, and `draft` alone could
98 // never see a row that is not there. The caller's pre-flight check
99 // answers the same 409 one round trip earlier.
100 //
101 // `$before` — the sitting's previous mark — answers both counter
102 // questions off one read: `None` there means no row at all (the claim
103 // branch), while a number is what the student's counter takes its
104 // difference against. Read one statement before the counters inside
105 // the same transaction: read anywhere else it would be a guess about a
106 // row two graders may be writing at once, and the difference would be
107 // taken against a mark some other round had already replaced. The exam
108 // row's `FOR UPDATE` is what makes that read the write's own: a rival
109 // grade holds the same lock across its whole transaction, so the two
110 // serialize instead of interleaving their counter moves.
111 let exam = exam.clone();
112 let (user, graded_by) = (*user, *graded_by);
113 let kind = kind.to_owned();
114 tx_with_retry(db, false, async move |conn| {
115 let exam_row = sqlx::query!(
116 r#"SELECT draft AS "draft: bool" FROM exam WHERE id = $1 FOR UPDATE"#,
117 exam.uuid(),
118 )
119 .fetch_optional(&mut *conn)
120 .await?;
121 let Some(exam_row) = exam_row else {
122 return Err(AppError::NotFound);
123 };
124 if exam_row.draft {
125 return Err(draft_error());
126 }
127 let before = sqlx::query!(
128 r#"SELECT mark AS "mark: Mark" FROM exam_result
129 WHERE exam = $1 AND app_user = $2 AND seq = $3"#,
130 exam.uuid(),
131 user.uuid(),
132 seq,
133 )
134 .fetch_optional(&mut *conn)
135 .await?
136 .map(|row| row.mark);
137 if before.is_none() {
138 // `kind_retired`: the mark's own transaction refusing a name
139 // the school has retired. An absent row reads as zero
140 // references, in service — the claim mints it, exactly like a
141 // menu publish mints an absent `slot_ref`. A row already
142 // retired refuses the claim: the guarded update skips, the
143 // `RETURNING` comes back empty.
144 let claimed = sqlx::query!(
145 r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 1, false)
146 ON CONFLICT (name) DO UPDATE SET count = kind_ref.count + 1
147 WHERE kind_ref.retired IS DISTINCT FROM TRUE
148 RETURNING 1 AS n"#,
149 kind,
150 )
151 .fetch_optional(&mut *conn)
152 .await?;
153 if claimed.is_none() {
154 return Err(retired_kind_error(&kind));
155 }
156 sqlx::query!(
157 r#"UPDATE exam SET result_count = exam.result_count + 1 WHERE id = $1"#,
158 exam.uuid(),
159 )
160 .execute(&mut *conn)
161 .await?;
162 sqlx::query!(
163 r#"UPDATE app_user SET marks_given_total = app_user.marks_given_total + 1
164 WHERE id = $1"#,
165 graded_by.uuid(),
166 )
167 .execute(&mut *conn)
168 .await?;
169 }
170 let stored = before.map_or(-1, |mark| mark.as_i64());
171 let high = i64::from(mark.as_i64() >= HIGH_MARK_MIN) - i64::from(stored >= HIGH_MARK_MIN);
172 if high != 0 {
173 sqlx::query!(
174 r#"UPDATE app_user SET high_mark_total =
175 GREATEST(high_mark_total + $2, 0)
176 WHERE id = $1"#,
177 user.uuid(),
178 high,
179 )
180 .execute(&mut *conn)
181 .await?;
182 }
183 let written = sqlx::query_as!(
184 ExamResult,
185 r#"INSERT INTO exam_result (exam, app_user, seq, mark, graded_by, graded_at)
186 VALUES ($1, $2, $3, $4, $5, $6)
187 ON CONFLICT (exam, app_user, seq) DO UPDATE
188 SET mark = EXCLUDED.mark, graded_by = EXCLUDED.graded_by,
189 graded_at = EXCLUDED.graded_at
190 RETURNING exam AS "exam: ExamId", app_user AS "user: UserId", seq,
191 mark AS "mark: Mark", graded_by AS "graded_by: UserId""#,
192 exam.uuid(),
193 user.uuid(),
194 seq,
195 mark.as_i64(),
196 graded_by.uuid(),
197 Timestamp::now().as_millis(),
198 )
199 .fetch_one(&mut *conn)
200 .await?;
201 Ok(written)
202 })
203 .await
204}
205
206/// The user's graded results that count under one instance — the raw rows
207/// behind the per-instance block of the marks report.
208///
209/// It reads `exam_audience`, not `exam.class_course`: an exam addressed to
210/// several instances (a shared exam) is *each* of their exams, and its marks
211/// count in every one of them, not only in the owner's. The owner's audience
212/// row is always written with the exam, so for an exam nobody else was
213/// addressed to this is the same set the owner column used to give.
214pub async fn list_for_user_in_course(
215 db: &Database,
216 class_course: &ClassCourseId,
217 user: &UserId,
218) -> Result<Vec<ExamResult>, AppError> {
219 let rows = sqlx::query_as!(
220 ExamResult,
221 r#"SELECT r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq,
222 r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId"
223 FROM exam_result r JOIN exam_audience a ON a.exam = r.exam
224 WHERE r.app_user = $1 AND a.class_course = $2
225 ORDER BY r.exam DESC, r.seq DESC"#,
226 user.uuid(),
227 class_course.uuid(),
228 )
229 .fetch_all(db)
230 .await?;
231 Ok(latest_per_pair(rows))
232}
233
234/// One row of [`list_for_user_in_term`]: a mark's own columns plus the
235/// instance the audience join resolved it under.
236///
237/// The instance is the *join's* answer, not a column of `exam_result`, so this
238/// is a second spelling of [`ExamResult`]'s five columns. Flat, and named after
239/// the query's column aliases: `query_as!` builds the row field by field out of
240/// the selected columns, so a nested or renamed field would not line up.
241/// [`into_parts`](AttributedResult::into_parts) hands the caller the domain row
242/// back.
243struct AttributedResult {
244 class_course: ClassCourseId,
245 exam: ExamId,
246 user: UserId,
247 seq: i64,
248 mark: Mark,
249 graded_by: UserId,
250}
251
252impl AttributedResult {
253 fn into_parts(self) -> (ClassCourseId, ExamResult) {
254 (
255 self.class_course,
256 ExamResult {
257 exam: self.exam,
258 user: self.user,
259 seq: self.seq,
260 mark: self.mark,
261 graded_by: self.graded_by,
262 },
263 )
264 }
265}
266
267/// The user's graded results inside one term, each paired with the instance it
268/// counts under — the report card's input slice (D8: a report card is per term,
269/// and an exam belongs to the term it was sat in).
270///
271/// A mark comes back once per *queried* instance the exam is addressed to
272/// (`exam_audience`), not only under its owner: a shared exam announced to
273/// several instances is each of their exams, and this is what puts its mark in
274/// every one of their report cards. Only the latest sitting per (instance, exam)
275/// comes back, the grade-of-record the per-instance read folds to as well.
276pub async fn list_for_user_in_term(
277 db: &Database,
278 user: &UserId,
279 term: &TermId,
280 instances: &[ClassCourseId],
281) -> Result<Vec<(ClassCourseId, ExamResult)>, AppError> {
282 if instances.is_empty() {
283 return Ok(Vec::new());
284 }
285 let instances: Vec<uuid::Uuid> = instances.iter().map(ClassCourseId::uuid).collect();
286 let rows = sqlx::query_as!(
287 AttributedResult,
288 r#"SELECT DISTINCT ON (a.class_course, r.exam)
289 a.class_course AS "class_course: ClassCourseId",
290 r.exam AS "exam: ExamId", r.app_user AS "user: UserId", r.seq,
291 r.mark AS "mark: Mark", r.graded_by AS "graded_by: UserId"
292 FROM exam_result r
293 JOIN exam e ON e.id = r.exam
294 JOIN exam_audience a ON a.exam = r.exam
295 WHERE r.app_user = $1 AND e.term = $2 AND a.class_course = ANY($3)
296 ORDER BY a.class_course, r.exam DESC, r.seq DESC"#,
297 user.uuid(),
298 term.uuid(),
299 &instances,
300 )
301 .fetch_all(db)
302 .await?;
303 Ok(rows.into_iter().map(AttributedResult::into_parts).collect())
304}
305
306pub async fn list_for_exam(db: &Database, exam: &ExamId) -> Result<Vec<ExamResult>, AppError> {
307 let rows = sqlx::query_as!(
308 ExamResult,
309 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
310 mark AS "mark: Mark", graded_by AS "graded_by: UserId"
311 FROM exam_result WHERE exam = $1
312 ORDER BY exam DESC, seq DESC"#,
313 exam.uuid(),
314 )
315 .fetch_all(db)
316 .await?;
317 Ok(latest_per_pair(rows))
318}
319
320/// Every sitting's mark for one (exam, user) pair, oldest first — the
321/// per-attempt grade history behind the FE's attempt-by-attempt view.
322pub async fn list_all_for_exam_user(
323 db: &Database,
324 exam: &ExamId,
325 user: &UserId,
326) -> Result<Vec<ExamResult>, AppError> {
327 Ok(sqlx::query_as!(
328 ExamResult,
329 r#"SELECT exam AS "exam: ExamId", app_user AS "user: UserId", seq,
330 mark AS "mark: Mark", graded_by AS "graded_by: UserId"
331 FROM exam_result WHERE exam = $1 AND app_user = $2
332 ORDER BY seq ASC"#,
333 exam.uuid(),
334 user.uuid(),
335 )
336 .fetch_all(db)
337 .await?)
338}
339
340/// A single user's result for an exam, if graded.
341pub async fn read_for_user(
342 db: &Database,
343 exam: &ExamId,
344 user: &UserId,
345) -> Result<Option<ExamResult>, AppError> {
346 find(db, exam, user).await
347}
348
349/// Delete every sitting's mark for one (exam, user) pair. `kind` is the
350/// exam's: the marks give their references back, so a kind nothing is
351/// graded under any more can leave the settings again.
352///
353/// The two badge counters come back the same way, and for a reason the
354/// other counters do not need: [`grade`] credits them on the
355/// branch that finds no row, and a deleted row *is* no row. Left standing,
356/// ungrade-then-regrade credited a second time off one stored mark, and
357/// looped it minted a badge from a single exam — permanently, since an
358/// award is never revoked. Each is given back off the rows this statement
359/// actually deleted: `marks_given_total` to each row's *own* grader (two
360/// teachers can hold two sittings of the same pair), and `high_mark_total`
361/// once per removed row that cleared [`HIGH_MARK_MIN`], read off the
362/// deleted image rather than re-derived. That last one is why
363/// [`grade`] has to move the student's counter on a *regrade*
364/// too: this end reads the stored mark, so the other end must be decided by
365/// the stored mark as well, or a mark walked across the line between the
366/// two leaves a credit no delete can find to give back.
367pub async fn remove(
368 db: &Database,
369 exam: &ExamId,
370 user: &UserId,
371 kind: &str,
372) -> Result<Option<ExamResult>, AppError> {
373 // Both counters go back *inside* the delete's own transaction, driven
374 // off the rows this statement actually deleted. Counted outside it, a
375 // cascade (exam or course delete) taking the same rows in the gap would
376 // release them a second time, and on a kind another exam still grades
377 // under, one release too many reads as one mark too few — a kind
378 // wrongly free to leave the settings.
379 let exam = exam.clone();
380 let user = *user;
381 let kind = kind.to_owned();
382 tx_with_retry(db, false, async move |conn| {
383 // The `gone` CTE deletes and reports in one statement: the counters
384 // below move by exactly what this delete removed, so a concurrent
385 // grade's rows (it holds the exam row's lock, and this statement's
386 // sibling below takes the same lock before touching `result_count`)
387 // can never be half-counted.
388 let gone = sqlx::query!(
389 r#"WITH gone AS (
390 DELETE FROM exam_result
391 WHERE exam = $1 AND app_user = $2
392 RETURNING mark, graded_by, seq)
393 SELECT seq, mark AS "mark: Mark", graded_by AS "graded_by: UserId"
394 FROM gone ORDER BY seq ASC"#,
395 exam.uuid(),
396 user.uuid(),
397 )
398 .fetch_all(&mut *conn)
399 .await?;
400 if gone.is_empty() {
401 return Ok(None);
402 }
403 sqlx::query!(
404 r#"UPDATE kind_ref SET count = GREATEST(kind_ref.count - $2, 0)
405 WHERE name = $1"#,
406 kind,
407 gone.len() as i64,
408 )
409 .execute(&mut *conn)
410 .await?;
411 sqlx::query!(
412 r#"UPDATE exam SET result_count = GREATEST(exam.result_count - $2, 0)
413 WHERE id = $1"#,
414 exam.uuid(),
415 gone.len() as i64,
416 )
417 .execute(&mut *conn)
418 .await?;
419 let high = gone
420 .iter()
421 .filter(|row| row.mark.as_i64() >= HIGH_MARK_MIN)
422 .count() as i64;
423 if high > 0 {
424 sqlx::query!(
425 r#"UPDATE app_user SET high_mark_total =
426 GREATEST(high_mark_total - $2, 0)
427 WHERE id = $1"#,
428 user.uuid(),
429 high,
430 )
431 .execute(&mut *conn)
432 .await?;
433 }
434 // One give-back per distinct grader: two teachers can hold two
435 // sittings of the same pair.
436 let mut per_grader: Vec<(UserId, i64)> = Vec::new();
437 for row in &gone {
438 if let Some((_, n)) = per_grader
439 .iter_mut()
440 .find(|(grader, _)| grader == &row.graded_by)
441 {
442 *n += 1;
443 } else {
444 per_grader.push((row.graded_by, 1));
445 }
446 }
447 for (grader, n) in &per_grader {
448 sqlx::query!(
449 r#"UPDATE app_user SET marks_given_total =
450 GREATEST(marks_given_total - $2, 0)
451 WHERE id = $1"#,
452 grader.uuid(),
453 n,
454 )
455 .execute(&mut *conn)
456 .await?;
457 }
458 // The first sitting's row comes back — the same shape the old
459 // `RETURN` handed over, whose caller only asks whether anything was
460 // removed and what the latest standing was.
461 let first = gone.into_iter().next().map(|row| ExamResult {
462 exam: exam.clone(),
463 user,
464 seq: row.seq,
465 mark: row.mark,
466 graded_by: row.graded_by,
467 });
468 Ok(first)
469 })
470 .await
471}
472#[cfg(test)]
473pub(crate) mod tests {
474 use super::*;
475 use sqlx::Row as _;
476
477 use crate::database::init_test_db;
478
479 /// The mark [`an_ortak_exam_karne`] grades on the exam addressed to both
480 /// instances, and the one it grades on the owner-only exam.
481 pub(crate) const ORTAK_MARK: i64 = 85;
482 pub(crate) const OWNER_MARK: i64 = 45;
483
484 /// The shape the audience attribution is read against: two sections, one
485 /// catalog course and one student who is a live member of both, so the
486 /// report card and the marks report each carry a line for *both* instances.
487 pub(crate) struct OrtakExam {
488 pub student: UserId,
489 pub term: TermId,
490 /// The instance both exams were created in — their owner.
491 pub owner: ClassCourseId,
492 /// The other instance the shared exam was addressed to.
493 pub addressed: ClassCourseId,
494 }
495
496 /// A year with one term, two sections of it carrying the same catalog
497 /// course, and one student who sits both. Two exams are created in the
498 /// first section's instance and graded: one owned there but **addressed to
499 /// both** (the second `exam_audience` row is written directly, which is
500 /// what a school-wide shared exam is), the other addressed to its owner
501 /// alone.
502 ///
503 /// That is what tells the two conclusions apart: read through
504 /// `exam_audience`, [`ORTAK_MARK`] stands on *both* instances' lines and
505 /// [`OWNER_MARK`] on the owner's alone; read through `exam.class_course`
506 /// (the shape this fixture was built to catch), the second instance held no
507 /// mark at all and the owner's line averaged only its own exam.
508 pub(crate) async fn an_ortak_exam_karne(db: &Database) -> OrtakExam {
509 use crate::domain::academic_year::AcademicYearName;
510 use crate::domain::class_group::ClassName;
511 use crate::domain::course::{CourseDescription, CourseKind, CourseTitle};
512 use crate::domain::exam::{
513 ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
514 };
515 use crate::domain::settings::Settings;
516 use crate::domain::term::TermName;
517
518 let office = crate::db::class_member::tests::fixture_user(db, "ortak-office").await;
519 let student = crate::db::class_member::tests::fixture_user(db, "ortak-student").await;
520 let year = crate::db::academic_year::create(
521 db,
522 &office,
523 AcademicYearName::try_new("ortak 2026-2027").unwrap(),
524 Timestamp::from_millis(0),
525 Timestamp::from_millis(1),
526 Vec::new(),
527 )
528 .await
529 .unwrap();
530 let term = crate::db::term::create(
531 db,
532 TermName::try_new("1. Dönem").unwrap(),
533 *year.get_id(),
534 Timestamp::from_millis(0),
535 Timestamp::from_millis(1),
536 )
537 .await
538 .unwrap();
539 let course = crate::db::course::create(
540 db,
541 &office,
542 CourseTitle::try_new("Matematik").unwrap(),
543 CourseDescription::try_new("").unwrap(),
544 CourseKind::course(),
545 )
546 .await
547 .unwrap();
548 let mut instances: Vec<ClassCourseId> = Vec::new();
549 for name in ["5-A", "5-B"] {
550 let class = crate::db::class_group::create(
551 db,
552 &office,
553 ClassName::try_new(name).unwrap(),
554 crate::domain::grade::GradeLevel::new(5).unwrap(),
555 Some(*year.get_id()),
556 None,
557 )
558 .await
559 .unwrap();
560 crate::service::class_member::add(db, class.get_id(), &student, &office)
561 .await
562 .unwrap();
563 let instance =
564 crate::service::class_course::attach(db, class.get_id(), course.get_id(), &office)
565 .await
566 .unwrap();
567 instances.push(instance.get_id().clone());
568 }
569 let owner = instances[0].clone();
570 let addressed = instances[1].clone();
571
572 let kinds = Settings::defaults().get_exam_kinds().to_vec();
573 for (title, addressed_to_both, kind, mark) in [
574 ("ortak", true, "yazili", ORTAK_MARK),
575 ("tek", false, "sozlu", OWNER_MARK),
576 ] {
577 let exam = crate::db::exam::create(
578 db,
579 &office,
580 &owner,
581 term.get_id(),
582 ExamTitle::try_new(title).unwrap(),
583 ExamDescription::try_new("").unwrap(),
584 ExamKind::try_new(kind, &kinds).unwrap(),
585 ExamSchedule::try_new(None, None, None, None).unwrap(),
586 ExamAttemptLimit::try_new(1).unwrap(),
587 true,
588 false,
589 false,
590 )
591 .await
592 .unwrap();
593 if addressed_to_both {
594 // The shared-exam half: the create wrote the owner's audience row,
595 // and the school announces the exam to the second section too.
596 sqlx::query("INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)")
597 .bind(exam.get_id().uuid())
598 .bind(addressed.uuid())
599 .execute(db)
600 .await
601 .unwrap();
602 }
603 super::grade(
604 db,
605 exam.get_id(),
606 &student,
607 1,
608 Mark::try_new(mark).unwrap(),
609 &office,
610 kind,
611 )
612 .await
613 .unwrap();
614 }
615
616 OrtakExam {
617 student,
618 term: *term.get_id(),
619 owner,
620 addressed,
621 }
622 }
623
624 #[tokio::test]
625 async fn retakes_keep_a_mark_per_sitting_with_the_latest_as_grade_of_record() {
626 let (db, _leases) = init_test_db().await;
627 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a1");
628 let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a");
629 let teacher = UserId::from_key(TEACHER);
630 // The exam has to be real: a mark is refused on one that isn't.
631 an_exam(&db, &exam, "midterm").await;
632 the_two_people(&db).await;
633
634 // Grade sitting #1, then a retake as sitting #2 — two rows, not one.
635 super::grade(
636 &db,
637 &exam,
638 &user,
639 1,
640 Mark::try_new(40).unwrap(),
641 &teacher,
642 "midterm",
643 )
644 .await
645 .unwrap();
646 let second = super::grade(
647 &db,
648 &exam,
649 &user,
650 2,
651 Mark::try_new(90).unwrap(),
652 &teacher,
653 "midterm",
654 )
655 .await
656 .unwrap();
657 assert_eq!(second.get_seq(), 2);
658
659 // Grade-of-record is the latest sitting's mark.
660 let latest = read_for_user(&db, &exam, &user)
661 .await
662 .unwrap()
663 .expect("graded");
664 assert_eq!(latest.get_mark().as_i64(), 90);
665 assert_eq!(latest.get_seq(), 2);
666
667 // The roster yields exactly one row per pair — the latest.
668 let roster = list_for_exam(&db, &exam).await.unwrap();
669 assert_eq!(roster.len(), 1);
670 assert_eq!(roster[0].get_mark().as_i64(), 90);
671
672 // History keeps both sittings, oldest first.
673 let history = list_all_for_exam_user(&db, &exam, &user).await.unwrap();
674 assert_eq!(
675 history
676 .iter()
677 .map(|r| r.get_mark().as_i64())
678 .collect::<Vec<_>>(),
679 vec![40, 90]
680 );
681
682 // Deleting the pair removes every sitting.
683 remove(&db, &exam, &user, "midterm").await.unwrap();
684 assert!(
685 list_all_for_exam_user(&db, &exam, &user)
686 .await
687 .unwrap()
688 .is_empty()
689 );
690 }
691
692 /// A deleted exam reads NONE, and NONE is falsy — the draft gate alone let
693 /// a mark land on an exam that no longer existed.
694 #[tokio::test]
695 async fn a_mark_is_refused_on_an_exam_that_no_longer_exists() {
696 let (db, _leases) = init_test_db().await;
697 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e2c1");
698 let user = UserId::from_key("019732e3-7b00-7000-8000-00000000a11a");
699 let teacher = UserId::from_key("019732e3-7b00-7000-8000-00000000acdc");
700
701 let refused = super::grade(
702 &db,
703 &exam,
704 &user,
705 1,
706 Mark::try_new(40).unwrap(),
707 &teacher,
708 "midterm",
709 )
710 .await;
711 assert!(matches!(refused, Err(AppError::NotFound)), "{refused:?}");
712 assert!(
713 list_all_for_exam_user(&db, &exam, &user)
714 .await
715 .unwrap()
716 .is_empty()
717 );
718 assert_eq!(counters(&db, "midterm").await, (0, 0));
719 }
720
721 /// The two counters, re-read out of the store — never off a return value.
722 /// A missing `kind_ref` row is a zero, and the exams' counts aggregate to
723 /// zero over an empty table the same way.
724 async fn counters(db: &Database, kind: &str) -> (i64, i64) {
725 let kind_count = sqlx::query("SELECT count FROM kind_ref WHERE name = $1")
726 .bind(kind)
727 .fetch_optional(db)
728 .await
729 .unwrap()
730 .map(|row| row.try_get::<i64, _>(0).unwrap())
731 .unwrap_or(0);
732 let exam_count = sqlx::query("SELECT COALESCE(sum(result_count), 0)::bigint FROM exam")
733 .fetch_one(db)
734 .await
735 .unwrap()
736 .try_get::<i64, _>(0)
737 .unwrap();
738 (kind_count, exam_count)
739 }
740
741 async fn an_exam(db: &Database, exam: &ExamId, kind: &str) {
742 // The exam has to be real: a mark is refused on one that isn't. Its
743 // creator is a real row (idempotently — [`the_two_people`] re-runs it)
744 // and so are its parents: the instance it is taught in and the term it
745 // is graded in, both through the shared fixtures.
746 let teacher = UserId::from_key(TEACHER);
747 sqlx::query(
748 "INSERT INTO app_user (id, username, created_at, role) \
749 VALUES ($1, 't', 0, 'teacher') ON CONFLICT (id) DO NOTHING",
750 )
751 .bind(teacher.uuid())
752 .execute(db)
753 .await
754 .unwrap();
755 let (instance, _course) = crate::db::course::a_test_instance(db).await;
756 let term = crate::db::term::a_test_term(db).await;
757 sqlx::query(
758 "INSERT INTO exam (id, creator, class_course, term, title, description, kind, \
759 max_attempts, allow_rejoin, allow_review, draft) \
760 VALUES ($1, $2, $3, $4, 't', '', $5, 1, true, false, false)",
761 )
762 .bind(exam.uuid())
763 .bind(teacher.uuid())
764 .bind(instance.uuid())
765 .bind(term.uuid())
766 .bind(kind)
767 .execute(db)
768 .await
769 .unwrap();
770 }
771
772 const STUDENT: &str = "019732e3-7b00-7000-8000-00000000a11a";
773 const TEACHER: &str = "019732e3-7b00-7000-8000-00000000acdc";
774
775 /// The tests' handle on [`super::grade`] with the grader and target
776 /// pinned to the two test people.
777 async fn grade(
778 db: &Database,
779 exam: &ExamId,
780 seq: i64,
781 mark: i64,
782 kind: &str,
783 ) -> Result<ExamResult, AppError> {
784 super::grade(
785 db,
786 exam,
787 &UserId::from_key(STUDENT),
788 seq,
789 Mark::try_new(mark).unwrap(),
790 &UserId::from_key(TEACHER),
791 kind,
792 )
793 .await
794 }
795
796 /// Both counters ride the mark's own transaction: a new mark claims each
797 /// exactly once, and a *regrade* of the same sitting claims neither — one
798 /// mark, one reference. Claimed-then-released around the write, a regrade
799 /// drifted them upward and froze the kind out of the settings for good.
800 #[tokio::test]
801 async fn a_new_mark_moves_both_counters_and_a_regrade_moves_neither() {
802 let (db, _leases) = init_test_db().await;
803 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1c4");
804 an_exam(&db, &exam, "midterm").await;
805 the_two_people(&db).await;
806
807 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
808 assert_eq!(counters(&db, "midterm").await, (1, 1));
809
810 // Same sitting, new mark: an overwrite, so neither counter moves.
811 let regraded = grade(&db, &exam, 1, 90, "midterm").await.unwrap();
812 assert_eq!(regraded.get_mark().as_i64(), 90);
813 assert_eq!(counters(&db, "midterm").await, (1, 1));
814
815 // A retake is a second row, so it does claim.
816 grade(&db, &exam, 2, 70, "midterm").await.unwrap();
817 assert_eq!(counters(&db, "midterm").await, (2, 2));
818 }
819
820 /// The two badge counters, re-read out of the store: the grader's marks
821 /// given and the student's high marks.
822 async fn badge_counters(db: &Database) -> (i64, i64) {
823 let given = sqlx::query("SELECT marks_given_total FROM app_user WHERE id = $1")
824 .bind(UserId::from_key(TEACHER).uuid())
825 .fetch_one(db)
826 .await
827 .unwrap()
828 .try_get::<i64, _>(0)
829 .unwrap();
830 let high = sqlx::query("SELECT high_mark_total FROM app_user WHERE id = $1")
831 .bind(UserId::from_key(STUDENT).uuid())
832 .fetch_one(db)
833 .await
834 .unwrap()
835 .try_get::<i64, _>(0)
836 .unwrap();
837 (given, high)
838 }
839
840 /// The rows a counter needs to land on — an `UPDATE` writes nothing to a
841 /// user that does not exist, so the badge tests must make both real.
842 /// Idempotent: [`an_exam`] may already have grown the teacher.
843 async fn the_two_people(db: &Database) {
844 for (role, key) in [("teacher", TEACHER), ("student", STUDENT)] {
845 sqlx::query(
846 "INSERT INTO app_user (id, username, created_at, role) \
847 VALUES ($1, $2, 0, $3) ON CONFLICT (id) DO NOTHING",
848 )
849 .bind(UserId::from_key(key).uuid())
850 .bind(key)
851 .bind(role)
852 .execute(db)
853 .await
854 .unwrap();
855 }
856 }
857
858 /// A first grade credits the grader once and the student only when the mark
859 /// clears the line; a regrade of the same sitting credits neither again,
860 /// while a retake — a distinct seq, so a distinct row — counts on its own.
861 #[tokio::test]
862 async fn a_grade_credits_the_grader_once_and_a_high_mark_the_student() {
863 let (db, _leases) = init_test_db().await;
864 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b2");
865 an_exam(&db, &exam, "midterm").await;
866 the_two_people(&db).await;
867
868 grade(&db, &exam, 1, 90, "midterm").await.unwrap();
869 assert_eq!(badge_counters(&db).await, (1, 1), "at the line earns it");
870
871 // Same sitting graded again: neither counter may move, however high.
872 grade(&db, &exam, 1, 100, "midterm").await.unwrap();
873 assert_eq!(badge_counters(&db).await, (1, 1), "a regrade moves nothing");
874
875 // A retake below the line: the grader is credited, the student is not.
876 grade(&db, &exam, 2, 89, "midterm").await.unwrap();
877 assert_eq!(badge_counters(&db).await, (2, 1), "89 is under the line");
878
879 // …and a high-scoring retake counts as its own sitting.
880 grade(&db, &exam, 3, 95, "midterm").await.unwrap();
881 assert_eq!(badge_counters(&db).await, (3, 2));
882 }
883
884 /// Ungrading gives both badge counters back, so grade → ungrade → regrade
885 /// nets to one credit however often it is run. Crediting the grade without
886 /// refunding the delete let that loop mint a badge off a single exam — and
887 /// an award, once earned, is never taken back.
888 #[tokio::test]
889 async fn ungrading_gives_the_badge_counters_back() {
890 let (db, _leases) = init_test_db().await;
891 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1ba");
892 an_exam(&db, &exam, "midterm").await;
893 the_two_people(&db).await;
894 let student = UserId::from_key(STUDENT);
895
896 for _ in 0..3 {
897 grade(&db, &exam, 1, 95, "midterm").await.unwrap();
898 assert_eq!(badge_counters(&db).await, (1, 1));
899 remove(&db, &exam, &student, "midterm")
900 .await
901 .unwrap()
902 .expect("the mark was there");
903 assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit");
904 // The kind's reference and the exam's count come back as before.
905 assert_eq!(counters(&db, "midterm").await, (0, 0));
906 }
907
908 // Every removed sitting is refunded, and only the ones that took: the
909 // grader gets both back, the student only the mark that cleared the line.
910 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
911 grade(&db, &exam, 2, 95, "midterm").await.unwrap();
912 assert_eq!(badge_counters(&db).await, (2, 1));
913 remove(&db, &exam, &student, "midterm")
914 .await
915 .unwrap()
916 .expect("both sittings were there");
917 assert_eq!(badge_counters(&db).await, (0, 0));
918
919 // Nothing to remove is nothing to give back — the floor holds.
920 assert!(
921 remove(&db, &exam, &student, "midterm")
922 .await
923 .unwrap()
924 .is_none()
925 );
926 assert_eq!(badge_counters(&db).await, (0, 0));
927 }
928
929 /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the
930 /// student's counter has to walk with it — the delete refunds off the mark
931 /// it finds stored, so a credit decided by a mark that is no longer there
932 /// is a credit nothing can give back. Left on the first-write branch alone,
933 /// grade-high → regrade-low → delete kept a phantom high mark every round
934 /// and looped it into a permanent badge.
935 #[tokio::test]
936 async fn a_regrade_across_the_line_moves_the_student_counter_with_it() {
937 let (db, _leases) = init_test_db().await;
938 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1e6");
939 an_exam(&db, &exam, "midterm").await;
940 the_two_people(&db).await;
941 let student = UserId::from_key(STUDENT);
942
943 // Up across the line: no row is added, but a high mark now exists.
944 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
945 assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line");
946 grade(&db, &exam, 1, 95, "midterm").await.unwrap();
947 assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up");
948 remove(&db, &exam, &student, "midterm")
949 .await
950 .unwrap()
951 .expect("the mark was there");
952 assert_eq!(badge_counters(&db).await, (0, 0));
953
954 // Down across it: the credit goes back the moment the mark does, so
955 // the delete has nothing left to refund and the counter still lands
956 // on zero rather than under it.
957 grade(&db, &exam, 1, 95, "midterm").await.unwrap();
958 assert_eq!(badge_counters(&db).await, (1, 1));
959 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
960 assert_eq!(
961 badge_counters(&db).await,
962 (1, 0),
963 "the regrade crossed down"
964 );
965 remove(&db, &exam, &student, "midterm")
966 .await
967 .unwrap()
968 .expect("the mark was there");
969 assert_eq!(badge_counters(&db).await, (0, 0));
970
971 // Both sides of a regrade above the line: nothing crosses, nothing moves.
972 grade(&db, &exam, 1, 90, "midterm").await.unwrap();
973 grade(&db, &exam, 1, 100, "midterm").await.unwrap();
974 assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one");
975
976 // The loop that minted the badge: three rounds of high → low → delete
977 // must leave the counter exactly where it started.
978 for _ in 0..3 {
979 grade(&db, &exam, 1, 95, "midterm").await.unwrap();
980 grade(&db, &exam, 1, 40, "midterm").await.unwrap();
981 remove(&db, &exam, &student, "midterm")
982 .await
983 .unwrap()
984 .expect("the mark was there");
985 }
986 assert_eq!(
987 badge_counters(&db).await,
988 (0, 0),
989 "the loop kept a high mark with no high mark stored"
990 );
991 }
992
993 /// The other half of the same asymmetry: a refund read off a stored mark
994 /// that was never credited eats a credit earned somewhere else. One exam
995 /// holds a genuine high mark while a second is graded low, regraded high
996 /// and deleted — the first exam's credit must still be standing.
997 #[tokio::test]
998 async fn one_exams_regrade_never_eats_another_exams_high_mark() {
999 let (db, _leases) = init_test_db().await;
1000 let first = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a8");
1001 let second = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1a9");
1002 an_exam(&db, &first, "midterm").await;
1003 an_exam(&db, &second, "midterm").await;
1004 the_two_people(&db).await;
1005 let student = UserId::from_key(STUDENT);
1006
1007 grade(&db, &first, 1, 95, "midterm").await.unwrap();
1008 assert_eq!(
1009 badge_counters(&db).await,
1010 (1, 1),
1011 "earned on the first exam"
1012 );
1013
1014 grade(&db, &second, 1, 40, "midterm").await.unwrap();
1015 grade(&db, &second, 1, 95, "midterm").await.unwrap();
1016 assert_eq!(badge_counters(&db).await, (2, 2));
1017 remove(&db, &second, &student, "midterm")
1018 .await
1019 .unwrap()
1020 .expect("the mark was there");
1021 assert_eq!(
1022 badge_counters(&db).await,
1023 (1, 1),
1024 "the first exam's high mark was eaten"
1025 );
1026 }
1027
1028 /// A refused mark leaves the badge counters where the other two are left.
1029 #[tokio::test]
1030 async fn a_refused_mark_credits_nobody() {
1031 let (db, _leases) = init_test_db().await;
1032 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1b3");
1033 an_exam(&db, &exam, "midterm").await;
1034 the_two_people(&db).await;
1035 sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1")
1036 .bind(exam.uuid())
1037 .execute(&db)
1038 .await
1039 .unwrap();
1040
1041 assert!(grade(&db, &exam, 1, 100, "midterm").await.is_err());
1042 assert_eq!(badge_counters(&db).await, (0, 0));
1043 }
1044
1045 /// A retired kind refuses the claim from inside the transaction, which
1046 /// takes the mark and the exam's counter down with it — the settings guard
1047 /// enforcing the same invariant from the other side.
1048 #[tokio::test]
1049 async fn a_retired_kind_refuses_the_mark_and_leaves_both_counters_alone() {
1050 let (db, _leases) = init_test_db().await;
1051 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1f7");
1052 an_exam(&db, &exam, "midterm").await;
1053 // Retire the kind the way the settings guard does: the counter row
1054 // flips to retired, which nothing references yet, so the flip lands.
1055 sqlx::query(
1056 "INSERT INTO kind_ref (name, count, retired) VALUES ('midterm', 0, TRUE)
1057 ON CONFLICT (name) DO UPDATE SET retired = TRUE
1058 WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE",
1059 )
1060 .execute(&db)
1061 .await
1062 .unwrap();
1063
1064 let refused = grade(&db, &exam, 1, 40, "midterm").await;
1065 assert!(
1066 matches!(&refused, Err(AppError::ConflictOwned(message))
1067 if message.contains("has been removed from the school's settings")),
1068 "{refused:?}"
1069 );
1070 assert!(
1071 list_for_exam(&db, &exam).await.unwrap().is_empty(),
1072 "the mark must not have landed"
1073 );
1074 assert_eq!(counters(&db, "midterm").await, (0, 0));
1075 }
1076
1077 /// A draft exam refuses the mark, and the counters stay put — the gate
1078 /// runs before the claim now, so there is nothing to give back.
1079 #[tokio::test]
1080 async fn a_draft_exam_refuses_the_mark_and_leaves_both_counters_alone() {
1081 let (db, _leases) = init_test_db().await;
1082 let exam = ExamId::from_key("019732e3-7b00-7000-8000-00000000e1d5");
1083 an_exam(&db, &exam, "midterm").await;
1084 sqlx::query("UPDATE exam SET draft = TRUE WHERE id = $1")
1085 .bind(exam.uuid())
1086 .execute(&db)
1087 .await
1088 .unwrap();
1089
1090 let refused = grade(&db, &exam, 1, 40, "midterm").await;
1091 assert!(matches!(refused, Err(AppError::Conflict(_))), "{refused:?}");
1092 assert!(list_for_exam(&db, &exam).await.unwrap().is_empty());
1093 assert_eq!(counters(&db, "midterm").await, (0, 0));
1094 }
1095}