forge
Explore
Log in

Don't you dare go Hollow

Stop a corrected mark leaving a high mark nothing can take back

Browse files at this commit

c1a0c3b3fe43d081d7c91308aa7264f40fa0adc9Ahmet Kaan GümüşParent: 174a277
  • fix
    • stop a corrected mark leaving a high mark nothing can take back
Show full message
🎯 fix: stop a corrected mark leaving a high mark nothing can take back

The credit and the refund on `high_mark_total` read different values. The
credit was decided in Rust from the *incoming* mark and buried on the
first-write branch, so a regrade of the same sitting moved it never; the
refund reads the mark actually *stored* on the deleted row. A sitting graded
95 and corrected to 40 therefore kept a credit the delete could not find —
grade high, regrade low, delete, repeat, and the counter climbed without
bound off one exam, minting `high_mark_10` and `high_mark_25` permanently,
since an award is never revoked. It cut the other way too: a genuine 95 on
one exam was eaten by a second exam graded low, regraded high and deleted,
whose refund found a stored high mark it had never been credited for.

Fixed as a delta rather than a stamp on the row. `$before` already had to be
read inside the transaction to decide the claim branch, so reading the
sitting's previous *mark* there instead of its id costs nothing and needs no
new column and no backfill — `HIGH_MARK_MIN` is a threshold on a value the
row already stores, so a stamp would only duplicate it. The counter then
moves by the difference between the two sides of the line: +1 crossing up,
-1 crossing down, nothing when both marks sit on the same side, which keeps
an ordinary correction off the student's row entirely as before. Credit and
refund now read the same value, and the counter can no longer exceed the
number of stored marks at or above the cut.

Both regrade directions, a correction above the line, the inflate loop and
the cross-exam theft are pinned in `exam_result`'s tests; all five go red
against the old shape. The integration pin that asserted a regrade must not
move the counter asserted the defect — it contradicted both the README and
the refund — and now asserts the crossing.
README.mdmodified+8 -1
@@ -1340,7 +1340,14 @@ catalog — awards carrying it stop being served, no migration.
1340 course) does not: a cascade is not an un-grade.1340 course) does not: a cascade is not an un-grade.
1341 - **High marks.** `+1 high_mark_total` for the **student** whenever an exam1341 - **High marks.** `+1 high_mark_total` for the **student** whenever an exam
1342 mark lands at or above `badges.high_mark_min` (90, published at `/limits`),1342 mark lands at or above `badges.high_mark_min` (90, published at `/limits`),
1343- once per sitting — a retake is another sitting and can earn another. Homework1343+ once per sitting — a retake is another sitting and can earn another. Unlike
1344+ the grader's counter, a **regrade does move it**, in whichever direction it
1345+ crossed the line: it counts marks that are *stored* at or above the cut, not
1346+ first gradings, so 40 corrected to 95 earns it and 95 corrected to 40 hands it
1347+ straight back (a correction that stays on one side of the line moves nothing).
1348+ It has to work that way, because the refund below reads the stored mark — the
1349+ two decided off different values, and a mark walked across the line left a
1350+ credit no delete could find to give back. Homework
1344 marks never count here: a homework mark is optional and most grades are1351 marks never count here: a homework mark is optional and most grades are
1345 status-only, so counting them would reward a teacher's habit rather than a1352 status-only, so counting them would reward a teacher's habit rather than a
1346 student's work. The cut is compiled in rather than read from the school's1353 student's work. The cut is compiled in rather than read from the school's
src/domain/exam_result.rsmodified+136 -26
@@ -203,13 +203,23 @@ impl ExamResult {
203 /// both counters where they are — there is no claim to give back, and so no203 /// both counters where they are — there is no claim to give back, and so no
204 /// window in which a crash could fail to give it.204 /// window in which a crash could fail to give it.
205 ///205 ///
206- /// The two badge counters ride that same first-time branch: the grader's206+ /// The grader's `marks_given_total` rides that same first-time branch: a
207- /// `marks_given_total`, and — only when the mark clears207+ /// regrade of a sitting moves it however often it is run, while a retake,
208- /// [`HIGH_MARK_MIN`] — the student's `high_mark_total`. So a regrade of a208+ /// being a distinct `seq` and so a distinct row, counts on its own.
209- /// sitting moves neither however often it is run, while a retake, being a209+ ///
210- /// distinct `seq` and so a distinct row, counts on its own. They are210+ /// The student's `high_mark_total` cannot ride it, because it is not a
211- /// written field-scoped: a user row also carries admin-owned data (`role`)211+ /// count of rows but a count of rows *at or above* [`HIGH_MARK_MIN`], and a
212- /// that a whole-row save would revert.212+ /// regrade moves a mark across that line without adding or removing a row.
213+ /// It moves by the difference between the mark about to be stored and the
214+ /// one already there — `+1` crossing up, `-1` crossing down, nothing at all
215+ /// when both sides sit on the same side of the line, so an overwrite still
216+ /// costs the student's row no write unless the answer actually changed.
217+ /// Decided on the first branch alone it drifted upward without bound: 95
218+ /// credited, regraded to 40 (no row added, so no move), then deleted, whose
219+ /// refund reads the *stored* mark and so found nothing to give back — a
220+ /// counter of one over zero stored high marks, looped into a permanent
221+ /// badge. Both counters are written field-scoped: a user row also carries
222+ /// admin-owned data (`role`) that a whole-row save would revert.
213 pub async fn grade(223 pub async fn grade(
214 exam: &ExamId,224 exam: &ExamId,
215 user: &UserId,225 user: &UserId,
@@ -239,10 +249,14 @@ impl ExamResult {
239 // exam survive my claim?" check moot: the claim now sits behind this249 // exam survive my claim?" check moot: the claim now sits behind this
240 // gate instead of in front of it.250 // gate instead of in front of it.
241 //251 //
242- // Whether the row was already there decides both counters, and it is252+ // `$before` is the sitting's *previous mark*, and it answers both
243- // read one statement before them inside the same transaction — read253+ // questions off one read: `mark` is a mandatory column on a schemafull
244- // anywhere else it would be a guess about a row two graders may be254+ // row, so `NONE` there means no row at all — the claim branch — while a
245- // writing at once.255+ // number is what the student's counter takes its difference against.
256+ // Read one statement before the counters inside the same transaction:
257+ // read anywhere else it would be a guess about a row two graders may be
258+ // writing at once, and the difference would be taken against a mark
259+ // some other round had already replaced.
246 //260 //
247 // Re-sent while the store answers "conflict, retry": the gates read a261 // Re-sent while the store answers "conflict, retry": the gates read a
248 // column an exam PATCH writes, and the counters are the ones a262 // column an exam PATCH writes, and the counters are the ones a
@@ -255,17 +269,6 @@ impl ExamResult {
255 // the index entry can only ever point at the row the id already names269 // the index entry can only ever point at the row the id already names
256 // and the write resolves onto it. A lost round aborts having written270 // and the write resolves onto it. A lost round aborts having written
257 // nothing, counters included.271 // nothing, counters included.
258- // Below the line the student's counter is left out of the statement
259- // list entirely, rather than added to by a zero: a low mark is most
260- // marks, and it must not write the student's row at all.
261- let high_mark = if mark.as_i64() >= HIGH_MARK_MIN {
262- format!(
263- "UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} =
264- ({HIGH_MARK_TOTAL_FIELD} ?? 0) + 1;"
265- )
266- } else {
267- String::new()
268- };
269 let _guard = cap::counter_lock().await;272 let _guard = cap::counter_lock().await;
270 let (mut written, mut errors) = transaction_with_retry(273 let (mut written, mut errors) = transaction_with_retry(
271 db,274 db,
@@ -273,7 +276,7 @@ impl ExamResult {
273 "BEGIN TRANSACTION;276 "BEGIN TRANSACTION;
274 IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }};277 IF (SELECT VALUE id FROM ONLY $exam) IS NONE {{ THROW 'exam_missing' }};
275 IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }};278 IF (SELECT VALUE draft FROM ONLY $exam) {{ THROW 'exam_draft' }};
276- LET $before = (SELECT VALUE id FROM ONLY $id);279+ LET $before = (SELECT VALUE mark FROM ONLY $id);
277 IF $before = NONE {{280 IF $before = NONE {{
278 LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1281 LET $kind = (UPSERT $kref SET {REF_COUNT_FIELD} = ({REF_COUNT_FIELD} ?? 0) + 1
279 WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id);282 WHERE {REF_RETIRED_FIELD} != true RETURN VALUE id);
@@ -282,7 +285,12 @@ impl ExamResult {
282 ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1;285 ({EXAM_RESULT_COUNT_FIELD} ?? 0) + 1;
283 UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =286 UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} =
284 ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1;287 ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1;
285- {high_mark}288+ }};
289+ LET $high = (IF $result.mark >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }})
290+ - (IF ($before ?? -1) >= {HIGH_MARK_MIN} {{ 1 }} ELSE {{ 0 }});
291+ IF $high != 0 {{
292+ UPDATE $student SET {HIGH_MARK_TOTAL_FIELD} =
293+ math::max([({HIGH_MARK_TOTAL_FIELD} ?? 0) + $high, 0])
286 }};294 }};
287 LET $after = (UPSERT $id CONTENT $result RETURN AFTER);295 LET $after = (UPSERT $id CONTENT $result RETURN AFTER);
288 RETURN $after[0];296 RETURN $after[0];
@@ -393,8 +401,11 @@ impl ExamResult {
393 /// actually deleted: `marks_given_total` to each row's *own* grader (two401 /// 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`402 /// 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 the403 /// once per removed row that cleared [`HIGH_MARK_MIN`], read off the
396- /// `BEFORE` image rather than re-derived — the mark that was credited is404+ /// `BEFORE` image rather than re-derived. That last one is why
397- /// the mark that was stored.405+ /// [`grade`](Self::grade) has to move the student's counter on a *regrade*
406+ /// too: this end reads the stored mark, so the other end must be decided by
407+ /// the stored mark as well, or a mark walked across the line between the
408+ /// two leaves a credit no delete can find to give back.
398 pub async fn remove(409 pub async fn remove(
399 exam: &ExamId,410 exam: &ExamId,
400 user: &UserId,411 user: &UserId,
@@ -769,6 +780,105 @@ mod tests {
769 assert_eq!(badge_counters(&db).await, (0, 0));780 assert_eq!(badge_counters(&db).await, (0, 0));
770 }781 }
771 782
783+ /// A regrade walks the *same* sitting across [`HIGH_MARK_MIN`], and the
784+ /// student's counter has to walk with it — the delete refunds off the mark
785+ /// it finds stored, so a credit decided by a mark that is no longer there
786+ /// is a credit nothing can give back. Left on the first-write branch alone,
787+ /// grade-high → regrade-low → delete kept a phantom high mark every round
788+ /// and looped it into a permanent badge.
789+ #[tokio::test]
790+ async fn a_regrade_across_the_line_moves_the_student_counter_with_it() {
791+ let db = init_mem().await.unwrap();
792+ let exam = ExamId::from_key("01TESTEXAMREGRADEAAAAAAAAA");
793+ an_exam(&db, &exam, "midterm").await;
794+ the_two_people(&db).await;
795+ let student = UserId::from_key(STUDENT);
796+
797+ // Up across the line: no row is added, but a high mark now exists.
798+ grade(&db, &exam, 1, 40, "midterm").await.unwrap();
799+ assert_eq!(badge_counters(&db).await, (1, 0), "40 is under the line");
800+ grade(&db, &exam, 1, 95, "midterm").await.unwrap();
801+ assert_eq!(badge_counters(&db).await, (1, 1), "the regrade crossed up");
802+ ExamResult::remove(&exam, &student, "midterm", &db)
803+ .await
804+ .unwrap()
805+ .expect("the mark was there");
806+ assert_eq!(badge_counters(&db).await, (0, 0));
807+
808+ // Down across it: the credit goes back the moment the mark does, so
809+ // the delete has nothing left to refund and the counter still lands
810+ // on zero rather than under it.
811+ grade(&db, &exam, 1, 95, "midterm").await.unwrap();
812+ assert_eq!(badge_counters(&db).await, (1, 1));
813+ grade(&db, &exam, 1, 40, "midterm").await.unwrap();
814+ assert_eq!(
815+ badge_counters(&db).await,
816+ (1, 0),
817+ "the regrade crossed down"
818+ );
819+ ExamResult::remove(&exam, &student, "midterm", &db)
820+ .await
821+ .unwrap()
822+ .expect("the mark was there");
823+ assert_eq!(badge_counters(&db).await, (0, 0));
824+
825+ // Both sides of a regrade above the line: nothing crosses, nothing moves.
826+ grade(&db, &exam, 1, 90, "midterm").await.unwrap();
827+ grade(&db, &exam, 1, 100, "midterm").await.unwrap();
828+ assert_eq!(badge_counters(&db).await, (1, 1), "90 → 100 stays one");
829+
830+ // The loop that minted the badge: three rounds of high → low → delete
831+ // must leave the counter exactly where it started.
832+ for _ in 0..3 {
833+ grade(&db, &exam, 1, 95, "midterm").await.unwrap();
834+ grade(&db, &exam, 1, 40, "midterm").await.unwrap();
835+ ExamResult::remove(&exam, &student, "midterm", &db)
836+ .await
837+ .unwrap()
838+ .expect("the mark was there");
839+ }
840+ assert_eq!(
841+ badge_counters(&db).await,
842+ (0, 0),
843+ "the loop kept a high mark with no high mark stored"
844+ );
845+ }
846+
847+ /// The other half of the same asymmetry: a refund read off a stored mark
848+ /// that was never credited eats a credit earned somewhere else. One exam
849+ /// holds a genuine high mark while a second is graded low, regraded high
850+ /// and deleted — the first exam's credit must still be standing.
851+ #[tokio::test]
852+ async fn one_exams_regrade_never_eats_another_exams_high_mark() {
853+ let db = init_mem().await.unwrap();
854+ let first = ExamId::from_key("01TESTEXAMSTEALONEAAAAAAAA");
855+ let second = ExamId::from_key("01TESTEXAMSTEALTWOAAAAAAAA");
856+ an_exam(&db, &first, "midterm").await;
857+ an_exam(&db, &second, "midterm").await;
858+ the_two_people(&db).await;
859+ let student = UserId::from_key(STUDENT);
860+
861+ grade(&db, &first, 1, 95, "midterm").await.unwrap();
862+ assert_eq!(
863+ badge_counters(&db).await,
864+ (1, 1),
865+ "earned on the first exam"
866+ );
867+
868+ grade(&db, &second, 1, 40, "midterm").await.unwrap();
869+ grade(&db, &second, 1, 95, "midterm").await.unwrap();
870+ assert_eq!(badge_counters(&db).await, (2, 2));
871+ ExamResult::remove(&second, &student, "midterm", &db)
872+ .await
873+ .unwrap()
874+ .expect("the mark was there");
875+ assert_eq!(
876+ badge_counters(&db).await,
877+ (1, 1),
878+ "the first exam's high mark was eaten"
879+ );
880+ }
881+
772 /// A refused mark leaves the badge counters where the other two are left.882 /// A refused mark leaves the badge counters where the other two are left.
773 #[tokio::test]883 #[tokio::test]
774 async fn a_refused_mark_credits_nobody() {884 async fn a_refused_mark_credits_nobody() {
src/lib.rsmodified+1 -1
@@ -44,7 +44,7 @@ use crate::state::AppState;
44 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),44 (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
45 (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),45 (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
46 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),46 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
47- (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter, and `stats.courses` stays the owner's true total either way. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),47+ (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (teacher+, optionally role-filtered), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total`), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. `stats.courses` and `stats.classes` stay the owner's true totals either way — they are motivational counters, and a magnitude names no course and no class. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
48 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),48 (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`)"),
49 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),49 (name = "messages", description = "One-to-one mail-style messages between any two users (parents included — messaging is the one place a parent writes), each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
50 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),50 (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A teacher demoted after publishing leaves inert slots: they drop out of the bookable list and booking one is refused"),
tests/regress_badges.rsmodified+14 -9
@@ -152,13 +152,16 @@ async fn ten_marks_put_the_graders_badge_on_a_profile() {
152 assert_eq!(stat(&theirs, "marks_given_total"), 0, "{theirs}");152 assert_eq!(stat(&theirs, "marks_given_total"), 0, "{theirs}");
153 }153 }
154 154
155-/// A mark is credited at the *first* grade of a sitting, so correcting one is155+/// The *grader's* mark is credited at the first grade of a sitting, so
156-/// free: the counter stays, and — the permanence rule at the stamp — the badge156+/// correcting one is free: the counter stays, and — the permanence rule at the
157-/// it already earned keeps the `earned_at` it was first given. The regrade is157+/// stamp — the badge it already earned keeps the `earned_at` it was first
158-/// deliberately pushed over the high-mark line, which a re-judging158+/// given. The *student's* high-mark counter is the one thing a regrade does
159-/// implementation would mint a `high_mark` for.159+/// move, and has to: it counts stored marks at or above the line, not first
160+/// gradings, and the delete that refunds it reads the stored mark. Pinned the
161+/// other way round, the pair drifted — the credit was decided by a mark the
162+/// refund could no longer find.
160 #[tokio::test]163 #[tokio::test]
161-async fn a_regrade_moves_neither_the_counter_nor_the_stamp() {164+async fn a_regrade_leaves_the_grader_alone_but_walks_the_high_mark_with_it() {
162 let m = marking(10).await;165 let m = marking(10).await;
163 for exam in &m.exams {166 for exam in &m.exams {
164 grade(&m.app, &m.teacher, exam, &m.student_id, 70).await;167 grade(&m.app, &m.teacher, exam, &m.student_id, 70).await;
@@ -186,13 +189,15 @@ async fn a_regrade_moves_neither_the_counter_nor_the_stamp() {
186 Some(earned),189 Some(earned),
187 "a re-sync moved a permanent stamp: {after}"190 "a re-sync moved a permanent stamp: {after}"
188 );191 );
192+ // The sitting now *stores* a 100, so the student holds one high mark —
193+ // exactly what deleting the result would refund, and nothing else.
189 let theirs = my_profile(&m.app, &m.student).await;194 let theirs = my_profile(&m.app, &m.student).await;
190 assert_eq!(195 assert_eq!(
191 stat(&theirs, "high_mark_total"),196 stat(&theirs, "high_mark_total"),
192- 0,197+ 1,
193- "a regrade re-judged the sitting and minted a high mark: {theirs}"198+ "the regrade crossed the line and the counter stayed behind: {theirs}"
194 );199 );
195- assert_eq!(badge_ids(&theirs), Vec::<&str>::new(), "{theirs}");200+ assert_eq!(badge_ids(&theirs), ["high_mark_1"], "{theirs}");
196 }201 }
197 202
198 /// The high-mark cut, from both sides of the line in one student's history:203 /// The high-mark cut, from both sides of the line in one student's history: