diff --git a/src/constant.rs b/src/constant.rs index 493b0ad..f0819d6 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -857,19 +857,30 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; /// below; released when a board is deleted. pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; /// The lifetime totals behind the badges, all on the user row. Not caps: each -/// one counts something the student *did*. Only the two homework counters ever -/// come down, and in exactly one case — a student withdrawing their own -/// submission — because that route is self-service and a strictly monotonic -/// counter would let one homework be farmed into fifty by submit/delete/submit. -/// The exam and pomodoro totals never decrease at all: there is no student-facing -/// delete behind them, so sitting an exam or finishing a stint is a lifetime -/// fact. Nothing else decrements: a teacher's delete and the course cascade -/// (which do take the attempt rows with them) leave them alone, -/// since history a teacher erased is still history the student lived. A badge -/// already earned is never taken back either, whatever a counter does -/// afterwards — [`crate::domain::badge`] only ever adds award rows. Floored at -/// zero, and absent means zero: an account older than the columns reads exactly -/// like a fresh one. +/// one counts something the person *did*. A counter comes down in exactly one +/// shape, and the two cases that qualify share a reason: the account credited +/// is the account that can delete what earned it, so a strictly monotonic +/// counter is a farm. A student withdrawing their own submission gives the two +/// homework counters back (else one homework becomes fifty by +/// submit/delete/submit), and a teacher un-grading gives back +/// `MARKS_GIVEN` — with `HIGH_MARK` on the exam side, credited to the student +/// by the same act (else one exam becomes fifty by grade/ungrade/regrade). +/// The exam and pomodoro totals never decrease at all: there is no delete +/// behind them but a teacher's, so sitting an exam or finishing a stint is a +/// lifetime fact. Nothing else decrements: the cascades (an exam, a homework or +/// a course delete, which do take the attempt and result rows with them) leave +/// them alone, since history a teacher erased is still history the student +/// lived. A badge already earned is never taken back either, whatever a counter +/// does afterwards — [`crate::domain::badge`] only ever adds award rows. Floored +/// at zero, and absent means zero: an account older than the columns reads +/// exactly like a fresh one. +// +// ponytail: that cascade ruling is also the farm's long way round — delete the +// *exam* instead of the mark and the credit stands, so the loop still climbs, +// at a couple of requests a point rather than two. Closing it means +// `Exam::delete`, `Homework::delete` and `Course::delete` refunding per swept +// row the way `ExamResult::remove` now does, which is a policy call (a course +// delete would then have to walk every mark it drops) rather than an oversight. pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total"; pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total"; pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total"; diff --git a/src/domain/exam_result.rs b/src/domain/exam_result.rs index a327501..324dd14 100644 --- a/src/domain/exam_result.rs +++ b/src/domain/exam_result.rs @@ -383,6 +383,18 @@ impl ExamResult { /// Delete every sitting's mark for one (exam, user) pair. `kind` is the /// exam's: the marks give their references back, so a kind nothing is /// graded under any more can leave the settings again. + /// + /// The two badge counters come back the same way, and for a reason the + /// other counters do not need: [`grade`](Self::grade) credits them on the + /// branch that finds no row, and a deleted row *is* no row. Left standing, + /// ungrade-then-regrade credited a second time off one stored mark, and + /// looped it minted a badge from a single exam — permanently, since an + /// award is never revoked. Each is given back off the rows this statement + /// actually deleted: `marks_given_total` to each row's *own* grader (two + /// teachers can hold two sittings of the same pair), and `high_mark_total` + /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the + /// `BEFORE` image rather than re-derived — the mark that was credited is + /// the mark that was stored. pub async fn remove( exam: &ExamId, user: &UserId, @@ -414,6 +426,16 @@ impl ExamResult { math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]); UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} = math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]); + LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]); + IF $high > 0 {{ + UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} = + math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0]) + }}; + FOR $row IN $gone {{ + LET $grader = $row.graded_by; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; }}; RETURN $gone; COMMIT TRANSACTION;" @@ -702,6 +724,51 @@ mod tests { assert_eq!(badge_counters(&db).await, (3, 2)); } + /// Ungrading gives both badge counters back, so grade → ungrade → regrade + /// nets to one credit however often it is run. Crediting the grade without + /// refunding the delete let that loop mint a badge off a single exam — and + /// an award, once earned, is never taken back. + #[tokio::test] + async fn ungrading_gives_the_badge_counters_back() { + let db = init_mem().await.unwrap(); + let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA"); + an_exam(&db, &exam, "midterm").await; + the_two_people(&db).await; + let student = UserId::from_key(STUDENT); + + for _ in 0..3 { + grade(&db, &exam, 1, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (1, 1)); + ExamResult::remove(&exam, &student, "midterm", &db) + .await + .unwrap() + .expect("the mark was there"); + assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit"); + // The kind's reference and the exam's count come back as before. + assert_eq!(counters(&db, "midterm").await, (0, 0)); + } + + // Every removed sitting is refunded, and only the ones that took: the + // grader gets both back, the student only the mark that cleared the line. + grade(&db, &exam, 1, 40, "midterm").await.unwrap(); + grade(&db, &exam, 2, 95, "midterm").await.unwrap(); + assert_eq!(badge_counters(&db).await, (2, 1)); + ExamResult::remove(&exam, &student, "midterm", &db) + .await + .unwrap() + .expect("both sittings were there"); + assert_eq!(badge_counters(&db).await, (0, 0)); + + // Nothing to remove is nothing to give back — the floor holds. + assert!( + ExamResult::remove(&exam, &student, "midterm", &db) + .await + .unwrap() + .is_none() + ); + assert_eq!(badge_counters(&db).await, (0, 0)); + } + /// A refused mark leaves the badge counters where the other two are left. #[tokio::test] async fn a_refused_mark_credits_nobody() { diff --git a/src/domain/homework_result.rs b/src/domain/homework_result.rs index 1aa0634..e99da96 100644 --- a/src/domain/homework_result.rs +++ b/src/domain/homework_result.rs @@ -16,7 +16,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, }; -use crate::database::Database; +use crate::database::{Database, transaction_with_retry}; use crate::domain::course::CourseId; use crate::domain::exam_result::Mark; use crate::domain::homework::HomeworkId; @@ -262,29 +262,62 @@ impl HomeworkResult { /// stamp [`grade`](Self::grade) left on it is cleared in the same /// transaction — scoped to *this* grade's id, so it can never wipe a stamp a /// concurrent re-grade has just written. + /// + /// The grader's `marks_given_total` comes back with it, in that same + /// transaction and only when a row was really deleted. [`grade`](Self::grade) + /// credits on the branch that finds no row, and a deleted row *is* no row: + /// left standing, ungrade-then-regrade credited a second time off one + /// stored grade, and looped it minted a badge with no exam, no mark and no + /// submission behind it — permanently, since an award is never revoked. + /// Given back to the *removed row's own* grader, not the caller: a manager + /// may un-grade what a teacher graded, and the credit is the teacher's. + /// + /// Sound to re-send while the store answers "conflict, retry" — this is the + /// upgrade `grade` still wants, taken here because the counter above is what + /// makes it necessary: the grader's row is written by exam grading too, so + /// the delete now contends with another domain, and only `DELETE`/`UPDATE` + /// are in the batch, none of which can legitimately answer "already exists". pub async fn remove( homework: &HomeworkId, user: &UserId, db: &Database, ) -> Result, AppError> { let id = HomeworkResultId::composite(homework, user); - let mut result = db - .query(format!( + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( "BEGIN TRANSACTION; - DELETE $id RETURN BEFORE; + LET $gone = (DELETE $id RETURN BEFORE); UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ WHERE {SUBMISSION_GRADED_FIELD} = $id; + IF array::len($gone) > 0 {{ + LET $grader = $gone[0].graded_by; + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) + }}; + RETURN $gone; COMMIT TRANSACTION;" - )) - .bind(("id", id.record())) - .bind(( - "sub", - HomeworkSubmissionId::composite(homework, user).record(), - )) - .await? - .check()?; - // BEGIN is slot 0; the grade's DELETE is slot 1, the unstamp slot 2. - Ok(result.take::>(1)?.into_iter().next()) + ), + &[ + ("id".into(), id.record().into_value()), + ( + "sub".into(), + HomeworkSubmissionId::composite(homework, user) + .record() + .into_value(), + ), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, so + // its slot follows the statement count — the hand-kept "slot 1" this + // replaces was one added statement away from handing back the unstamp. + let slot = result.num_statements().saturating_sub(2); + Ok(result.take::>(slot)?.into_iter().next()) } } @@ -403,6 +436,55 @@ mod tests { ); } + /// Un-grading gives the credit back, so grade → ungrade → regrade nets to + /// one however often it is run. Crediting the grade without refunding the + /// delete was the cheapest counter farm in the codebase — two requests per + /// mark given, with no exam, no mark and no submission behind them. + #[tokio::test] + async fn ungrading_gives_the_grader_credit_back() { + let db = crate::database::init_mem().await.unwrap(); + let homework = HomeworkId::from_key("01TESTHWUNGRADEAAAAAAAAAAA"); + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); + db.query("CREATE $usr SET username = 't', password_hash = 'x'") + .bind(("usr", teacher.record())) + .await + .unwrap() + .check() + .unwrap(); + + for _ in 0..3 { + HomeworkResult::grade( + &homework, + &user, + HomeworkStatus::try_new("missing").unwrap(), + None, + &teacher, + &db, + ) + .await + .unwrap(); + assert_eq!(marks_given(&teacher, &db).await, 1); + assert!( + HomeworkResult::remove(&homework, &user, &db) + .await + .unwrap() + .is_some(), + "the grade was there" + ); + assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one"); + } + + // Nothing to remove is nothing to give back — the floor holds. + assert!( + HomeworkResult::remove(&homework, &user, &db) + .await + .unwrap() + .is_none() + ); + assert_eq!(marks_given(&teacher, &db).await, 0); + } + /// The grader's badge counter, re-read out of the store. async fn marks_given(user: &UserId, db: &Database) -> i64 { let mut result = db