forge
Explore
Log in

Don't you dare go Hollow

🪝 make the course claim a write the store can see

Browse files at this commit

6200ad073fce87ffa670119fc3f9b061a7ea1b6bAhmet Kaan GümüşParent: 36c718a
  • fix
    • 🪝 make the course claim a write the store can see
Show full message
fix: 🪝 make the course claim a write the store can see

Attaching a course to a class claimed the course row by re-stating its
counter — SET count = count — on the reasoning that the row must be
touched, not changed. SurrealDB drops an update that leaves the
document unchanged, so that statement never entered the write set and
never collided with anything. A concurrent course delete and the attach
both committed, leaving a class linked to a course that was gone.

The claim now bumps the counter, checks the row is still there, and
puts the value back as it found it — absent stays absent, so the boot
backfill still matches. Both statements are in the one transaction, so
nothing can observe the bump or strand it.

A sweep for the same shape found no other site: every other claim in
the crate moves a real value.
src/domain/class_course.rsmodified+117 -1
@@ -239,7 +239,8 @@ impl ClassCourse {
239 mod tests {239 mod tests {
240 use super::*;240 use super::*;
241 use crate::domain::class_member::ClassMember;241 use crate::domain::class_member::ClassMember;
242- use crate::domain::class_member::tests::{a_class, a_course, counter, rows, source_of};242+ use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of};
243+ use crate::domain::course::Course;
243 use crate::domain::enrollment::Enrollment;244 use crate::domain::enrollment::Enrollment;
244 245
245 /// Attaching seeds the course from the roster the class already holds.246 /// Attaching seeds the course from the roster the class already holds.
@@ -461,4 +462,119 @@ mod tests {
461 assert_eq!(source_of(&algebra, &student, &db).await, None);462 assert_eq!(source_of(&algebra, &student, &db).await, None);
462 assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);463 assert_eq!(counter("enrollment_count", algebra.record(), &db).await, 0);
463 }464 }
465+
466+ /// The restore half of the pivot claim: it bumps the course's counter to
467+ /// prove the row is there and must put it back *exactly* as it found it —
468+ /// absent, which the boot backfill keys on (`WHERE enrollment_count =
469+ /// NONE`). An empty roster is the case that has no seat write to hide a
470+ /// leftover bump behind.
471+ #[tokio::test]
472+ async fn the_pivot_claim_gives_the_courses_counter_back_untouched() {
473+ let db = crate::database::init_mem().await.unwrap();
474+ let class = a_class("9-A", &db).await;
475+ let algebra = a_course("algebra", None, &db).await;
476+ let absent = "SELECT VALUE id FROM course WHERE enrollment_count = NONE";
477+ assert_eq!(
478+ rows(absent, &db).await,
479+ 1,
480+ "a fresh course carries no count"
481+ );
482+
483+ ClassCourse::attach(&class, &algebra, &UserId::from_key("manager"), &db)
484+ .await
485+ .unwrap();
486+ assert_eq!(
487+ rows(absent, &db).await,
488+ 1,
489+ "the claim's bump must be restored to absent, not to 0"
490+ );
491+ }
492+
493+ /// The `Menu::delete` defect on the class layer: a `class_course` row must
494+ /// not outlive the course it names. The attach's proof that the course is
495+ /// still there is a *write* on the course row
496+ /// ([`crate::domain::class_pump::Axis::pivot_claim`]), landing it on the
497+ /// very key `Course::delete`'s guard writes — but only because that write
498+ /// now *moves* the counter. The `count = count` this shipped with left the
499+ /// document unchanged, which SurrealDB 3.2.3 elides: it entered no write
500+ /// set, collided with nothing, and both callers were told OK while the link
501+ /// stayed pointing at a deleted course.
502+ ///
503+ /// The roster is empty deliberately — that is the only shape where nothing
504+ /// else in the transaction touches the course row, so the claim is the
505+ /// whole guard. One child per round, for the reason the menu twin
506+ /// documents: a second writer makes the delete lose and re-send, and the
507+ /// re-sent sweep clears the evidence.
508+ ///
509+ /// The window is opened by the schema, not by a lucky interleaving: a
510+ /// `DEFINE EVENT` on `course` fires inside the delete's own transaction the
511+ /// instant the row goes, so the `SLEEP` lands between the delete and its
512+ /// `DELETE class_course WHERE course = $course` sweep every time.
513+ ///
514+ /// Real server, and `#[ignore]`d for it: the subject *is* the store's
515+ /// conflict detection, which `init_mem`'s embedded engine does not have —
516+ /// it commits both and answers `Ok` to each, so this passes there on broken
517+ /// code.
518+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
519+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
520+ async fn a_class_course_link_never_outlives_the_course() {
521+ let (db, _serialized) = crate::database::init_test_server("class_course_race").await;
522+ db.query(
523+ "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \
524+ THEN { SLEEP 1s; };",
525+ )
526+ .await
527+ .unwrap()
528+ .check()
529+ .unwrap();
530+
531+ let manager = UserId::from_key("manager");
532+ let (mut orphans, mut swept, mut miscounted) = (0, 0, 0);
533+ for round in 0..4 {
534+ let class = a_class(&format!("9-{round}"), &db).await;
535+ let algebra = a_course(&format!("algebra{round}"), None, &db).await;
536+ let course = Course::read(&algebra, &db).await.unwrap().unwrap();
537+
538+ let drop_it = {
539+ let db = db.clone();
540+ tokio::spawn(async move { course.delete(&db).await })
541+ };
542+ // The attach starts inside the held window — the course row is gone
543+ // but uncommitted, which is exactly what a course read believes.
544+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
545+ let child = {
546+ let (db, class, algebra, manager) =
547+ (db.clone(), class.clone(), algebra.clone(), manager.clone());
548+ tokio::spawn(
549+ async move { ClassCourse::attach(&class, &algebra, &manager, &db).await },
550+ )
551+ };
552+ let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
553+ // A 404 for the attach, or a refusal for the delete, is a correct
554+ // answer — the only defect is stored state.
555+ assert!(
556+ !matches!(child, Err(AppError::Db(_))),
557+ "round {round}: a raced attach must be answered, not 500: {child:?}"
558+ );
559+
560+ // Stored state is the whole verdict; a return value is not evidence.
561+ if !exists(algebra.record(), &db).await {
562+ swept += 1;
563+ let link = ClassCourseId::composite(&class, &algebra);
564+ if exists(link.record(), &db).await {
565+ orphans += 1;
566+ }
567+ miscounted += counter("class_course_count", class.record(), &db).await;
568+ } else if matches!(drop_it, Ok(true)) {
569+ panic!("round {round}: the delete reported success but the course is still there");
570+ }
571+ }
572+ eprintln!("Course::delete raced by an attach: {swept}/4 rounds deleted the course");
573+ assert!(
574+ swept > 0,
575+ "no round ever deleted the course, so the window was never reached"
576+ );
577+ assert_eq!(orphans, 0, "a class_course link outlived its course");
578+ assert_eq!(miscounted, 0, "a class counts a course that is gone");
579+ }
464 }580 }
src/domain/class_pump.rsmodified+28 -11
@@ -220,9 +220,17 @@ impl Axis {
220 /// nothing once the row is gone, and it puts this transaction on the very220 /// nothing once the row is gone, and it puts this transaction on the very
221 /// record the course's delete guard writes.221 /// record the course's delete guard writes.
222 ///222 ///
223- /// The counter is re-stated verbatim rather than incremented: the row must223+ /// The counter is *moved* — bumped, gated, then restored to the value this
224- /// be touched, not changed, and `count = count` leaves an absent counter224+ /// transaction found — because re-stating it verbatim claims nothing: an
225- /// absent, so the boot backfill still sees the `NONE` it seeds off.225+ /// `UPDATE` that leaves the document unchanged is elided by SurrealDB 3.2.3
226+ /// and never enters the write set, so `count = count` sat on no key at all
227+ /// and a concurrent `DELETE /courses/{id}` committed beside it with both
228+ /// callers told OK (measured on 3.2.3, counter present and absent alike).
229+ /// Same shape as [`crate::domain::exam_answer::ExamAnswer::save`]: the
230+ /// restore is by captured value, `NONE` included, so the row is
231+ /// byte-identical afterwards and the boot backfill still sees the `NONE` it
232+ /// seeds off. Both statements are inside the transaction, so an abort
233+ /// between them cannot leave a course counting a seat nobody took.
226 ///234 ///
227 /// The member axis claims nothing: its pivot is a user, whose row is no235 /// The member axis claims nothing: its pivot is a user, whose row is no
228 /// class write's to touch, and a membership left pointing at a deleted user236 /// class write's to touch, and a membership left pointing at a deleted user
@@ -231,14 +239,23 @@ impl Axis {
231 fn pivot_claim(&self) -> Vec<String> {239 fn pivot_claim(&self) -> Vec<String> {
232 match self {240 match self {
233 Axis::Member => Vec::new(),241 Axis::Member => Vec::new(),
234- Axis::Course => claim(242+ Axis::Course => {
235- "alive",243+ let mut claimed = vec![format!(
236- &format!(244+ "LET $was_alive = (SELECT VALUE {ENROLLMENT_COUNT_FIELD} FROM ONLY $pivot)"
237- "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \245+ )];
238- {ENROLLMENT_COUNT_FIELD} RETURN VALUE id"246+ claimed.extend(claim(
239- ),247+ "alive",
240- GONE_MARK,248+ &format!(
241- ),249+ "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = \
250+ ({ENROLLMENT_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id"
251+ ),
252+ GONE_MARK,
253+ ));
254+ claimed.push(format!(
255+ "UPDATE $pivot SET {ENROLLMENT_COUNT_FIELD} = $was_alive"
256+ ));
257+ claimed
258+ }
242 }259 }
243 }260 }
244 261