🗃️ backfill the rows the choice-identity retype left unwritable
Browse files at this commitb005e15968e72b6ad38ed5d8edcbe99fe899c613Parent: b4a5a00- fix
- 🗃️ backfill the rows the choice-identity retype left unwritable
1 changed file +190 -0
- src/database.rs +190 -0
src/database.rsmodified+190 -0
| @@ -61,6 +61,25 @@ pub const CHAT_MESSAGE_TABLE: &str = "chatbot_message"; | |||
| 61 | pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot"; | 61 | pub const APPOINTMENT_SLOT_TABLE: &str = "appointment_slot"; |
| 62 | pub const APPOINTMENT_TABLE: &str = "appointment"; | 62 | pub const APPOINTMENT_TABLE: &str = "appointment"; |
| 63 | 63 | ||
| 64 | +/// Repairs that must run *before* the DDL batch, because the DDL is what makes | ||
| 65 | +/// them impossible. | ||
| 66 | +/// | ||
| 67 | +/// `MIGRATION` retires `exam_question.source_bank` with `REMOVE FIELD`, and | ||
| 68 | +/// once the column is gone SCHEMAFULL rejects every write to a row that still | ||
| 69 | +/// stores it ("Found field 'source_bank', but no such field exists") — an | ||
| 70 | +/// UNSET included. So the value has to go while its definition is still | ||
| 71 | +/// standing. Runs as its own query for the usual reason (see `MIGRATION`). | ||
| 72 | +/// | ||
| 73 | +/// The table-exists guard is load-bearing: on a fresh database `MIGRATION` has | ||
| 74 | +/// not run yet, and an UPDATE against an undefined table is an error, not an | ||
| 75 | +/// empty result. On a database that has the table but never had the column the | ||
| 76 | +/// `WHERE` simply matches nothing. | ||
| 77 | +const PRE_REPAIR: &str = " | ||
| 78 | + IF 'exam_question' IN object::keys((INFO FOR DB).tables) { | ||
| 79 | + UPDATE exam_question UNSET source_bank WHERE source_bank != NONE | ||
| 80 | + }; | ||
| 81 | +"; | ||
| 82 | + | ||
| 64 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. | 83 | /// SCHEMAFULL schema: every column is typed, references use `record<..>`. |
| 65 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the | 84 | /// Idempotent — safe to run on every boot: `IF NOT EXISTS` guards the |
| 66 | /// definitions and `REMOVE ... IF EXISTS` retires schema (like the | 85 | /// definitions and `REMOVE ... IF EXISTS` retires schema (like the |
| @@ -562,6 +581,56 @@ const BACKFILL: &str = " | |||
| 562 | -- `user.role = NONE`, which is also != 'student' — those rows go too. | 581 | -- `user.role = NONE`, which is also != 'student' — those rows go too. |
| 563 | DELETE enrollment WHERE user.role != 'student'; | 582 | DELETE enrollment WHERE user.role != 'student'; |
| 564 | 583 | ||
| 584 | + -- Choices gained stable ids (2026-07-24): `choices` held bare strings and | ||
| 585 | + -- `correct`/`selected`/`slot` held the option's *position*. The DDL above | ||
| 586 | + -- retypes those columns, which leaves every old-shaped row readable but | ||
| 587 | + -- unwritable ('Expected `none | array<object>` but found `[..]`'), so this | ||
| 588 | + -- conversion is repair, not cosmetics. | ||
| 589 | + -- | ||
| 590 | + -- Ids are minted in array order, so the id at position i *is* the id for | ||
| 591 | + -- old index i — that identity is what keeps a stored answer, and an option | ||
| 592 | + -- picture, pointing at the option the student actually saw. Hence the | ||
| 593 | + -- dependent rows are remapped inside the loop that mints `$new`, against | ||
| 594 | + -- that same array: once the ids are stored the positions are still | ||
| 595 | + -- recoverable, but nothing guarantees a later pass would look them up the | ||
| 596 | + -- same way. `WHERE choices[0] != NONE AND type::is_string(choices[0])` | ||
| 597 | + -- matches only unconverted rows, so a second boot re-mints nothing; an | ||
| 598 | + -- empty or absent `choices` needs no conversion at all. A question-level | ||
| 599 | + -- picture (`slot = NONE`) is not an index and is left alone. | ||
| 600 | + -- | ||
| 601 | + -- Runs *before* every other backfill that writes these rows (the `seq` | ||
| 602 | + -- stamps below): a write coerces the whole record, so touching a row for | ||
| 603 | + -- any reason fails while its choices are still positional. For the same | ||
| 604 | + -- reason the answer's remap stamps `seq` itself — the two legacy gaps sit | ||
| 605 | + -- on the same row, and a write that fixes only one of them is rejected for | ||
| 606 | + -- the other. `seq ?? 1` leaves an already-numbered sitting alone (DEFAULT | ||
| 607 | + -- fills a CREATE, not an UPDATE of a row that predates the column). | ||
| 608 | + FOR $q IN ((SELECT id, choices, correct FROM exam_question | ||
| 609 | + WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { | ||
| 610 | + LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); | ||
| 611 | + UPDATE $q.id SET choices = $new, | ||
| 612 | + correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; | ||
| 613 | + FOR $img IN ((SELECT id, slot FROM question_image | ||
| 614 | + WHERE question = $q.id AND type::is_int(slot)) ?? []) { | ||
| 615 | + UPDATE $img.id SET slot = $new[$img.slot].id; | ||
| 616 | + }; | ||
| 617 | + FOR $ans IN ((SELECT id, selected FROM exam_answer | ||
| 618 | + WHERE question = $q.id AND type::is_int(selected)) ?? []) { | ||
| 619 | + UPDATE $ans.id SET selected = $new[$ans.selected].id, seq = seq ?? 1; | ||
| 620 | + }; | ||
| 621 | + }; | ||
| 622 | + | ||
| 623 | + FOR $q IN ((SELECT id, choices, correct FROM bank_question | ||
| 624 | + WHERE choices[0] != NONE AND type::is_string(choices[0])) ?? []) { | ||
| 625 | + LET $new = $q.choices.map(|$c| { id: rand::ulid(), text: $c }); | ||
| 626 | + UPDATE $q.id SET choices = $new, | ||
| 627 | + correct = IF $q.correct = NONE { NONE } ELSE { $new[$q.correct].id }; | ||
| 628 | + FOR $img IN ((SELECT id, slot FROM bank_question_image | ||
| 629 | + WHERE bank_question = $q.id AND type::is_int(slot)) ?? []) { | ||
| 630 | + UPDATE $img.id SET slot = $new[$img.slot].id; | ||
| 631 | + }; | ||
| 632 | + }; | ||
| 633 | + | ||
| 565 | -- Per-attempt history (2026-07-24): answers, drawings, and marks written | 634 | -- Per-attempt history (2026-07-24): answers, drawings, and marks written |
| 566 | -- before retakes stopped wiping belong to the student's first sitting. | 635 | -- before retakes stopped wiping belong to the student's first sitting. |
| 567 | -- They already use the bare (seq==1) record key, so only the denormalized | 636 | -- They already use the bare (seq==1) record key, so only the denormalized |
| @@ -624,6 +693,7 @@ pub async fn init_mem() -> Result<Database, AppError> { | |||
| 624 | /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, | 693 | /// Apply the schema + backfills. Idempotent — `init` runs it on every boot, |
| 625 | /// and tests re-run it on a live handle to simulate a second boot. | 694 | /// and tests re-run it on a live handle to simulate a second boot. |
| 626 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | 695 | pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { |
| 696 | + db.query(PRE_REPAIR).await?.check()?; | ||
| 627 | db.query(MIGRATION).await?.check()?; | 697 | db.query(MIGRATION).await?.check()?; |
| 628 | db.query(BACKFILL).await?.check()?; | 698 | db.query(BACKFILL).await?.check()?; |
| 629 | Ok(()) | 699 | Ok(()) |
| @@ -665,4 +735,124 @@ mod tests { | |||
| 665 | assert_eq!(interrupted["error_code"], "interrupted"); | 735 | assert_eq!(interrupted["error_code"], "interrupted"); |
| 666 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); | 736 | assert!(interrupted["completed_at"].as_i64().unwrap() > 0); |
| 667 | } | 737 | } |
| 738 | + | ||
| 739 | + /// A row written before choices had ids survives the retyped columns: it is | ||
| 740 | + /// converted, it is writable again, and its stored *position* still names | ||
| 741 | + /// the same option — a wrong remap here silently regrades exams. | ||
| 742 | + #[tokio::test] | ||
| 743 | + async fn boot_converts_positional_choices_and_keeps_the_same_option() { | ||
| 744 | + let db = super::init_mem().await.unwrap(); | ||
| 745 | + // Roll the columns back to their pre-2026-07-24 shapes and write the | ||
| 746 | + // kind of row an older binary left behind, `source_bank` included. | ||
| 747 | + db.query( | ||
| 748 | + "REMOVE FIELD IF EXISTS choices[*].id ON TABLE exam_question; | ||
| 749 | + REMOVE FIELD IF EXISTS choices[*].text ON TABLE exam_question; | ||
| 750 | + REMOVE FIELD IF EXISTS choices[*].id ON TABLE bank_question; | ||
| 751 | + REMOVE FIELD IF EXISTS choices[*].text ON TABLE bank_question; | ||
| 752 | + DEFINE FIELD OVERWRITE choices ON exam_question TYPE option<array<string>>; | ||
| 753 | + DEFINE FIELD OVERWRITE correct ON exam_question TYPE option<int>; | ||
| 754 | + DEFINE FIELD OVERWRITE source_bank ON exam_question TYPE option<string>; | ||
| 755 | + DEFINE FIELD OVERWRITE slot ON question_image TYPE option<int>; | ||
| 756 | + DEFINE FIELD OVERWRITE selected ON exam_answer TYPE option<int>; | ||
| 757 | + DEFINE FIELD OVERWRITE choices ON bank_question TYPE option<array<string>>; | ||
| 758 | + DEFINE FIELD OVERWRITE correct ON bank_question TYPE option<int>; | ||
| 759 | + DEFINE FIELD OVERWRITE slot ON bank_question_image TYPE option<int>;", | ||
| 760 | + ) | ||
| 761 | + .await | ||
| 762 | + .unwrap() | ||
| 763 | + .check() | ||
| 764 | + .unwrap(); | ||
| 765 | + db.query( | ||
| 766 | + "CREATE user:u SET username = 'u', password_hash = 'x'; | ||
| 767 | + CREATE exam_question:q SET exam = exam:e, text = 'q', kind = 'multiple', | ||
| 768 | + points = 5, subject = subject:s, choices = ['3', '4', '5'], correct = 1, | ||
| 769 | + source_bank = 'bank_question:b'; | ||
| 770 | + CREATE question_image:i SET exam = exam:e, question = exam_question:q, slot = 2, | ||
| 771 | + file = 'f', content_type = 'image/png', size = 1; | ||
| 772 | + CREATE question_image:whole SET exam = exam:e, question = exam_question:q, | ||
| 773 | + file = 'w', content_type = 'image/png', size = 1; | ||
| 774 | + CREATE exam_answer:a SET exam = exam:e, question = exam_question:q, user = user:u, | ||
| 775 | + selected = 2, updated_at = 1; | ||
| 776 | + CREATE bank_question:b SET owner = user:u, text = 'b', kind = 'multiple', | ||
| 777 | + points = 3, choices = ['a', 'b'], correct = 0, created_at = 1; | ||
| 778 | + CREATE bank_question_image:bi SET bank_question = bank_question:b, slot = 1, | ||
| 779 | + file = 'bf', content_type = 'image/png', size = 1;", | ||
| 780 | + ) | ||
| 781 | + .await | ||
| 782 | + .unwrap() | ||
| 783 | + .check() | ||
| 784 | + .unwrap(); | ||
| 785 | + | ||
| 786 | + super::migrate(&db).await.unwrap(); | ||
| 787 | + | ||
| 788 | + let mut res = db | ||
| 789 | + .query( | ||
| 790 | + "SELECT choices, correct FROM ONLY exam_question:q; | ||
| 791 | + SELECT VALUE slot FROM ONLY question_image:i; | ||
| 792 | + SELECT VALUE slot FROM ONLY question_image:whole; | ||
| 793 | + SELECT VALUE selected FROM ONLY exam_answer:a; | ||
| 794 | + SELECT choices, correct FROM ONLY bank_question:b; | ||
| 795 | + SELECT VALUE slot FROM ONLY bank_question_image:bi;", | ||
| 796 | + ) | ||
| 797 | + .await | ||
| 798 | + .unwrap(); | ||
| 799 | + let q: Option<serde_json::Value> = res.take(0).unwrap(); | ||
| 800 | + let q = q.unwrap(); | ||
| 801 | + let img_slot: Option<String> = res.take(1).unwrap(); | ||
| 802 | + let whole_slot: Option<String> = res.take(2).unwrap(); | ||
| 803 | + let selected: Option<String> = res.take(3).unwrap(); | ||
| 804 | + let bank: Option<serde_json::Value> = res.take(4).unwrap(); | ||
| 805 | + let bank = bank.unwrap(); | ||
| 806 | + let bank_slot: Option<String> = res.take(5).unwrap(); | ||
| 807 | + | ||
| 808 | + let ids: Vec<&str> = q["choices"] | ||
| 809 | + .as_array() | ||
| 810 | + .unwrap() | ||
| 811 | + .iter() | ||
| 812 | + .map(|c| c["id"].as_str().unwrap()) | ||
| 813 | + .collect(); | ||
| 814 | + assert_eq!( | ||
| 815 | + q["choices"][0]["text"], "3", | ||
| 816 | + "option order (and so the meaning of every stored index) is preserved" | ||
| 817 | + ); | ||
| 818 | + assert_eq!(q["correct"], ids[1], "correct was index 1"); | ||
| 819 | + assert_eq!( | ||
| 820 | + img_slot.as_deref(), | ||
| 821 | + Some(ids[2]), | ||
| 822 | + "option picture was slot 2" | ||
| 823 | + ); | ||
| 824 | + assert_eq!(selected.as_deref(), Some(ids[2]), "the answer was index 2"); | ||
| 825 | + assert_eq!(whole_slot, None, "a question-level picture has no index"); | ||
| 826 | + let bank_ids: Vec<&str> = bank["choices"] | ||
| 827 | + .as_array() | ||
| 828 | + .unwrap() | ||
| 829 | + .iter() | ||
| 830 | + .map(|c| c["id"].as_str().unwrap()) | ||
| 831 | + .collect(); | ||
| 832 | + assert_eq!(bank["correct"], bank_ids[0]); | ||
| 833 | + assert_eq!(bank_slot.as_deref(), Some(bank_ids[1])); | ||
| 834 | + | ||
| 835 | + // Writable again — every one of these failed coercion before the | ||
| 836 | + // backfill existed, and `source_bank` outlived its own column. | ||
| 837 | + db.query( | ||
| 838 | + "UPDATE exam_question:q SET points = 7; | ||
| 839 | + UPDATE question_image:i SET size = 2; | ||
| 840 | + UPDATE exam_answer:a SET updated_at = 2; | ||
| 841 | + UPDATE bank_question:b SET points = 4; | ||
| 842 | + UPDATE bank_question_image:bi SET size = 2;", | ||
| 843 | + ) | ||
| 844 | + .await | ||
| 845 | + .unwrap() | ||
| 846 | + .check() | ||
| 847 | + .unwrap(); | ||
| 848 | + | ||
| 849 | + // A second boot re-mints nothing. | ||
| 850 | + super::migrate(&db).await.unwrap(); | ||
| 851 | + let mut res = db | ||
| 852 | + .query("SELECT VALUE choices.map(|$c| $c.id) FROM ONLY exam_question:q") | ||
| 853 | + .await | ||
| 854 | + .unwrap(); | ||
| 855 | + let again: Vec<String> = res.take(0).unwrap(); | ||
| 856 | + assert_eq!(again, ids, "conversion is idempotent"); | ||
| 857 | + } | ||
| 668 | } | 858 | } |