From ebbd8135ed8fb9bbd23a9d15479a9e591a4996a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 00:08:54 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=8F=A6=20link=20exam=20questions?= =?UTF-8?q?=20to=20their=20bank=20template,=20both=20ways?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - question_to_bank now writes source_bank back onto the exam question, mirroring what question_from_bank already did; repeat saves repoint the link at the newest template instead of leaving the client blind - link_source_bank is a field-scoped UPDATE, not a whole-row content save: the caller holds only BANK_LOCK and awaits a bank insert plus the blob-copy loop between reading the row and linking it, so a concurrent PATCH of the question was silently reverted - a failed back-link is logged and swallowed: the template and its copied blobs stand, and the next save re-links it - deleting a template clears source_bank on every question that referenced it; deleting an exam clears source_exam on its templates (both cascades were documented but never written) - tests: the concurrent-edit clobber, the two cascades, and repeat saves repointing the link --- src/domain/bank_question.rs | 16 +++- src/domain/exam.rs | 11 ++- src/domain/exam_question.rs | 28 ++++++ src/web/exams.rs | 24 ++++- tests/integration.rs | 183 ++++++++++++++++++++++++++++++++++++ 5 files changed, 253 insertions(+), 9 deletions(-) diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 42a2fd1..ad0fad8 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -217,11 +217,19 @@ impl BankQuestion { /// Delete the template and cascade-remove its bank images, so none points /// at a missing template. Bank rows have no answers. The image *blobs* are /// the web layer's to remove — it collects their names before calling this. + /// + /// Exam questions saved from this template keep living: only their + /// `source_bank` provenance link is cleared, field-scoped (never a whole-row + /// save — the question isn't ours and may be edited concurrently), so the + /// bank page can't read a link to a template that no longer exists. pub async fn delete(self, db: &Database) -> Result { - db.query("DELETE bank_question_image WHERE bank_question = $b;") - .bind(("b", self.id.record())) - .await? - .check()?; + db.query( + "DELETE bank_question_image WHERE bank_question = $b; + UPDATE exam_question SET source_bank = NONE WHERE source_bank = $b;", + ) + .bind(("b", self.id.record())) + .await? + .check()?; let deleted: Option = db.delete(self.id.record()).await?; deleted.ok_or(AppError::NotFound) } diff --git a/src/domain/exam.rs b/src/domain/exam.rs index 437f9b7..1815faa 100644 --- a/src/domain/exam.rs +++ b/src/domain/exam.rs @@ -474,6 +474,10 @@ impl Exam { /// so a failure can't leave an emptied-out exam shell behind. The image /// *blobs* (question and answer) are the web layer's to remove — it collects /// their names before calling this. + /// + /// Bank templates saved out of this exam survive it — they are a separate, + /// reusable library — so only their `source_exam` provenance link is cleared, + /// in the same transaction, never left pointing at a dead exam. pub async fn delete(self, db: &Database) -> Result { let mut result = db .query( @@ -484,15 +488,16 @@ impl Exam { DELETE answer_image WHERE exam = $ex; DELETE question_image WHERE exam = $ex; DELETE exam_question WHERE exam = $ex; + UPDATE bank_question SET source_exam = NONE WHERE source_exam = $ex; DELETE $ex RETURN BEFORE; COMMIT TRANSACTION;", ) .bind(("ex", self.id.record())) .await? .check()?; - // Statement slots count BEGIN and the child deletes: the exam's own - // DELETE is slot 7. - let deleted: Option = result.take::>(7)?.into_iter().next(); + // Statement slots count BEGIN, the child deletes and the bank + // provenance clear: the exam's own DELETE is slot 8. + let deleted: Option = result.take::>(8)?.into_iter().next(); deleted.ok_or(AppError::NotFound) } } diff --git a/src/domain/exam_question.rs b/src/domain/exam_question.rs index f3faa85..345f8da 100644 --- a/src/domain/exam_question.rs +++ b/src/domain/exam_question.rs @@ -334,6 +334,34 @@ impl ExamQuestion { updated.ok_or(AppError::NotFound) } + /// Point the question at the bank template it was just saved into + /// (`POST …/questions/{qid}/to-bank`), the mirror of the `source_bank` + /// [`Self::create_from_bank`] writes on the other direction. Overwrites any + /// earlier link: repeat saves mint a new template and the newest one wins. + /// + /// Field-scoped write, unlike [`Self::update`]: the caller holds only + /// `BANK_LOCK` (which guards the bank, not `exam_question`) and awaits a + /// bank insert plus the whole blob-copy loop between reading this row and + /// linking it, so a concurrent `PATCH` of the question is entirely possible + /// in that window — a whole-row save would silently revert it. + pub async fn link_source_bank( + self, + source: BankQuestionId, + db: &Database, + ) -> Result { + let mut result = db + .query("UPDATE $id SET source_bank = $bank RETURN AFTER") + .bind(("id", self.id.record())) + .bind(("bank", source.record())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::NotFound) + } + /// Delete the question and cascade-remove its answers and image rows, so /// neither can point at a missing question. The image *blobs* are the web /// layer's to remove — it collects their names before calling this. diff --git a/src/web/exams.rs b/src/web/exams.rs index 2307839..037cfe7 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -1863,8 +1863,10 @@ async fn question_from_bank( /// template. Requires teacher+ and management rights over the exam's course. /// The caller becomes the template's owner; the question's subject rides along /// as origin metadata. A full copy — text, points, spec, illustration, and -/// option pictures — lands under a new bank id; the exam question is untouched. -/// The origin exam is recorded on the template as `source_exam`. +/// option pictures — lands under a new bank id. Provenance rides both ways: the +/// origin exam is recorded on the template as `source_exam`, and the exam +/// question's `source_bank` is pointed at the new template (a repeat save is +/// allowed and repoints it at the newest one). #[utoipa::path( post, path = "/{id}/questions/{qid}/to-bank", @@ -1953,6 +1955,24 @@ async fn question_to_bank( } } } + // Provenance back-link, so a client can tell this question was already + // banked: the question points at the template it was saved into, and a + // repeat save repoints it at the newest one (never blocked). Written only + // after the all-or-nothing copy above, so a rolled-back template can never + // leave a dangling link. A failure here is logged and swallowed rather than + // rolling the template back: the save is the user's actual work and a + // template silently vanishing over a metadata write is worse than a + // template with no back-link (the next save re-links it). + let question_key = question.get_id().key().to_string(); + if let Err(err) = question + .link_source_bank(template.get_id().clone(), &st.db) + .await + { + tracing::warn!( + "saved question {question_key} to the bank but could not link it back: {err}" + ); + } + let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; Ok(( StatusCode::CREATED, diff --git a/tests/integration.rs b/tests/integration.rs index 985ed80..7a2e5a7 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -17476,3 +17476,186 @@ async fn bank_provenance_both_directions() { let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; assert!(res.body["source_exam"].is_null()); } + +/// Save-to-bank also links the *question* back at the template it produced, so +/// a client can tell it was already banked. A repeat save is allowed and +/// repoints the link at the newer template. +#[tokio::test] +async fn to_bank_links_the_question_at_the_new_template() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bback_t", "teacher").await; + let course = create_course(&app, &teacher, "bback_c").await; + let subject = create_subject(&app, &teacher, &course, "bback_s").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "plain", "kind": "text", "points": 5 }), + ) + .await; + + // Fresh question: no link yet. + let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { + common::items(body) + .iter() + .find(|q| q["id"] == qid) + .expect("question in list")["source_bank"] + .clone() + }; + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert!(source_bank_of(&res.body).is_null()); + + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let first = id_of(&res.body); + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert_eq!(source_bank_of(&res.body), json!(first)); + + // Second save: still 201, a distinct template, and the link follows it. + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let second = id_of(&res.body); + assert_ne!(first, second); + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert_eq!(source_bank_of(&res.body), json!(second)); +} + +/// The back-link is a field-scoped write. `question_to_bank` reads the question, +/// then awaits a bank insert and the whole blob-copy loop before linking, holding +/// no lock over `exam_question` — so a `PATCH` can land in that window. A +/// whole-row save from the stale struct would silently revert it. Driven at the +/// domain level: HTTP offers no way to interleave inside the handler. +#[tokio::test] +async fn linking_the_bank_source_does_not_clobber_a_concurrent_edit() { + use hezarfen_backend::domain::bank_question::BankQuestionId; + use hezarfen_backend::domain::exam_question::{ExamQuestion, ExamQuestionId}; + + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bclob_t", "teacher").await; + let course = create_course(&app, &teacher, "bclob_c").await; + let subject = create_subject(&app, &teacher, &course, "bclob_s").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "original", "kind": "text", "points": 5 }), + ) + .await; + let res = send( + &app, + "POST", + "/bank-questions", + Some(&teacher), + Some(json!({ "subject_id": subject, "text": "q", "kind": "text", "points": 5 })), + ) + .await; + let bid = id_of(&res.body); + + // The handler's read, then someone else's edit lands mid-window. + let stale = ExamQuestion::read(&ExamQuestionId::from_key(&qid), &db) + .await + .unwrap() + .expect("question exists"); + let res = send( + &app, + "PATCH", + &format!("/exams/{exam}/questions/{qid}"), + Some(&teacher), + Some(json!({ "text": "edited by someone else", "points": 9 })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + stale + .link_source_bank(BankQuestionId::from_key(&bid), &db) + .await + .expect("link written"); + + // The edit survives and the link is set. + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + let question = common::items(&res.body) + .iter() + .find(|q| q["id"] == qid) + .expect("question in list") + .clone(); + assert_eq!(question["text"], "edited by someone else"); + assert_eq!(question["points"], 9); + assert_eq!(question["source_bank"], bid); +} + +/// Deleting a bank template clears the provenance link on every exam question +/// saved from it, instead of leaving `source_bank` pointing at a dead row. +#[tokio::test] +async fn deleting_a_template_clears_the_questions_source_bank() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "bdang_t", "teacher").await; + let course = create_course(&app, &teacher, "bdang_c").await; + let subject = create_subject(&app, &teacher, &course, "bdang_s").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "plain", "kind": "text", "points": 5 }), + ) + .await; + + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + + let source_bank_of = |body: &serde_json::Value| -> serde_json::Value { + common::items(body) + .iter() + .find(|q| q["id"] == qid) + .expect("question in list")["source_bank"] + .clone() + }; + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert_eq!(source_bank_of(&res.body), json!(bid)); + + let res = send(&app, "DELETE", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + // The question survives the template with no dangling link. + let res = send(&app, "GET", &format!("/exams/{exam}/questions"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!(source_bank_of(&res.body).is_null(), "{}", res.body); +} + +/// The mirror: deleting the origin exam clears `source_exam` on the templates +/// saved out of it — the template is a reusable library row and outlives the +/// exam, but the bank page must not read a link to a dead exam. +#[tokio::test] +async fn deleting_an_exam_clears_the_templates_source_exam() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "edang_t", "teacher").await; + let course = create_course(&app, &teacher, "edang_c").await; + let subject = create_subject(&app, &teacher, &course, "edang_s").await; + let exam = create_exam(&app, &teacher, &course, "midterm", "final").await; + let qid = create_question( + &app, + &teacher, + &exam, + &subject, + json!({ "text": "plain", "kind": "text", "points": 5 }), + ) + .await; + + let res = send(&app, "POST", &format!("/exams/{exam}/questions/{qid}/to-bank"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let bid = id_of(&res.body); + assert_eq!(res.body["source_exam"], exam); + + let res = send(&app, "DELETE", &format!("/exams/{exam}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); + + let res = send(&app, "GET", &format!("/bank-questions/{bid}"), Some(&teacher), None).await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + assert!(res.body["source_exam"].is_null(), "{}", res.body); +}