forge
Explore
Log in

Don't you dare go Hollow

πŸŽ–οΈ give the grade credit back when a grade is deleted

Browse files at this commit

6197fc3dc2c2d2856037eea61e97766a06ce7d4dAhmet Kaan GümüşParent: b0f72a5
  • fix
    • πŸŽ–οΈ give the grade credit back when a grade is deleted
Show full message
fix: πŸŽ–οΈ give the grade credit back when a grade is deleted

Both grade sites credit on the branch that finds no row, and a deleted row
reads as no row β€” so ungrade-then-regrade credited a second time off one
stored mark. Looped, one teacher and one student minted marks_given_250 and
high_mark_25 from a single exam, or from a homework with no submission behind
it at all, and an award once earned is never revoked.

Each delete now refunds inside its own transaction and only for rows it really
removed: marks_given_total to each removed row's own grader (a manager may
un-grade what a teacher graded), and high_mark_total off the removed mark's
BEFORE image. Floored at zero, so a row predating the columns cannot push one
negative. HomeworkResult::remove takes the transaction_with_retry upgrade its
sibling already wanted β€” the new counter is what makes it necessary, since the
grader's row is written by exam grading too β€” and with it the hand-kept slot 1
becomes the usual trailing-RETURN count.

The rule in constant.rs said the opposite; it now states which routes refund
and why, and names the cascades as the one leak left open.
src/constant.rsmodified+24 -13
@@ -857,19 +857,30 @@ pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count";
857 /// below; released when a board is deleted.857 /// below; released when a board is deleted.
858 pub const USER_BOARD_COUNT_FIELD: &str = "board_count";858 pub const USER_BOARD_COUNT_FIELD: &str = "board_count";
859 /// The lifetime totals behind the badges, all on the user row. Not caps: each859 /// The lifetime totals behind the badges, all on the user row. Not caps: each
860-/// one counts something the student *did*. Only the two homework counters ever860+/// one counts something the person *did*. A counter comes down in exactly one
861-/// come down, and in exactly one case β€” a student withdrawing their own861+/// shape, and the two cases that qualify share a reason: the account credited
862-/// submission β€” because that route is self-service and a strictly monotonic862+/// is the account that can delete what earned it, so a strictly monotonic
863-/// counter would let one homework be farmed into fifty by submit/delete/submit.863+/// counter is a farm. A student withdrawing their own submission gives the two
864-/// The exam and pomodoro totals never decrease at all: there is no student-facing864+/// homework counters back (else one homework becomes fifty by
865-/// delete behind them, so sitting an exam or finishing a stint is a lifetime865+/// submit/delete/submit), and a teacher un-grading gives back
866-/// fact. Nothing else decrements: a teacher's delete and the course cascade866+/// `MARKS_GIVEN` β€” with `HIGH_MARK` on the exam side, credited to the student
867-/// (which do take the attempt rows with them) leave them alone,867+/// by the same act (else one exam becomes fifty by grade/ungrade/regrade).
868-/// since history a teacher erased is still history the student lived. A badge868+/// The exam and pomodoro totals never decrease at all: there is no delete
869-/// already earned is never taken back either, whatever a counter does869+/// behind them but a teacher's, so sitting an exam or finishing a stint is a
870-/// afterwards β€” [`crate::domain::badge`] only ever adds award rows. Floored at870+/// lifetime fact. Nothing else decrements: the cascades (an exam, a homework or
871-/// zero, and absent means zero: an account older than the columns reads exactly871+/// a course delete, which do take the attempt and result rows with them) leave
872-/// like a fresh one.872+/// them alone, since history a teacher erased is still history the student
873+/// lived. A badge already earned is never taken back either, whatever a counter
874+/// does afterwards β€” [`crate::domain::badge`] only ever adds award rows. Floored
875+/// at zero, and absent means zero: an account older than the columns reads
876+/// exactly like a fresh one.
877+//
878+// ponytail: that cascade ruling is also the farm's long way round β€” delete the
879+// *exam* instead of the mark and the credit stands, so the loop still climbs,
880+// at a couple of requests a point rather than two. Closing it means
881+// `Exam::delete`, `Homework::delete` and `Course::delete` refunding per swept
882+// row the way `ExamResult::remove` now does, which is a policy call (a course
883+// delete would then have to walk every mark it drops) rather than an oversight.
873 pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";884 pub const HOMEWORK_SUBMITTED_TOTAL_FIELD: &str = "homework_submitted_total";
874 pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";885 pub const HOMEWORK_ON_TIME_TOTAL_FIELD: &str = "homework_on_time_total";
875 pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";886 pub const EXAM_SAT_TOTAL_FIELD: &str = "exam_sat_total";
src/domain/exam_result.rsmodified+67 -0
@@ -383,6 +383,18 @@ impl ExamResult {
383 /// Delete every sitting's mark for one (exam, user) pair. `kind` is the383 /// Delete every sitting's mark for one (exam, user) pair. `kind` is the
384 /// exam's: the marks give their references back, so a kind nothing is384 /// exam's: the marks give their references back, so a kind nothing is
385 /// graded under any more can leave the settings again.385 /// graded under any more can leave the settings again.
386+ ///
387+ /// The two badge counters come back the same way, and for a reason the
388+ /// other counters do not need: [`grade`](Self::grade) credits them on the
389+ /// branch that finds no row, and a deleted row *is* no row. Left standing,
390+ /// ungrade-then-regrade credited a second time off one stored mark, and
391+ /// looped it minted a badge from a single exam β€” permanently, since an
392+ /// award is never revoked. Each is given back off the rows this statement
393+ /// actually deleted: `marks_given_total` to each row's *own* grader (two
394+ /// teachers can hold two sittings of the same pair), and `high_mark_total`
395+ /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the
396+ /// `BEFORE` image rather than re-derived β€” the mark that was credited is
397+ /// the mark that was stored.
386 pub async fn remove(398 pub async fn remove(
387 exam: &ExamId,399 exam: &ExamId,
388 user: &UserId,400 user: &UserId,
@@ -414,6 +426,16 @@ impl ExamResult {
414 math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]);426 math::max([({REF_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
415 UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} =427 UPDATE $ex SET {EXAM_RESULT_COUNT_FIELD} =
416 math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]);428 math::max([({EXAM_RESULT_COUNT_FIELD} ?? 0) - array::len($gone), 0]);
429+ LET $high = array::len($gone[WHERE mark >= {HIGH_MARK_MIN}]);
430+ IF $high > 0 {{
431+ UPDATE $usr SET {HIGH_MARK_TOTAL_FIELD} =
432+ math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) - $high, 0])
433+ }};
434+ FOR $row IN $gone {{
435+ LET $grader = $row.graded_by;
436+ UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
437+ math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])
438+ }};
417 }};439 }};
418 RETURN $gone;440 RETURN $gone;
419 COMMIT TRANSACTION;"441 COMMIT TRANSACTION;"
@@ -702,6 +724,51 @@ mod tests {
702 assert_eq!(badge_counters(&db).await, (3, 2));724 assert_eq!(badge_counters(&db).await, (3, 2));
703 }725 }
704 726
727+ /// Ungrading gives both badge counters back, so grade β†’ ungrade β†’ regrade
728+ /// nets to one credit however often it is run. Crediting the grade without
729+ /// refunding the delete let that loop mint a badge off a single exam β€” and
730+ /// an award, once earned, is never taken back.
731+ #[tokio::test]
732+ async fn ungrading_gives_the_badge_counters_back() {
733+ let db = init_mem().await.unwrap();
734+ let exam = ExamId::from_key("01TESTEXAMUNGRADEAAAAAAAAA");
735+ an_exam(&db, &exam, "midterm").await;
736+ the_two_people(&db).await;
737+ let student = UserId::from_key(STUDENT);
738+
739+ for _ in 0..3 {
740+ grade(&db, &exam, 1, 95, "midterm").await.unwrap();
741+ assert_eq!(badge_counters(&db).await, (1, 1));
742+ ExamResult::remove(&exam, &student, "midterm", &db)
743+ .await
744+ .unwrap()
745+ .expect("the mark was there");
746+ assert_eq!(badge_counters(&db).await, (0, 0), "the loop kept a credit");
747+ // The kind's reference and the exam's count come back as before.
748+ assert_eq!(counters(&db, "midterm").await, (0, 0));
749+ }
750+
751+ // Every removed sitting is refunded, and only the ones that took: the
752+ // grader gets both back, the student only the mark that cleared the line.
753+ grade(&db, &exam, 1, 40, "midterm").await.unwrap();
754+ grade(&db, &exam, 2, 95, "midterm").await.unwrap();
755+ assert_eq!(badge_counters(&db).await, (2, 1));
756+ ExamResult::remove(&exam, &student, "midterm", &db)
757+ .await
758+ .unwrap()
759+ .expect("both sittings were there");
760+ assert_eq!(badge_counters(&db).await, (0, 0));
761+
762+ // Nothing to remove is nothing to give back β€” the floor holds.
763+ assert!(
764+ ExamResult::remove(&exam, &student, "midterm", &db)
765+ .await
766+ .unwrap()
767+ .is_none()
768+ );
769+ assert_eq!(badge_counters(&db).await, (0, 0));
770+ }
771+
705 /// A refused mark leaves the badge counters where the other two are left.772 /// A refused mark leaves the badge counters where the other two are left.
706 #[tokio::test]773 #[tokio::test]
707 async fn a_refused_mark_credits_nobody() {774 async fn a_refused_mark_credits_nobody() {
src/domain/homework_result.rsmodified+96 -14
@@ -16,7 +16,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
16 use crate::constant::{16 use crate::constant::{
17 HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD,17 HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD,
18 };18 };
19-use crate::database::Database;19+use crate::database::{Database, transaction_with_retry};
20 use crate::domain::course::CourseId;20 use crate::domain::course::CourseId;
21 use crate::domain::exam_result::Mark;21 use crate::domain::exam_result::Mark;
22 use crate::domain::homework::HomeworkId;22 use crate::domain::homework::HomeworkId;
@@ -262,29 +262,62 @@ impl HomeworkResult {
262 /// stamp [`grade`](Self::grade) left on it is cleared in the same262 /// stamp [`grade`](Self::grade) left on it is cleared in the same
263 /// transaction β€” scoped to *this* grade's id, so it can never wipe a stamp a263 /// transaction β€” scoped to *this* grade's id, so it can never wipe a stamp a
264 /// concurrent re-grade has just written.264 /// concurrent re-grade has just written.
265+ ///
266+ /// The grader's `marks_given_total` comes back with it, in that same
267+ /// transaction and only when a row was really deleted. [`grade`](Self::grade)
268+ /// credits on the branch that finds no row, and a deleted row *is* no row:
269+ /// left standing, ungrade-then-regrade credited a second time off one
270+ /// stored grade, and looped it minted a badge with no exam, no mark and no
271+ /// submission behind it β€” permanently, since an award is never revoked.
272+ /// Given back to the *removed row's own* grader, not the caller: a manager
273+ /// may un-grade what a teacher graded, and the credit is the teacher's.
274+ ///
275+ /// Sound to re-send while the store answers "conflict, retry" β€” this is the
276+ /// upgrade `grade` still wants, taken here because the counter above is what
277+ /// makes it necessary: the grader's row is written by exam grading too, so
278+ /// the delete now contends with another domain, and only `DELETE`/`UPDATE`
279+ /// are in the batch, none of which can legitimately answer "already exists".
265 pub async fn remove(280 pub async fn remove(
266 homework: &HomeworkId,281 homework: &HomeworkId,
267 user: &UserId,282 user: &UserId,
268 db: &Database,283 db: &Database,
269 ) -> Result<Option<HomeworkResult>, AppError> {284 ) -> Result<Option<HomeworkResult>, AppError> {
270 let id = HomeworkResultId::composite(homework, user);285 let id = HomeworkResultId::composite(homework, user);
271- let mut result = db286+ let (mut result, mut errors) = transaction_with_retry(
272- .query(format!(287+ db,
288+ &format!(
273 "BEGIN TRANSACTION;289 "BEGIN TRANSACTION;
274- DELETE $id RETURN BEFORE;290+ LET $gone = (DELETE $id RETURN BEFORE);
275 UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \291 UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \
276 WHERE {SUBMISSION_GRADED_FIELD} = $id;292 WHERE {SUBMISSION_GRADED_FIELD} = $id;
293+ IF array::len($gone) > 0 {{
294+ LET $grader = $gone[0].graded_by;
295+ UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
296+ math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0])
297+ }};
298+ RETURN $gone;
277 COMMIT TRANSACTION;"299 COMMIT TRANSACTION;"
278- ))300+ ),
279- .bind(("id", id.record()))301+ &[
280- .bind((302+ ("id".into(), id.record().into_value()),
281- "sub",303+ (
282- HomeworkSubmissionId::composite(homework, user).record(),304+ "sub".into(),
283- ))305+ HomeworkSubmissionId::composite(homework, user)
284- .await?306+ .record()
285- .check()?;307+ .into_value(),
286- // BEGIN is slot 0; the grade's DELETE is slot 1, the unstamp slot 2.308+ ),
287- Ok(result.take::<Vec<HomeworkResult>>(1)?.into_iter().next())309+ ],
310+ &[],
311+ )
312+ .await?;
313+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
314+ return Err(error.into());
315+ }
316+ // The trailing `RETURN` is always the last statement before `COMMIT`, so
317+ // its slot follows the statement count β€” the hand-kept "slot 1" this
318+ // replaces was one added statement away from handing back the unstamp.
319+ let slot = result.num_statements().saturating_sub(2);
320+ Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next())
288 }321 }
289 }322 }
290 323
@@ -403,6 +436,55 @@ mod tests {
403 );436 );
404 }437 }
405 438
439+ /// Un-grading gives the credit back, so grade β†’ ungrade β†’ regrade nets to
440+ /// one however often it is run. Crediting the grade without refunding the
441+ /// delete was the cheapest counter farm in the codebase β€” two requests per
442+ /// mark given, with no exam, no mark and no submission behind them.
443+ #[tokio::test]
444+ async fn ungrading_gives_the_grader_credit_back() {
445+ let db = crate::database::init_mem().await.unwrap();
446+ let homework = HomeworkId::from_key("01TESTHWUNGRADEAAAAAAAAAAA");
447+ let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA");
448+ let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA");
449+ db.query("CREATE $usr SET username = 't', password_hash = 'x'")
450+ .bind(("usr", teacher.record()))
451+ .await
452+ .unwrap()
453+ .check()
454+ .unwrap();
455+
456+ for _ in 0..3 {
457+ HomeworkResult::grade(
458+ &homework,
459+ &user,
460+ HomeworkStatus::try_new("missing").unwrap(),
461+ None,
462+ &teacher,
463+ &db,
464+ )
465+ .await
466+ .unwrap();
467+ assert_eq!(marks_given(&teacher, &db).await, 1);
468+ assert!(
469+ HomeworkResult::remove(&homework, &user, &db)
470+ .await
471+ .unwrap()
472+ .is_some(),
473+ "the grade was there"
474+ );
475+ assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one");
476+ }
477+
478+ // Nothing to remove is nothing to give back β€” the floor holds.
479+ assert!(
480+ HomeworkResult::remove(&homework, &user, &db)
481+ .await
482+ .unwrap()
483+ .is_none()
484+ );
485+ assert_eq!(marks_given(&teacher, &db).await, 0);
486+ }
487+
406 /// The grader's badge counter, re-read out of the store.488 /// The grader's badge counter, re-read out of the store.
407 async fn marks_given(user: &UserId, db: &Database) -> i64 {489 async fn marks_given(user: &UserId, db: &Database) -> i64 {
408 let mut result = db490 let mut result = db