forge
Explore
Log in

Don't you dare go Hollow

πŸ“ tell the truth about a board body

Browse files at this commit

c47fb00c6eb3f78a54bb85101a44d2dc980d14f9Ahmet Kaan GümüşParent: 43bbae8
  • docs
    • πŸ“ tell the truth about a board body
Show full message
docs: πŸ“ tell the truth about a board body

Rejecting unknown keys made POST and PATCH /boards answer 422, a status
neither utoipa block declared, so a generated client had no case for the
first status a read-modify-write caller hits. Both now list it.

The README went further and promised the opposite of what ships: it said
the shared `participants` spelling meant a client "may post back a board
it just read", but a board response carries id, creator, locked_by and
epoch β€” all unknown to the request β€” so a verbatim round-trip is exactly
the 422. It now says to send the writable fields only.

The race test that comes with this is a smoke test and says so: cutting
the retry to a single attempt leaves it green in five runs of five, while
the same cut reddens its course.rs twin in two of three. Nothing exercises
this delete's retry; it stays because the batch is admissible for it, not
because a test has caught it losing a round.
README.mdmodified+9 -4
@@ -2510,10 +2510,15 @@ model β€” no course, no lesson session, no appointment. Any account from
2510 alone clears, locks, closes or deletes.**2510 alone clears, locks, closes or deletes.**
2511 2511
2512 The roster is spelled `participants` everywhere β€” in the `POST` body, in the2512 The roster is spelled `participants` everywhere β€” in the `POST` body, in the
2513-`PATCH` body and in every board response β€” so a client may post back a board it2513+`PATCH` body and in every board response β€” so the field never changes name
2514-just read. Unlike the rest of this API, the two board request bodies **reject2514+between a request and a reply. That is the *only* thing the shared spelling
2515-an unknown key** (`422`) rather than ignoring it: a misspelled roster would2515+buys: unlike the rest of this API, the two board request bodies **reject an
2516-otherwise open a board its author is silently alone on.2516+unknown key** (`422`) rather than ignoring it, because a misspelled roster
2517+would otherwise open a board its author is silently alone on. So a body must
2518+carry **only** the fields that request accepts β€” a board it just read is not a
2519+legal body, since `id`, `creator`, `locked_by`, `epoch` and the rest are all
2520+unknown to `POST` and `PATCH`. A read-modify-write client sends the writable
2521+fields it changed, never the whole board object back.
2517 2522
2518 **No parents, anywhere.** The `parent` role is the school's read-only observer,2523 **No parents, anywhere.** The `parent` role is the school's read-only observer,
2519 and it has no whiteboard access at all β€” not a view-only tier, none. It is2524 and it has no whiteboard access at all β€” not a view-only tier, none. It is
src/domain/board.rsmodified+104 -0
@@ -498,4 +498,108 @@ mod tests {
498 .unwrap();498 .unwrap();
499 assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]);499 assert_eq!(result.take::<Vec<Vec<i64>>>(0).unwrap()[0], vec![7, 9]);
500 }500 }
501+
502+ /// [`Board::delete`] cascades the stroke log and decrements the creator's
503+ /// `board_count` off the very record a concurrent stroke claim increments,
504+ /// so the two contend by design. Losing that round writes nothing, which is
505+ /// what makes re-sending it the recovery; without
506+ /// [`crate::database::transaction_with_retry`] a lost round comes out as a
507+ /// 500.
508+ ///
509+ /// A refusal or an `Err(NotFound)` is *correct* here β€” the board really is
510+ /// gone β€” and must not fail this test. The only defect is `AppError::Db`.
511+ ///
512+ /// Multi-threaded and on a real server for the reason spelled out on
513+ /// [`super::super::course`]'s twin: the current-thread runtime never
514+ /// interleaves the two, and the embedded engine does not conflict-check
515+ /// concurrent writes to one record at all.
516+ ///
517+ /// Mutation status, stated honestly: cutting
518+ /// [`crate::database::transaction_with_retry`] to a single attempt leaves
519+ /// this GREEN β€” 5 runs of 5, every one at 20/20 contended. The mutation is
520+ /// real, not a dud: the same cut reddens the `course.rs` twin in 2 runs of
521+ /// 3. So the delete here never actually loses a round in this window, and
522+ /// nothing in the suite exercises its retry. Read this as a smoke test that
523+ /// a contended delete does not 500 β€” the retry stays because the batch is
524+ /// admissible for it and a lost round is possible in principle, not because
525+ /// a test has ever caught it losing one.
526+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
527+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
528+ async fn a_delete_racing_a_stroke_never_answers_500() {
529+ use crate::domain::board_stroke::BoardStroke;
530+ let (db, _serialized) = crate::database::init_test_server("board_delete_race").await;
531+ db.query("CREATE user:c SET username = 'c', password_hash = 'x';")
532+ .await
533+ .unwrap()
534+ .check()
535+ .unwrap();
536+ let (mut delete_500, mut stroke_500, mut drawn) = (0, 0, 0);
537+ let (mut last_delete, mut last_stroke) = (String::new(), String::new());
538+ for round in 0..20 {
539+ let board = a_board(&db).await;
540+ // The delete is held back by a sweeping beat: released together it
541+ // is one statement while an append spends a read before it claims,
542+ // so it would win every round and the guard would never be
543+ // contended at all. Six racers over a 0-3ms sweep put the delete
544+ // somewhere inside the counter writes instead.
545+ let drop_it = {
546+ let (board, db) = (board.clone(), db.clone());
547+ let beat = std::time::Duration::from_millis(round % 4);
548+ tokio::spawn(async move {
549+ tokio::time::sleep(beat).await;
550+ board.delete(&db).await
551+ })
552+ };
553+ let marks: Vec<_> = (0..6)
554+ .map(|mark| {
555+ let (id, db) = (board.get_id().clone(), db.clone());
556+ let author = user("c");
557+ tokio::spawn(async move {
558+ BoardStroke::append(&id, &author, &format!("{{\"m\":{mark}}}"), 0, &db)
559+ .await
560+ })
561+ })
562+ .collect();
563+ let drop_it = drop_it.await.unwrap();
564+ if matches!(drop_it, Err(AppError::Db(_))) {
565+ delete_500 += 1;
566+ last_delete = format!("{drop_it:?}");
567+ }
568+ // Contention is counted off the claim's own outcome, not off stored
569+ // rows: the delete cascades `board_stroke`, so a stroke that landed
570+ // and then lost its board leaves nothing behind to count. An `Ok`
571+ // means the claim committed against the board row the delete was
572+ // tearing down, which is exactly the overlap being measured.
573+ let mut claimed = 0;
574+ for mark in marks {
575+ let mark = mark.await.unwrap();
576+ if matches!(mark, Err(AppError::Db(_))) {
577+ stroke_500 += 1;
578+ last_stroke = format!("{mark:?}");
579+ }
580+ if mark.is_ok() {
581+ claimed += 1;
582+ }
583+ }
584+ if claimed > 0 {
585+ drawn += 1;
586+ }
587+ }
588+ eprintln!(
589+ "Board::delete raced: {delete_500}/20 delete 500s, {stroke_500} stroke 500s, \
590+ {drawn}/20 rounds with a stroke claimed"
591+ );
592+ assert!(
593+ drawn > 0,
594+ "no round ever landed a stroke, so the delete's cascade was never contended"
595+ );
596+ assert_eq!(
597+ delete_500, 0,
598+ "a raced delete must retry, not 500: {delete_500}/20 rounds, last {last_delete}"
599+ );
600+ assert_eq!(
601+ stroke_500, 0,
602+ "a raced stroke must retry, not 500: {stroke_500}/20 rounds, last {last_stroke}"
603+ );
604+ }
501 }605 }
src/domain/cap.rsmodified+4 -1
@@ -272,7 +272,10 @@ pub(crate) enum ClaimedTwo<T> {
272 /// slots are the same type β€” and misreport that forever. The names are the272 /// slots are the same type β€” and misreport that forever. The names are the
273 /// guard against it.273 /// guard against it.
274 ///274 ///
275-/// The fields and `guard` are always in-crate constants, never user input.275+/// The fields are always in-crate constants, and `guard` is either one or
276+/// built in-crate out of numbers this crate read back itself
277+/// (`board_stroke::append` appends an `epoch` it took off the board row) β€”
278+/// never text from a client.
276 pub(crate) async fn claim_two_when_and_create<T: SurrealValue + Clone>(279 pub(crate) async fn claim_two_when_and_create<T: SurrealValue + Clone>(
277 parent: &RecordId,280 parent: &RecordId,
278 soft_field: &str,281 soft_field: &str,
src/web/boards.rsmodified+2 -0
@@ -239,6 +239,7 @@ struct CreateBoard {
239 (status = 401, description = "Not authenticated", body = ErrorResponse),239 (status = 401, description = "Not authenticated", body = ErrorResponse),
240 (status = 403, description = "The caller is a parent", body = ErrorResponse),240 (status = 403, description = "The caller is a parent", body = ErrorResponse),
241 (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),241 (status = 409, description = "The caller already holds the maximum number of boards", body = ErrorResponse),
242+ (status = 422, description = "The body carries a key this request does not accept β€” a board response cannot be posted back verbatim"),
242 ),243 ),
243 )]244 )]
244 async fn create_board(245 async fn create_board(
@@ -453,6 +454,7 @@ struct UpdateBoard {
453 (status = 401, description = "Not authenticated", body = ErrorResponse),454 (status = 401, description = "Not authenticated", body = ErrorResponse),
454 (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),455 (status = 403, description = "Only the creator may change the participants or the lock", body = ErrorResponse),
455 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),456 (status = 404, description = "Not found, or the caller is not on it", body = ErrorResponse),
457+ (status = 422, description = "The body carries a key this request does not accept β€” a board response cannot be posted back verbatim"),
456 ),458 ),
457 )]459 )]
458 async fn update_board(460 async fn update_board(