Let a one-time migration block be corrected after it is marked
Browse files at this commitcd6a00a9cd23e9e9b122ef257c7f09350244ab2cParent: e6f927b- fix
- let a one-time migration block be corrected after it is marked
2 changed files +336 -13
- src/database.rs +282 -5
- src/migration_sql.rs +54 -8
src/database.rsmodified+282 -5
| @@ -9,7 +9,7 @@ use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STA | |||
| 9 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
| 10 | use crate::domain::user::{Password, User, Username}; | 10 | use crate::domain::user::{Password, User, Username}; |
| 11 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| 12 | -use crate::migration_sql::MIGRATION_BATCHES; | 12 | +use crate::migration_sql::{BACKFILL, MIGRATION_BATCHES}; |
| 13 | 13 | ||
| 14 | /// The shared database handle. | 14 | /// The shared database handle. |
| 15 | /// | 15 | /// |
| @@ -328,14 +328,150 @@ pub async fn migrate(db: &Surreal<Any>) -> Result<(), AppError> { | |||
| 328 | 328 | ||
| 329 | /// Parameters the batches are executed with. Bound, not baked into the SQL | 329 | /// Parameters the batches are executed with. Bound, not baked into the SQL |
| 330 | /// string: a `const` cannot be interpolated into another `const`, and a | 330 | /// string: a `const` cannot be interpolated into another `const`, and a |
| 331 | -/// hand-copied 300000 would drift silently. | 331 | +/// hand-copied 300000 would drift silently. The one-time blocks' fingerprints |
| 332 | -fn migration_binds() -> [(&'static str, i64); 1] { | 332 | +/// ride along — see [`marked_blocks`]. Bound to all three batches, which is |
| 333 | - [("stale_ms", CHATBOT_PENDING_STALE_SECS * 1_000)] | 333 | +/// free: an unused parameter is not an error. |
| 334 | +fn migration_binds() -> Vec<(String, i64)> { | ||
| 335 | + let mut binds = vec![("stale_ms".to_string(), CHATBOT_PENDING_STALE_SECS * 1_000)]; | ||
| 336 | + binds.extend(marked_blocks()); | ||
| 337 | + binds | ||
| 338 | +} | ||
| 339 | + | ||
| 340 | +/// The line every one-time block in [`BACKFILL`] opens with. The name straight | ||
| 341 | +/// after it is the block's `migration_mark` key, and `fp_<name>` is the | ||
| 342 | +/// parameter its fingerprint is bound to — so a block written in this idiom is | ||
| 343 | +/// found, hashed and bound with nothing to keep by hand. A block written any | ||
| 344 | +/// other way silently gets no fingerprint, which is what | ||
| 345 | +/// `every_one_time_block_is_fingerprinted` exists to catch. | ||
| 346 | +const MARK_GATE: &str = "IF array::len((SELECT VALUE id FROM migration_mark:"; | ||
| 347 | + | ||
| 348 | +/// Every one-time block in [`BACKFILL`], as (`fp_<name>`, hash of its own SQL). | ||
| 349 | +/// | ||
| 350 | +/// A `migration_mark` used to say only *that* a block had run, which made a | ||
| 351 | +/// marked block's content permanently uncorrectable: an edit to it never ran on | ||
| 352 | +/// any volume that had booted once. The mark now stores this number and the | ||
| 353 | +/// gate compares it against the number this binary computes, so an edited block | ||
| 354 | +/// runs one more time and re-stamps. There is nothing to remember to bump — the | ||
| 355 | +/// hash comes from the very string the server executes, which is the whole | ||
| 356 | +/// point: a hand-kept version is the same discipline failure in a new place. | ||
| 357 | +/// | ||
| 358 | +/// Hashed from the gate through the stamp with comments and indentation | ||
| 359 | +/// dropped: every re-run costs something (the `profile_counters` block says | ||
| 360 | +/// what, in its own comment), so re-wording a comment must not trigger one. | ||
| 361 | +fn marked_blocks() -> Vec<(String, i64)> { | ||
| 362 | + let mut blocks = Vec::new(); | ||
| 363 | + let mut rest = BACKFILL; | ||
| 364 | + while let Some(at) = rest.find(MARK_GATE) { | ||
| 365 | + let block = &rest[at..]; | ||
| 366 | + let name: String = block[MARK_GATE.len()..] | ||
| 367 | + .chars() | ||
| 368 | + .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') | ||
| 369 | + .collect(); | ||
| 370 | + let stamp = format!("UPSERT migration_mark:{name}"); | ||
| 371 | + let end = block | ||
| 372 | + .find(&stamp) | ||
| 373 | + .and_then(|from| block[from..].find(';').map(|to| from + to + 1)) | ||
| 374 | + .unwrap_or_else(|| panic!("the `{name}` block never stamps its own mark")); | ||
| 375 | + blocks.push((format!("fp_{name}"), block_fingerprint(&block[..end]))); | ||
| 376 | + rest = &block[end..]; | ||
| 377 | + } | ||
| 378 | + blocks | ||
| 379 | +} | ||
| 380 | + | ||
| 381 | +/// FNV-1a over a block's statements, comments and layout dropped. | ||
| 382 | +/// | ||
| 383 | +/// Hand-rolled rather than [`std::hash`]: this number is *stored*, so it has to | ||
| 384 | +/// mean the same thing after a compiler upgrade, and `DefaultHasher` promises | ||
| 385 | +/// nothing across versions — a hash that drifted on its own would re-run every | ||
| 386 | +/// one-time block on every volume. | ||
| 387 | +fn block_fingerprint(block: &str) -> i64 { | ||
| 388 | + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; | ||
| 389 | + for line in block | ||
| 390 | + .lines() | ||
| 391 | + .map(str::trim) | ||
| 392 | + .filter(|line| !line.is_empty() && !line.starts_with("--")) | ||
| 393 | + { | ||
| 394 | + for byte in line.bytes().chain(std::iter::once(b'\n')) { | ||
| 395 | + hash = (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3); | ||
| 396 | + } | ||
| 397 | + } | ||
| 398 | + hash as i64 | ||
| 334 | } | 399 | } |
| 335 | 400 | ||
| 336 | #[cfg(test)] | 401 | #[cfg(test)] |
| 337 | mod tests { | 402 | mod tests { |
| 338 | 403 | ||
| 404 | + /// The fingerprint has to move when a *statement* moves and stay put when | ||
| 405 | + /// prose does: a re-run is never free (see the `profile_counters` comment), | ||
| 406 | + /// and a fingerprint that ignored an edit would put us back where this | ||
| 407 | + /// mechanism started — a marked block nobody can correct. | ||
| 408 | + #[test] | ||
| 409 | + fn a_block_fingerprint_tracks_statements_not_prose() { | ||
| 410 | + let block = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 1;\n};"; | ||
| 411 | + let reworded = "IF x = 0 {\n -- why this runs, at length\n UPDATE t SET a = 1;\n};"; | ||
| 412 | + let edited = "IF x = 0 {\n -- why this runs\n UPDATE t SET a = 2;\n};"; | ||
| 413 | + assert_eq!( | ||
| 414 | + super::block_fingerprint(block), | ||
| 415 | + super::block_fingerprint(reworded), | ||
| 416 | + "a re-worded comment or a re-indent must not re-run a one-time block" | ||
| 417 | + ); | ||
| 418 | + assert_ne!( | ||
| 419 | + super::block_fingerprint(block), | ||
| 420 | + super::block_fingerprint(edited), | ||
| 421 | + "an edited statement must re-run its block" | ||
| 422 | + ); | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + /// The forcing function: a one-time block written outside the gate idiom | ||
| 426 | + /// gets no fingerprint parameter, and its `$fp_…` would bind to nothing — a | ||
| 427 | + /// gate that then matches every mark and skips forever. Nothing about the | ||
| 428 | + /// compiler notices, so this does. | ||
| 429 | + #[test] | ||
| 430 | + fn every_one_time_block_is_fingerprinted() { | ||
| 431 | + let blocks = super::marked_blocks(); | ||
| 432 | + let names: Vec<&str> = blocks.iter().map(|(name, _)| name.as_str()).collect(); | ||
| 433 | + assert_eq!( | ||
| 434 | + names, | ||
| 435 | + ["fp_board_roster", "fp_profile_counters"], | ||
| 436 | + "{names:?}" | ||
| 437 | + ); | ||
| 438 | + assert_ne!(blocks[0].1, blocks[1].1, "two blocks, two fingerprints"); | ||
| 439 | + // Two mentions of the mark table per block — its gate and its stamp. A | ||
| 440 | + // third, or a block gated some other way, means a block the binder | ||
| 441 | + // never saw. | ||
| 442 | + assert_eq!( | ||
| 443 | + super::BACKFILL.matches("migration_mark:").count(), | ||
| 444 | + blocks.len() * 2, | ||
| 445 | + "a one-time block outside the `{}…` idiom is invisible to the binder", | ||
| 446 | + super::MARK_GATE | ||
| 447 | + ); | ||
| 448 | + for (param, _) in &blocks { | ||
| 449 | + assert!( | ||
| 450 | + super::BACKFILL.contains(&format!("${param}")), | ||
| 451 | + "nothing reads ${param}" | ||
| 452 | + ); | ||
| 453 | + } | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + /// The fingerprint the mark for `name` must carry once its block has run. | ||
| 457 | + fn expected_fingerprint(name: &str) -> i64 { | ||
| 458 | + super::marked_blocks() | ||
| 459 | + .into_iter() | ||
| 460 | + .find(|(param, _)| *param == format!("fp_{name}")) | ||
| 461 | + .unwrap_or_else(|| panic!("no one-time block named {name}")) | ||
| 462 | + .1 | ||
| 463 | + } | ||
| 464 | + | ||
| 465 | + async fn stamped_fingerprint(db: &super::Database, name: &str) -> Vec<Option<i64>> { | ||
| 466 | + let mut rows = db | ||
| 467 | + .query(format!( | ||
| 468 | + "SELECT VALUE fingerprint FROM migration_mark:{name}" | ||
| 469 | + )) | ||
| 470 | + .await | ||
| 471 | + .unwrap(); | ||
| 472 | + rows.take(0).unwrap() | ||
| 473 | + } | ||
| 474 | + | ||
| 339 | /// The admin seed must not be interruptible into a state no later boot can | 475 | /// The admin seed must not be interruptible into a state no later boot can |
| 340 | /// repair. `create` + `set_role` was: killed between the two writes it | 476 | /// repair. `create` + `set_role` was: killed between the two writes it |
| 341 | /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then | 477 | /// leaves a *student* row holding ADMIN_USERNAME, which `ensure_admin` then |
| @@ -562,6 +698,12 @@ mod tests { | |||
| 562 | 1, | 698 | 1, |
| 563 | "the repair marks itself finished" | 699 | "the repair marks itself finished" |
| 564 | ); | 700 | ); |
| 701 | + // …with the fingerprint of the text it ran, which is what a later edit | ||
| 702 | + // to this block is compared against. | ||
| 703 | + assert_eq!( | ||
| 704 | + stamped_fingerprint(&db, "board_roster").await, | ||
| 705 | + vec![Some(expected_fingerprint("board_roster"))] | ||
| 706 | + ); | ||
| 565 | db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") | 707 | db.query("CREATE board:late SET creator = user:s, title = 'E', participants = [user:p], created_at = 1") |
| 566 | .await | 708 | .await |
| 567 | .unwrap() | 709 | .unwrap() |
| @@ -741,6 +883,10 @@ mod tests { | |||
| 741 | 1, | 883 | 1, |
| 742 | "the seed marks itself finished" | 884 | "the seed marks itself finished" |
| 743 | ); | 885 | ); |
| 886 | + assert_eq!( | ||
| 887 | + stamped_fingerprint(&db, "profile_counters").await, | ||
| 888 | + vec![Some(expected_fingerprint("profile_counters"))] | ||
| 889 | + ); | ||
| 744 | db.query( | 890 | db.query( |
| 745 | "CREATE homework_submission:late SET homework = homework:h, user = user:b, | 891 | "CREATE homework_submission:late SET homework = homework:h, user = user:b, |
| 746 | submitted_at = 90, updated_at = 90;", | 892 | submitted_at = 90, updated_at = 90;", |
| @@ -753,11 +899,142 @@ mod tests { | |||
| 753 | assert_eq!( | 899 | assert_eq!( |
| 754 | counters(&db).await, | 900 | counters(&db).await, |
| 755 | after_first, | 901 | after_first, |
| 756 | - "a marked database skips the seed entirely" | 902 | + "a mark carrying this binary's fingerprint skips the seed entirely" |
| 757 | ); | 903 | ); |
| 758 | assert_eq!(writes(&db).await, first_writes); | 904 | assert_eq!(writes(&db).await, first_writes); |
| 759 | } | 905 | } |
| 760 | 906 | ||
| 907 | + /// A marked block's *content* has to be correctable (2026-08-05). The mark | ||
| 908 | + /// used to record only that the block had run, so an edit to a marked block | ||
| 909 | + /// silently never ran on any volume that had booted once — which is how the | ||
| 910 | + /// `exam_sat_total` seed below (fixed to count sittings, not attempts) | ||
| 911 | + /// would have reached exactly nobody. The mark carries the fingerprint of | ||
| 912 | + /// the text it ran, and a different fingerprint runs the block once more. | ||
| 913 | + #[tokio::test] | ||
| 914 | + async fn an_edited_one_time_block_runs_once_more_and_restamps() { | ||
| 915 | + let db = super::init_mem().await.unwrap(); | ||
| 916 | + // `init_mem` migrates an empty store, so the seed is already marked | ||
| 917 | + // done — the state every booted volume is in. History written *after* | ||
| 918 | + // that mark is the probe: a skip has to leave it uncounted, and a | ||
| 919 | + // re-run has to pick it up. | ||
| 920 | + db.query( | ||
| 921 | + "CREATE user:a SET username = 'a', password_hash = 'x', role = 'student'; | ||
| 922 | + -- One sitting, taken twice. The corrected seed counts the exam, | ||
| 923 | + -- not the attempts, exactly as the request path credits it. | ||
| 924 | + CREATE exam_attempt:e1 SET exam = exam:x, user = user:a, seq = 1, started_at = 1; | ||
| 925 | + CREATE exam_attempt:e2 SET exam = exam:x, user = user:a, seq = 2, started_at = 2; | ||
| 926 | + CREATE pomodoro_session:p1 SET user = user:a, started_at = 1000, finished_at = 2000;", | ||
| 927 | + ) | ||
| 928 | + .await | ||
| 929 | + .unwrap() | ||
| 930 | + .check() | ||
| 931 | + .unwrap(); | ||
| 932 | + | ||
| 933 | + async fn counters(db: &super::Database) -> Vec<(i64, i64)> { | ||
| 934 | + let mut rows = db | ||
| 935 | + .query( | ||
| 936 | + // `?? 0`, parenthesized: the columns are `option<int>` and | ||
| 937 | + // a row the seed has not touched holds neither. | ||
| 938 | + "SELECT VALUE [(exam_sat_total ?? 0), (pomodoro_finished_total ?? 0)] | ||
| 939 | + FROM user ORDER BY id", | ||
| 940 | + ) | ||
| 941 | + .await | ||
| 942 | + .unwrap(); | ||
| 943 | + rows.take::<Vec<Vec<i64>>>(0) | ||
| 944 | + .unwrap() | ||
| 945 | + .into_iter() | ||
| 946 | + .map(|row| (row[0], row[1])) | ||
| 947 | + .collect() | ||
| 948 | + } | ||
| 949 | + let fp = expected_fingerprint("profile_counters"); | ||
| 950 | + | ||
| 951 | + // Same binary, same fingerprint: the block does not run, and the | ||
| 952 | + // history above stays uncounted. That is the mark still doing its job. | ||
| 953 | + super::migrate(&db).await.unwrap(); | ||
| 954 | + assert_eq!(counters(&db).await, vec![(0, 0)]); | ||
| 955 | + assert_eq!( | ||
| 956 | + stamped_fingerprint(&db, "profile_counters").await, | ||
| 957 | + vec![Some(fp)] | ||
| 958 | + ); | ||
| 959 | + | ||
| 960 | + // A write probe on the seeded table, defined now so it counts only the | ||
| 961 | + // runs under test: the event fires *inside* the UPDATE, so "exactly | ||
| 962 | + // once" is measured rather than inferred from the numbers. | ||
| 963 | + db.query( | ||
| 964 | + "DEFINE TABLE user_write_probe SCHEMALESS; | ||
| 965 | + DEFINE EVENT user_write ON user WHEN $event = 'UPDATE' THEN { | ||
| 966 | + UPSERT type::record('user_write_probe', 'n') SET n = (n ?? 0) + 1; | ||
| 967 | + }; | ||
| 968 | + -- A mark written by the binary before fingerprints existed: the | ||
| 969 | + -- row is there, the column is not. This is the live volumes' | ||
| 970 | + -- state, and it must run the corrected block exactly once. | ||
| 971 | + UPDATE migration_mark:profile_counters UNSET fingerprint;", | ||
| 972 | + ) | ||
| 973 | + .await | ||
| 974 | + .unwrap() | ||
| 975 | + .check() | ||
| 976 | + .unwrap(); | ||
| 977 | + assert_eq!( | ||
| 978 | + stamped_fingerprint(&db, "profile_counters").await, | ||
| 979 | + vec![None] | ||
| 980 | + ); | ||
| 981 | + | ||
| 982 | + super::migrate(&db).await.unwrap(); | ||
| 983 | + // Two attempt rows, one exam: the corrected seed says one sitting, the | ||
| 984 | + // number the request path would have given. The old text said two. | ||
| 985 | + assert_eq!(counters(&db).await, vec![(1, 1)]); | ||
| 986 | + assert_eq!( | ||
| 987 | + stamped_fingerprint(&db, "profile_counters").await, | ||
| 988 | + vec![Some(fp)] | ||
| 989 | + ); | ||
| 990 | + | ||
| 991 | + async fn writes(db: &super::Database) -> Vec<i64> { | ||
| 992 | + let mut rows = db | ||
| 993 | + .query("SELECT VALUE n FROM user_write_probe:n") | ||
| 994 | + .await | ||
| 995 | + .unwrap(); | ||
| 996 | + rows.take(0).unwrap() | ||
| 997 | + } | ||
| 998 | + let one_run = writes(&db).await; | ||
| 999 | + // Pinned non-zero, not merely compared: "it did not run twice" holds | ||
| 1000 | + // vacuously if the probe stopped firing, and the test would then pass | ||
| 1001 | + // on a mechanism that never runs anything at all. | ||
| 1002 | + assert!(matches!(one_run.as_slice(), [n] if *n > 0), "{one_run:?}"); | ||
| 1003 | + | ||
| 1004 | + // Once more, not on every boot: the re-run re-stamped, so the next boot | ||
| 1005 | + // is a plain skip again. | ||
| 1006 | + super::migrate(&db).await.unwrap(); | ||
| 1007 | + assert_eq!(counters(&db).await, vec![(1, 1)]); | ||
| 1008 | + assert_eq!(writes(&db).await, one_run, "the re-run happened once"); | ||
| 1009 | + | ||
| 1010 | + // And now the edit this whole mechanism exists for: a mark whose stored | ||
| 1011 | + // fingerprint is some *other* text's. The block runs again and lands on | ||
| 1012 | + // the same numbers — every SET is absolute, so a re-run converges | ||
| 1013 | + // instead of doubling what the first pass wrote. | ||
| 1014 | + db.query("UPDATE migration_mark:profile_counters SET fingerprint = 1") | ||
| 1015 | + .await | ||
| 1016 | + .unwrap() | ||
| 1017 | + .check() | ||
| 1018 | + .unwrap(); | ||
| 1019 | + super::migrate(&db).await.unwrap(); | ||
| 1020 | + assert_eq!( | ||
| 1021 | + counters(&db).await, | ||
| 1022 | + vec![(1, 1)], | ||
| 1023 | + "a re-run recomputes, it does not add to what is there" | ||
| 1024 | + ); | ||
| 1025 | + assert_eq!( | ||
| 1026 | + writes(&db).await, | ||
| 1027 | + vec![one_run[0] * 2], | ||
| 1028 | + "the edited block did the same work a second time, and no more" | ||
| 1029 | + ); | ||
| 1030 | + assert_eq!( | ||
| 1031 | + stamped_fingerprint(&db, "profile_counters").await, | ||
| 1032 | + vec![Some(fp)] | ||
| 1033 | + ); | ||
| 1034 | + super::migrate(&db).await.unwrap(); | ||
| 1035 | + assert_eq!(writes(&db).await, vec![one_run[0] * 2], "and stopped again"); | ||
| 1036 | + } | ||
| 1037 | + | ||
| 761 | #[tokio::test] | 1038 | #[tokio::test] |
| 762 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { | 1039 | async fn the_retired_claim_columns_are_dropped_off_a_live_row() { |
| 763 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. | 1040 | // Stale-data path for the 2026-07-30 removal of the chat claim queue. |
src/migration_sql.rsmodified+54 -8
| @@ -893,8 +893,20 @@ pub const MIGRATION: &str = " | |||
| 893 | -- boot loop carries no lock and no fingerprint any more (2026-07-30), so | 893 | -- boot loop carries no lock and no fingerprint any more (2026-07-30), so |
| 894 | -- there is nowhere else for that fact to live. A database that never ran the | 894 | -- there is nowhere else for that fact to live. A database that never ran the |
| 895 | -- repair holds no row and runs it; the row is written by the same query. | 895 | -- repair holds no row and runs it; the row is written by the same query. |
| 896 | + -- | ||
| 897 | + -- `fingerprint` is *which* text ran (2026-08-05), and it is what makes a | ||
| 898 | + -- marked block correctable. Saying only 'this ran' meant an edit to a block | ||
| 899 | + -- that was already marked could never reach a volume that had booted once: | ||
| 900 | + -- the `exam_sat_total` correction below shipped inside one and would have | ||
| 901 | + -- been dead on arrival on every existing database. The gate compares the | ||
| 902 | + -- stored number against the hash of the text *this* binary would run | ||
| 903 | + -- (`database::marked_blocks`), so an edited block runs once more and | ||
| 904 | + -- re-stamps, and an unedited one still costs a single record read. | ||
| 905 | + -- `option<int>`: a mark written before this column existed carries none, | ||
| 906 | + -- which matches no fingerprint and so re-runs its block exactly once. | ||
| 896 | DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL; | 907 | DEFINE TABLE IF NOT EXISTS migration_mark SCHEMAFULL; |
| 897 | DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int; | 908 | DEFINE FIELD IF NOT EXISTS done_at ON migration_mark TYPE int; |
| 909 | + DEFINE FIELD IF NOT EXISTS fingerprint ON migration_mark TYPE option<int>; | ||
| 898 | "; | 910 | "; |
| 899 | 911 | ||
| 900 | /// Data backfills for rows written by older binaries. Runs *after* (and apart | 912 | /// Data backfills for rows written by older binaries. Runs *after* (and apart |
| @@ -1074,10 +1086,21 @@ pub const BACKFILL: &str = " | |||
| 1074 | }; | 1086 | }; |
| 1075 | }; | 1087 | }; |
| 1076 | 1088 | ||
| 1077 | - -- Per-attempt history (2026-07-24): answers, drawings, and marks written | 1089 | + -- Per-attempt history (2026-07-24): sittings, answers, drawings, and marks |
| 1078 | - -- before retakes stopped wiping belong to the student's first sitting. | 1090 | + -- written before retakes stopped wiping belong to the student's first |
| 1079 | - -- They already use the bare (seq==1) record key, so only the denormalized | 1091 | + -- sitting. They already use the bare (seq==1) record key, so only the |
| 1080 | - -- `seq` field needs stamping. | 1092 | + -- denormalized `seq` field needs stamping. |
| 1093 | + -- | ||
| 1094 | + -- `exam_attempt` was left out of this list when the other three were added | ||
| 1095 | + -- and that is not a decision, it is a gap: `DEFAULT 1` fills a CREATE, never | ||
| 1096 | + -- a row stored before the column was defined, and 3.2.3 does not synthesize | ||
| 1097 | + -- it on read either — such a row comes back with no `seq` key at all, which | ||
| 1098 | + -- makes `ExamAttempt` (a non-`option` `i64`) fail to deserialize *and* makes | ||
| 1099 | + -- every later write to the row fail coercion, so finishing or leaving that | ||
| 1100 | + -- sitting 500s forever. Ungated like its siblings and for the same reason: | ||
| 1101 | + -- the cost here is the write, not a scan, and `WHERE seq = NONE` matches | ||
| 1102 | + -- nothing the moment it has converged. | ||
| 1103 | + UPDATE exam_attempt SET seq = 1 WHERE seq = NONE; | ||
| 1081 | UPDATE exam_answer SET seq = 1 WHERE seq = NONE; | 1104 | UPDATE exam_answer SET seq = 1 WHERE seq = NONE; |
| 1082 | UPDATE answer_image SET seq = 1 WHERE seq = NONE; | 1105 | UPDATE answer_image SET seq = 1 WHERE seq = NONE; |
| 1083 | UPDATE exam_result SET seq = 1 WHERE seq = NONE; | 1106 | UPDATE exam_result SET seq = 1 WHERE seq = NONE; |
| @@ -1274,12 +1297,19 @@ pub const BACKFILL: &str = " | |||
| 1274 | -- statement batch, so a boot killed mid-repair writes no mark and the next | 1297 | -- statement batch, so a boot killed mid-repair writes no mark and the next |
| 1275 | -- one redoes the whole sweep — which is free, because the sweep is | 1298 | -- one redoes the whole sweep — which is free, because the sweep is |
| 1276 | -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error. | 1299 | -- idempotent. `UPSERT`, not `CREATE`: re-marking must never be an error. |
| 1277 | - IF array::len((SELECT VALUE id FROM migration_mark:board_roster)) = 0 { | 1300 | + -- |
| 1301 | + -- Editing this block is therefore safe at any time: the fingerprint gate | ||
| 1302 | + -- re-runs it once and the sweep converges on whatever it finds, exactly as | ||
| 1303 | + -- a boot killed mid-repair would. The mark buys the scan back, not | ||
| 1304 | + -- correctness. | ||
| 1305 | + IF array::len((SELECT VALUE id FROM migration_mark:board_roster | ||
| 1306 | + WHERE fingerprint = $fp_board_roster)) = 0 { | ||
| 1278 | FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) { | 1307 | FOR $row IN ((SELECT id, participants FROM board WHERE array::len(participants ?? []) > 0) ?? []) { |
| 1279 | LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent'); | 1308 | LET $keep = (SELECT VALUE id FROM user WHERE id IN $row.participants AND role != 'parent'); |
| 1280 | UPDATE $row.id SET participants = $keep WHERE participants != $keep; | 1309 | UPDATE $row.id SET participants = $keep WHERE participants != $keep; |
| 1281 | }; | 1310 | }; |
| 1282 | - UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000; | 1311 | + UPSERT migration_mark:board_roster SET done_at = time::unix(time::now()) * 1000, |
| 1312 | + fingerprint = $fp_board_roster; | ||
| 1283 | }; | 1313 | }; |
| 1284 | 1314 | ||
| 1285 | -- The badge counters, seeded from the history that already exists | 1315 | -- The badge counters, seeded from the history that already exists |
| @@ -1336,7 +1366,22 @@ pub const BACKFILL: &str = " | |||
| 1336 | -- by the very same cut, so a submission that predates this seed debits at | 1366 | -- by the very same cut, so a submission that predates this seed debits at |
| 1337 | -- withdrawal exactly what the seed credited it. Absolute like every SET | 1367 | -- withdrawal exactly what the seed credited it. Absolute like every SET |
| 1338 | -- below, so it converges on a forced re-seed. | 1368 | -- below, so it converges on a forced re-seed. |
| 1339 | - IF array::len((SELECT VALUE id FROM migration_mark:profile_counters)) = 0 { | 1369 | + -- |
| 1370 | + -- ponytail: editing this block re-runs it (the fingerprint gate), and unlike | ||
| 1371 | + -- the board sweep above this one is only *mostly* re-runnable. Every SET is | ||
| 1372 | + -- absolute, so a re-run converges on the rows that exist — but two of the | ||
| 1373 | + -- counters are lifetime tallies the request path never decrements while the | ||
| 1374 | + -- rows behind them can be deleted (`exam_sat_total`, | ||
| 1375 | + -- `homework_submitted_total`, see the paragraph above). On a volume where a | ||
| 1376 | + -- teacher has deleted an exam or a homework since the last seed, a re-run | ||
| 1377 | + -- reads *lower* than the live count and the student's tally walks backwards | ||
| 1378 | + -- — badges already awarded are permanent, so nothing is revoked, but the | ||
| 1379 | + -- next one moves further away. Correcting this block is a deliberate trade, | ||
| 1380 | + -- not a free edit. The upgrade path, if it ever needs to be free: keep the | ||
| 1381 | + -- deleted rows' contribution on the row (a `*_retired` column the delete | ||
| 1382 | + -- bumps) so the recount can add it back. | ||
| 1383 | + IF array::len((SELECT VALUE id FROM migration_mark:profile_counters | ||
| 1384 | + WHERE fingerprint = $fp_profile_counters)) = 0 { | ||
| 1340 | UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0, | 1385 | UPDATE user SET homework_submitted_total = 0, homework_on_time_total = 0, |
| 1341 | exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0; | 1386 | exam_sat_total = 0, pomodoro_finished_total = 0, pomodoro_focus_ms_total = 0; |
| 1342 | FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) { | 1387 | FOR $row IN ((SELECT user, count() AS n FROM homework_submission GROUP BY user) ?? []) { |
| @@ -1362,7 +1407,8 @@ pub const BACKFILL: &str = " | |||
| 1362 | UPDATE $row.user SET pomodoro_finished_total = $row.sessions, | 1407 | UPDATE $row.user SET pomodoro_finished_total = $row.sessions, |
| 1363 | pomodoro_focus_ms_total = $row.focus_ms; | 1408 | pomodoro_focus_ms_total = $row.focus_ms; |
| 1364 | }; | 1409 | }; |
| 1365 | - UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000; | 1410 | + UPSERT migration_mark:profile_counters SET done_at = time::unix(time::now()) * 1000, |
| 1411 | + fingerprint = $fp_profile_counters; | ||
| 1366 | }; | 1412 | }; |
| 1367 | "; | 1413 | "; |
| 1368 | 1414 | ||