1672 lines · 70.1 KB · RustRaw
use super::*;use crate::definitions::TableDefinition;use serde_json::json;/// A synthetic table a person might define: one column of every type the/// encoding decides, a required title, a manual order and a project.fn lesson() -> TableDefinition { let definition = TableDefinition::from_json( &json!({ "id": "lesson", "name": "Lesson", "plural": "Lessons", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "title", "type": "text", "required": true }, { "key": "notes", "type": "longtext" }, { "key": "day", "type": "date" }, { "key": "starts", "type": "time" }, { "key": "minutes", "type": "number" }, { "key": "size", "type": "bytes" }, { "key": "fee", "type": "amount" }, { "key": "level", "type": "choice", "choices": ["beginner", "advanced"] }, { "key": "student", "type": "link", "link_to": "student" }, { "key": "project", "type": "link", "link_to": "project" }, { "key": "sheet", "type": "photo" }, { "key": "recording", "type": "file" }, { "key": "paid", "type": "bool" }, { "key": "position", "type": "number" } ], "title": "title", "date": "day", "project": "project", "order": "position", "slip": { "title": "title", "subtitle": "notes", "trailing": "day", "photo": null, "toggle": "paid" }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["title", "notes"] } ], "instructions": "A lesson is one class." }) .to_string(), ) .expect("parses"); definition.validate().expect("a valid definition"); definition}fn column(key: &str) -> Column { lesson().column(key).expect("declared").clone()}fn data(value: Value) -> Data { value.as_object().expect("an object").clone()}// ── values ──────────────────────────────────────────────────────────────────/// Every column type, the values it takes and the values it refuses — the/// whole encoding table.#[test]fn every_column_type_takes_its_encoding_and_nothing_else() { let cases: &[(&str, &[Value], &[Value])] = &[ ( "title", &[json!("Scales"), json!("")], &[json!(1), json!(true), json!(["a"]), json!({})], ), ("notes", &[json!("line one\nline two")], &[json!(2.5)]), ( "day", &[json!("2026-10-01"), json!("2024-02-29")], &[ json!("2026-02-30"), json!("2026-1-5"), json!("01-10-2026"), json!("2026-10-01T09:00:00Z"), json!(20261001), ], ), ( "starts", &[json!("09:30"), json!("00:00"), json!("23:59")], &[ json!("24:00"), json!("9:30"), json!("09:30:00"), json!("half nine"), json!(930), ], ), ( "minutes", &[json!(45), json!(45.5), json!(-1), json!(0)], &[json!("45"), json!(true)], ), ("size", &[json!(0), json!(400_000), json!(2_300_000_000u64)], &[json!(-1), json!(1.5), json!("400")]), ( "fee", &[json!(150_000), json!(0), json!(-2500)], &[json!("150000"), json!(true)], ), ( "level", &[json!("beginner"), json!("advanced")], &[json!("Beginner"), json!("expert"), json!(1)], ), ( "student", &[json!("0f5c3a52-1111-4111-8111-000000000001")], &[json!(""), json!(" "), json!(1)], ), ( "sheet", &[json!("media/abc123")], &[json!(""), json!(false)], ), ( "recording", &[json!("media/def456")], &[json!(""), json!(3)], ), ( "paid", &[json!(true), json!(false)], &[json!("true"), json!(1), json!(0)], ), ]; for (key, good, bad) in cases { let column = column(key); for value in *good { assert_eq!(check_value(&column, value), Ok(()), "{key} takes {value}"); } for value in *bad { assert!( check_value(&column, value).is_err(), "{key} refuses {value}" ); } }}/// RULE: An amount is a whole number of minor units; a fractional amount, even one ending in .0, is refused and never rounded.#[test]fn an_amount_is_never_a_float() { let fee = column("fee"); for value in [ json!(12.5), json!(12.0), json!(0.1), serde_json::from_str::<Value>("150000.0").unwrap(), ] { assert!( matches!( check_value(&fee, &value), Err(RecordError::NotWholeAmount { .. }) ), "{value} is refused as a fractional amount" ); } // Beyond what an i64 holds is not an amount either. let huge = serde_json::from_str::<Value>("18446744073709551615").unwrap(); assert!(check_value(&fee, &huge).is_err());}#[test]fn a_choice_refusal_names_the_choices() { let error = check_value(&column("level"), &json!("expert")).unwrap_err(); assert_eq!( error.to_string(), "\"level\" takes one of beginner, advanced; \"expert\" is not one" );}#[test]fn dates_and_times_are_strict() { for text in ["2026-10-01", "1999-12-31", "2000-02-29"] { assert!(is_date(text), "{text}"); } for text in [ "2026-13-01", "2026-00-10", "2026-10-1", "2026/10/01", "1900-02-29", " 2026-10-01", "", ] { assert!(!is_date(text), "{text}"); } for text in ["00:00", "12:05", "23:59"] { assert!(is_time(text), "{text}"); } for text in ["24:00", "12:60", "1:05", "12:5", "12.05", "12:05:00", ""] { assert!(!is_time(text), "{text}"); }}// RULE: a yearly date (a birthday) takes the day with no year, "--MM-DD", as every read says it; a date that is not yearly never does.#[test]fn a_yearly_date_takes_the_day_with_no_year() { let yearly: Column = serde_json::from_value(json!({"key": "birthday", "type": "date", "yearly": true})).unwrap(); let plain: Column = serde_json::from_value(json!({"key": "due", "type": "date"})).unwrap(); for text in ["--03-02", "--02-29", "--12-31", "1991-11-09"] { assert!(check_value(&yearly, &json!(text)).is_ok(), "{text}"); } for text in ["--13-01", "--02-30", "--3-02", "--03-02-", "03-02", "--"] { assert!(check_value(&yearly, &json!(text)).is_err(), "{text}"); } assert!(check_value(&plain, &json!("--03-02")).is_err());}// ── create and patch ────────────────────────────────────────────────────────#[test]fn a_create_is_checked_whole_and_drops_nulls() { let clean = validate_create( &lesson(), &json!({ "title": "Scales", "fee": 150_000, "notes": null, "paid": false }), ) .expect("fits"); assert_eq!( clean, data(json!({ "title": "Scales", "fee": 150_000, "paid": false })) );}/// RULE: A record is refused with a plain reason when it names a column its table does not have, lacks a required one, or holds a value of the wrong type.#[test]fn a_create_refuses_unknown_missing_and_mistyped_values() { let table = lesson(); assert_eq!( validate_create(&table, &json!({ "title": "Scales", "colour": "red" })), Err(RecordError::UnknownColumn { plural: "Lessons".into(), column: "colour".into() }) ); assert_eq!( validate_create(&table, &json!({ "notes": "no title" })), Err(RecordError::Required { column: "title".into() }) ); assert_eq!( validate_create(&table, &json!({ "title": null })), Err(RecordError::Required { column: "title".into() }) ); assert!(matches!( validate_create(&table, &json!({ "title": "Scales", "day": "tomorrow" })), Err(RecordError::WrongType { .. }) )); assert_eq!( validate_create(&table, &json!(["title"])), Err(RecordError::NotAnObject) ); assert_eq!( RecordError::UnknownColumn { plural: "Lessons".into(), column: "colour".into() } .to_string(), "Lessons have no column \"colour\"" );}#[test]fn a_patch_may_clear_but_never_a_required_column() { let table = lesson(); assert_eq!( validate_patch(&table, &json!({ "notes": null, "fee": 2000 })), Ok(data(json!({ "notes": null, "fee": 2000 }))) ); assert_eq!( validate_patch(&table, &json!({ "title": null })), Err(RecordError::Required { column: "title".into() }) ); assert_eq!( validate_patch(&table, &json!({})), Err(RecordError::NothingToChange) ); assert!(matches!( validate_patch(&table, &json!({ "fee": 20.5 })), Err(RecordError::NotWholeAmount { .. }) )); assert!(matches!( validate_patch(&table, &json!({ "nope": 1 })), Err(RecordError::UnknownColumn { .. }) )); assert_eq!( validate_patch(&table, &json!("x")), Err(RecordError::NotAnObject) );}#[test]fn a_patch_lays_over_and_a_null_removes() { let before = data(json!({ "title": "Scales", "notes": "slow", "fee": 100 })); let patch = data(json!({ "notes": null, "fee": 200, "paid": true })); assert_eq!( apply_patch(&before, &patch), data(json!({ "title": "Scales", "fee": 200, "paid": true })) );}#[test]fn a_diff_holds_only_what_changed_with_null_for_absent() { let before = data(json!({ "title": "Scales", "notes": "slow", "fee": 100 })); let after = data(json!({ "title": "Scales", "fee": 200, "paid": true })); let (was, now) = diff(&before, &after); assert_eq!( was, data(json!({ "notes": "slow", "fee": 100, "paid": null })) ); assert_eq!( now, data(json!({ "notes": null, "fee": 200, "paid": true })) ); let (was, now) = diff(&before, &before); assert!(was.is_empty() && now.is_empty());}/// RULE: A number read back from the database in another spelling (1 for 1.0) is the same value, so no diff or undo check sees a change nobody made.#[test]fn numbers_compare_by_value_not_spelling() { assert!(same_value(&json!(1), &json!(1.0))); assert!(same_value(&json!({ "a": [2, 3.0] }), &json!({ "a": [2.0, 3] }))); assert!(!same_value(&json!(1), &json!(1.5))); assert!(!same_value(&json!(1), &json!("1"))); assert!(!same_value(&json!({ "a": 1 }), &json!({ "a": 1, "b": 2 }))); let (was, now) = diff(&data(json!({ "p": 1.0 })), &data(json!({ "p": 1 }))); assert!(was.is_empty() && now.is_empty()); assert!(matches_on(&data(json!({ "p": 3.0 })), &data(json!({ "p": 3 }))));}#[test]fn matching_reads_absent_as_null() { let current = data(json!({ "title": "Scales", "fee": 100 })); assert!(matches_on( ¤t, &data(json!({ "fee": 100, "notes": null })) )); assert!(!matches_on(¤t, &data(json!({ "fee": 200 })))); assert!(same_record( ¤t, &data(json!({ "title": "Scales", "fee": 100, "paid": null })) )); assert!(!same_record(¤t, &data(json!({ "title": "Scales" }))));}// ── reorder and link ────────────────────────────────────────────────────────#[test]fn a_reorder_numbers_the_listed_records_from_one() { let ids: Vec<String> = ["c", "a", "b"].iter().map(|s| s.to_string()).collect(); assert_eq!( plan_reorder(&ids).unwrap(), vec![ ("c".to_string(), 1.0), ("a".to_string(), 2.0), ("b".to_string(), 3.0) ] ); assert_eq!(plan_reorder(&[]), Err(RecordError::BadReorder)); assert_eq!( plan_reorder(&["a".to_string(), "a".to_string()]), Err(RecordError::BadReorder) ); assert_eq!(plan_reorder(&[String::new()]), Err(RecordError::BadReorder));}/// RULE: A table with no order column cannot be reordered, and says so in plain words.#[test]fn a_table_without_an_order_refuses_a_reorder() { let mut table = lesson(); assert_eq!(order_column(&table), Ok("position")); table.order = None; let error = order_column(&table).unwrap_err(); assert_eq!( error.to_string(), "Lessons have no manual order, so they cannot be reordered" );}#[test]fn only_a_link_column_links() { let table = lesson(); assert_eq!( link_column(&table, "student").map(|c| c.key.as_str()), Ok("student") ); assert_eq!( link_column(&table, "title").map(|c| c.key.clone()), Err(RecordError::NotALink { column: "title".into() }) ); assert!(matches!( link_column(&table, "nope"), Err(RecordError::UnknownColumn { .. }) ));}#[test]fn every_verb_round_trips_its_spelling() { for verb in Verb::ALL { assert_eq!(Verb::parse(verb.as_str()), Some(verb)); assert_eq!(serde_json::to_value(verb).unwrap(), json!(verb.as_str())); } assert_eq!(Verb::parse("undo"), None);}// ── undo ────────────────────────────────────────────────────────────────────fn change(id: &str, verb: Verb, record: Option<&str>, before: Value, after: Value) -> Change { Change { id: id.to_string(), table_id: "lesson".to_string(), record_id: record.map(str::to_string), verb, byline: "assistant".to_string(), before, after, created_at: "2026-10-01T09:00:00.000Z".to_string(), undone_by: None, }}fn live(value: Value) -> Current { Current::Record(Some(data(value)))}#[test]fn undoing_each_verb_writes_its_inverse() { let order = Some("position"); let create = change( "c1", Verb::Create, Some("r1"), Value::Null, json!({ "title": "Scales" }), ); assert_eq!( plan_undo(&create, &[], &live(json!({ "title": "Scales" })), order), Ok(Inverse::Delete { record_id: "r1".into() }) ); let restore = change( "c1", Verb::Restore, Some("r1"), Value::Null, json!({ "title": "Scales" }), ); assert_eq!( plan_undo(&restore, &[], &live(json!({ "title": "Scales" })), order), Ok(Inverse::Delete { record_id: "r1".into() }) ); let delete = change( "c1", Verb::Delete, Some("r1"), json!({ "title": "Scales" }), Value::Null, ); assert_eq!( plan_undo(&delete, &[], &Current::Record(None), order), Ok(Inverse::Restore { record_id: "r1".into(), data: data(json!({ "title": "Scales" })) }) ); for verb in [Verb::Update, Verb::Link] { let update = change( "c1", verb, Some("r1"), json!({ "fee": 100, "notes": null }), json!({ "fee": 200, "notes": "x" }), ); assert_eq!( plan_undo( &update, &[], &live(json!({ "title": "Scales", "fee": 200, "notes": "x" })), order ), Ok(Inverse::Patch { record_id: "r1".into(), patch: data(json!({ "fee": 100, "notes": null })), taken: vec![], }) ); } let reorder = change( "c1", Verb::Reorder, None, json!({ "a": 2.0, "b": null }), json!({ "a": 1.0, "b": 2.0 }), ); assert_eq!( plan_undo( &reorder, &[], &Current::Positions(data(json!({ "a": 1.0, "b": 2.0 }))), order ), Ok(Inverse::Reorder { positions: data(json!({ "a": 2.0, "b": null })) }) );}#[test]fn an_inverse_names_the_verb_its_own_change_records() { assert_eq!( Inverse::Delete { record_id: "r".into() } .verb(), Verb::Delete ); assert_eq!( Inverse::Restore { record_id: "r".into(), data: Data::new() } .verb(), Verb::Restore ); assert_eq!( Inverse::Patch { record_id: "r".into(), patch: Data::new(), taken: vec![], } .verb(), Verb::Update ); assert_eq!( Inverse::Reorder { positions: Data::new() } .verb(), Verb::Reorder );}/// RULE: A move is undone only by the cross-database coordinator, because an/// inline inverse would recreate a second record or leave its tombstone behind.#[test]fn a_move_never_plans_an_inline_undo() { for verb in [Verb::Move, Verb::MoveIn] { let moved = change( "move-1", verb, Some("r1"), json!({ "title": "Scales" }), json!({ "title": "Scales" }), ); assert_eq!( plan_undo(&moved, &[], &live(json!({ "title": "Scales" })), None), Err(RecordError::MoveUndoNeedsCoordinator) ); }}/// RULE: A change is undone at most once; a second undo is refused with a plain reason.#[test]fn a_change_is_undone_once() { let mut update = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); update.undone_by = Some("c2".into()); let error = plan_undo(&update, &[], &live(json!({ "fee": 100 })), None).unwrap_err(); assert_eq!(error, RecordError::AlreadyUndone); assert_eq!(error.to_string(), "this change was already undone");}/// RULE: An undo is refused when a later change touched the same field of the same record, so it never overwrites the later edit.#[test]fn a_later_change_to_the_same_field_refuses_the_undo() { let first = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); let second = change( "c2", Verb::Update, Some("r1"), json!({ "fee": 200 }), json!({ "fee": 300 }), ); assert!(matches!( plan_undo(&first, &[second], &live(json!({ "fee": 300 })), None), Err(RecordError::ChangedSince { .. }) ));}#[test]fn a_later_change_to_another_field_or_record_does_not() { let first = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); let other_field = change( "c2", Verb::Update, Some("r1"), json!({ "notes": null }), json!({ "notes": "x" }), ); let other_record = change( "c3", Verb::Update, Some("r2"), json!({ "fee": 1 }), json!({ "fee": 2 }), ); assert_eq!( plan_undo( &first, &[other_field, other_record], &live(json!({ "fee": 200, "notes": "x" })), None ), Ok(Inverse::Patch { record_id: "r1".into(), patch: data(json!({ "fee": 100 })), taken: vec![], }) );}#[test]fn a_later_whole_record_change_touches_every_field() { let first = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); let deleted = change( "c2", Verb::Delete, Some("r1"), json!({ "fee": 200 }), Value::Null, ); assert!(plan_undo(&first, &[deleted], &Current::Record(None), None).is_err()); // And the create itself cannot be undone once the record was edited. let create = change( "c0", Verb::Create, Some("r1"), Value::Null, json!({ "fee": 100 }), ); assert!(plan_undo(&create, &[first], &live(json!({ "fee": 200 })), None).is_err());}#[test]fn a_later_change_that_was_itself_undone_cancels_out() { let first = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); let mut second = change( "c2", Verb::Update, Some("r1"), json!({ "fee": 200 }), json!({ "fee": 300 }), ); second.undone_by = Some("c3".into()); let undo_of_second = change( "c3", Verb::Update, Some("r1"), json!({ "fee": 300 }), json!({ "fee": 200 }), ); assert_eq!( plan_undo( &first, &[second, undo_of_second], &live(json!({ "fee": 200 })), None ), Ok(Inverse::Patch { record_id: "r1".into(), patch: data(json!({ "fee": 100 })), taken: vec![], }) );}#[test]fn a_reorder_and_an_update_of_the_order_column_collide() { let reorder = change( "c1", Verb::Reorder, None, json!({ "r1": 2.0 }), json!({ "r1": 1.0 }), ); let moved = change( "c2", Verb::Update, Some("r1"), json!({ "position": 1.0 }), json!({ "position": 5.0 }), ); assert!(plan_undo( &reorder, std::slice::from_ref(&moved), &Current::Positions(data(json!({ "r1": 5.0 }))), Some("position") ) .is_err()); // Without an order column in play, a column that happens to be called // `position` is just a field. let first = change( "c0", Verb::Reorder, None, json!({ "r2": 2.0 }), json!({ "r2": 1.0 }), ); assert!(plan_undo( &first, &[moved], &Current::Positions(data(json!({ "r2": 1.0 }))), Some("position") ) .is_ok());}/// RULE: An undo is refused when what is stored no longer matches what the change left, even if the later edit recorded no change.#[test]fn an_edit_made_outside_the_change_log_refuses_the_undo() { let update = change( "c1", Verb::Update, Some("r1"), json!({ "fee": 100 }), json!({ "fee": 200 }), ); assert!(matches!( plan_undo(&update, &[], &live(json!({ "fee": 250 })), None), Err(RecordError::ChangedSince { .. }) )); let create = change( "c1", Verb::Create, Some("r1"), Value::Null, json!({ "title": "Scales" }), ); assert!( plan_undo(&create, &[], &Current::Record(None), None).is_err(), "already gone" ); let delete = change( "c1", Verb::Delete, Some("r1"), json!({ "title": "Scales" }), Value::Null, ); assert!( plan_undo(&delete, &[], &live(json!({ "title": "Scales" })), None).is_err(), "already back" ); let reorder = change( "c1", Verb::Reorder, None, json!({ "a": 2.0 }), json!({ "a": 1.0 }), ); assert!(plan_undo( &reorder, &[], &Current::Positions(data(json!({ "a": 3.0 }))), None ) .is_err()); assert!( plan_undo(&reorder, &[], &live(json!({})), None).is_err(), "a reorder is checked against positions" );}#[test]fn a_malformed_change_is_refused_not_guessed() { let no_record = change( "c1", Verb::Update, None, json!({ "fee": 1 }), json!({ "fee": 2 }), ); assert!(matches!( plan_undo(&no_record, &[], &live(json!({ "fee": 2 })), None), Err(RecordError::Malformed(_)) )); let bad_side = change( "c1", Verb::Update, Some("r1"), json!("fee"), json!({ "fee": 2 }), ); assert!(matches!( plan_undo(&bad_side, &[], &live(json!({ "fee": 2 })), None), Err(RecordError::Malformed(_)) ));}// ── query ───────────────────────────────────────────────────────────────────#[test]fn a_query_reads_the_title_and_the_text_columns() { let table = lesson(); assert_eq!(searchable_columns(&table), vec!["title", "notes"]); let record = data(json!({ "title": "Major Scales", "notes": "Slow tempo", "level": "advanced" })); assert!(matches_query(&table, &record, "scales")); assert!(matches_query(&table, &record, "SCALES slow")); assert!(!matches_query(&table, &record, "scales fast")); assert!( !matches_query(&table, &record, "advanced"), "a choice is not text" ); assert!( matches_query(&table, &record, ""), "an empty query matches everything" );}/// RULE: No generic read answers a sealed value, a hint, a password or a digest, and no face of a built-in definition draws one: the one definition the object serves may declare a column it keeps (a secret's sealed value, a file's password), which no face draws and no read answers.#[test]fn sensitive_columns_are_never_declared_or_read() { for key in ["value_enc", "hint", "password", "refresh_token_enc", "token_hash", "token_digest", "secret_hash", "sync_token", "pdf_password"] { assert!(is_sensitive_column(key), "{key}"); } for key in ["title", "name", "username", "site", "secret_id"] { assert!(!is_sensitive_column(key), "{key}"); } for definition in crate::definitions::builtin_table_definitions() { // The one definition the object serves declares the columns it keeps // (a secret's hint and sealed value, a file's password): no face of // it draws one, and no read answers one (above). let faces = serde_json::to_string(&serde_json::json!([definition.slip, definition.tile, definition.page, definition.card, definition.parts])).unwrap(); for column in &definition.columns { // A file's password a page sends, tried and kept nowhere. if crate::definitions::is_write_only_column(&definition.id, &column.key) || !is_sensitive_column(&column.key) { continue; } assert!( !faces.contains(&format!("\"{}\"", column.key)), "{}.{} is a sensitive column a face draws", definition.id, column.key ); } }}// ── where ───────────────────────────────────────────────────────────────────fn clause(column: &str, condition: Condition) -> WhereClause { WhereClause { column: column.to_string(), condition, first_day: None, }}/// RULE: A `where` reads a value, `{values}` or `{present}` for each declared column, checked by the column's own type.#[test]fn a_where_reads_a_value_a_list_of_values_or_presence() { let table = lesson(); assert_eq!(parse_where(&table, None), Ok(Vec::new())); assert_eq!(parse_where(&table, Some(&Value::Null)), Ok(Vec::new())); assert_eq!(parse_where(&table, Some(&json!({}))), Ok(Vec::new())); let parsed = parse_where( &table, Some(&json!({ "level": "advanced", "paid": true, "fee": { "values": [100, 200] }, "notes": { "present": false }, "day": { "present": true } })), ) .expect("a where"); // serde_json's map keeps its own key order; compare as a set of entries. let mut parsed: Vec<String> = parsed.iter().map(|c| format!("{c:?}")).collect(); parsed.sort(); let mut wanted: Vec<String> = [ clause("level", Condition::Is(json!("advanced"))), clause("paid", Condition::Is(json!(true))), clause("fee", Condition::OneOf(vec![json!(100), json!(200)])), clause("notes", Condition::Present(false)), clause("day", Condition::Present(true)), ] .iter() .map(|c| format!("{c:?}")) .collect(); wanted.sort(); assert_eq!(parsed, wanted);}/// RULE: A `where` value that is a list of values is any one of them, the same as `{values}` — the shape a definition's own where says it in — and each is checked by the column's type.#[test]fn a_where_list_of_values_is_any_one_of_them() { let table = lesson(); assert_eq!( parse_where(&table, Some(&json!({ "level": ["beginner", "advanced"] }))), parse_where(&table, Some(&json!({ "level": { "values": ["beginner", "advanced"] } }))), ); assert_eq!( parse_where(&table, Some(&json!({ "level": ["advanced"] }))).unwrap(), vec![clause("level", Condition::OneOf(vec![json!("advanced")]))], ); let clause = &parse_where(&table, Some(&json!({ "level": ["beginner", "advanced"] }))).unwrap()[0]; assert!(holds(&data(json!({ "level": "advanced" })), clause, &where_zone(None))); assert!(!holds(&data(json!({ "level": "intermediate" })), clause, &where_zone(None))); assert!(matches!( parse_where(&table, Some(&json!({ "level": ["advanced", "expert"] }))), Err(RecordError::NotAChoice { .. }) ));}/// RULE: A `where` of `{not: [...]}` holds a value that is none of them, and a record holding nothing never matches it — "balance not 0" names the people something is owed between, never everyone with no money at all.#[test]fn a_where_not_holds_a_value_none_of_them_and_never_nothing() { let table = lesson(); let parsed = parse_where(&table, Some(&json!({ "fee": { "not": [0, 100] } }))).unwrap(); assert_eq!(parsed, vec![clause("fee", Condition::NoneOf(vec![json!(0), json!(100)]))]); let not = &parsed[0]; assert!(holds(&data(json!({ "fee": 250 })), not, &where_zone(None))); assert!(holds(&data(json!({ "fee": -250 })), not, &where_zone(None))); assert!(!holds(&data(json!({ "fee": 0 })), not, &where_zone(None))); assert!(!holds(&data(json!({ "fee": 100 })), not, &where_zone(None))); assert!(!holds(&data(json!({})), not, &where_zone(None)), "absent is nothing"); assert!(!holds(&data(json!({ "fee": null })), not, &where_zone(None)), "null is nothing"); // Each value is checked by the column's own type, as a write's is. assert!(matches!( parse_where(&table, Some(&json!({ "level": { "not": ["expert"] } }))), Err(RecordError::NotAChoice { .. }) )); for shape in [json!({ "fee": { "not": [] } }), json!({ "fee": { "not": 0 } })] { assert!(matches!(parse_where(&table, Some(&shape)), Err(RecordError::BadWhere { .. })), "{shape}"); }}/// RULE: A `where` of `{within_days: n}` holds a date no more than n days of 24 hours back from now, or later; a day reads as its UTC midnight, nothing never holds, and only a date column takes a whole n of 1 or more.#[test]fn a_where_within_days_holds_a_date_no_more_than_so_many_days_back() { let table = lesson(); let parsed = parse_where(&table, Some(&json!({ "day": { "within_days": 7 } }))).unwrap(); assert_eq!(parsed, vec![clause("day", Condition::WithinDays(DayWindow::Within(7)))]); let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T12:00:00Z").unwrap().with_timezone(&chrono::Utc); let within = |value: Value| within_days(&value, DayWindow::Within(7), now); assert!(within(json!("2026-10-23T11:00:00.000Z"))); assert!(within(json!("2026-10-16T12:00:00.000Z")), "exactly seven days back"); assert!(!within(json!("2026-10-16T11:59:59.000Z"))); assert!(within(json!("2026-10-23T08:00:00+05:30")), "an offset reads as its instant"); assert!(within(json!("2026-10-30T09:00:00.000Z")), "later is within"); assert!(within(json!("2026-10-17"))); assert!(!within(json!("2026-10-16")), "a day is its UTC midnight"); assert!(!within(json!(null)) && !within(json!("")) && !within(json!("soon"))); assert!(!holds(&data(json!({})), &parsed[0], &where_zone(None))); let refused = |shape: Value| parse_where(&table, Some(&shape)).expect_err("refused"); for (shape, reason) in [ (json!({ "day": { "within_days": 0 } }), WhereRefusal::WithinDaysRange { found: describe(&json!(0)) }), (json!({ "day": { "within_days": 1.5 } }), WhereRefusal::WithinDaysRange { found: describe(&json!(1.5)) }), (json!({ "day": { "within_days": "7" } }), WhereRefusal::WithinDaysRange { found: describe(&json!("7")) }), (json!({ "title": { "within_days": 7 } }), WhereRefusal::WithinDaysOnlyDate), ] { let column = shape.as_object().unwrap().keys().next().unwrap().clone(); assert_eq!(refused(shape), RecordError::BadWhere { column, reason }); }}/// RULE: `{at_most: n}` and `{at_least: n}` hold a number no more, or no less, than n (whole or not); nothing, a text or a list is in no bound, and only a number column takes a number n.#[test]fn a_where_bound_holds_a_number_on_its_side() { let table = lesson(); let most = parse_where(&table, Some(&json!({ "minutes": { "at_most": 30 } }))).unwrap(); assert_eq!(most, vec![clause("minutes", Condition::Bound(NumberBound::AtMost(30.0)))]); let least = parse_where(&table, Some(&json!({ "minutes": { "at_least": 3.5 } }))).unwrap(); assert_eq!(least, vec![clause("minutes", Condition::Bound(NumberBound::AtLeast(3.5)))]); let held = |clauses: &[WhereClause], minutes: Value| holds(&data(json!({ "minutes": minutes })), &clauses[0], &where_zone(None)); assert!(held(&most, json!(30)) && held(&most, json!(12.5)) && !held(&most, json!(31))); assert!(held(&least, json!(4)) && held(&least, json!(3.5)) && !held(&least, json!(3))); assert!(!held(&most, json!(null)) && !held(&most, json!("")) && !held(&most, json!("20")) && !held(&most, json!([10]))); assert!(!holds(&data(json!({})), &most[0], &where_zone(None)), "a record holding nothing is in no bound"); let refused = |shape: Value| parse_where(&table, Some(&shape)).expect_err("refused"); for (shape, reason) in [ (json!({ "minutes": { "at_most": "30" } }), WhereRefusal::BoundNumber { found: describe(&json!("30")) }), (json!({ "minutes": { "at_least": null } }), WhereRefusal::BoundNumber { found: describe(&json!(null)) }), (json!({ "day": { "at_most": 30 } }), WhereRefusal::BoundOnlyNumber), (json!({ "title": { "at_least": 1 } }), WhereRefusal::BoundOnlyNumber), ] { let column = shape.as_object().unwrap().keys().next().unwrap().clone(); assert_eq!(refused(shape), RecordError::BadWhere { column, reason }); }}/// RULE: `{on: "today"}` holds a date on today and `{on: "this_day"}` one on today's month and day in an earlier year (a journal's Today and On this day); a bare day is that day, a moment is read as its day in the device's zone, so 00:30 on the 12th in Kolkata is the 12th though it is the 11th in UTC; nothing never holds; only a date column takes `on`, and only those two words.#[test]fn a_where_on_holds_today_or_this_day_in_earlier_years() { let table = lesson(); assert_eq!(parse_where(&table, Some(&json!({ "day": { "on": "today" } }))).unwrap(), vec![clause("day", Condition::On(DayOn::Today))]); assert_eq!(parse_where(&table, Some(&json!({ "day": { "on": "this_day" } }))).unwrap(), vec![clause("day", Condition::On(DayOn::ThisDay))]); let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 12).unwrap(); let kolkata = chrono::FixedOffset::east_opt(19_800).unwrap(); let on = |value: Value, day: DayOn| on_day(&value, day, today, &kolkata); assert!(on(json!("2026-11-12"), DayOn::Today) && !on(json!("2026-11-11"), DayOn::Today) && !on(json!("2025-11-12"), DayOn::Today)); assert!(on(json!("2026-11-11T19:00:00Z"), DayOn::Today), "00:30 on the 12th in Kolkata is today there, though the 11th in UTC"); assert!(!on(json!("2026-11-11T18:00:00Z"), DayOn::Today), "23:30 on the 11th in Kolkata is yesterday there"); assert!(!on(json!("2026-11-12T19:00:00Z"), DayOn::Today), "00:30 on the 13th in Kolkata is tomorrow there"); assert!(on(json!("2025-11-12"), DayOn::ThisDay) && on(json!("2019-11-12T08:00:00Z"), DayOn::ThisDay)); assert!(!on(json!("2026-11-12"), DayOn::ThisDay), "today is not an earlier year"); assert!(!on(json!("2025-11-13"), DayOn::ThisDay) && !on(json!("2025-10-12"), DayOn::ThisDay)); let leap = chrono::NaiveDate::from_ymd_opt(2027, 2, 28).unwrap(); assert!(!on_day(&json!("2024-02-29"), DayOn::ThisDay, leap, &kolkata), "a 29 February is kept only on a 29 February"); for nothing in [json!(null), json!(""), json!("soon"), json!(12), json!(["2025-11-12"])] { assert!(!on(nothing.clone(), DayOn::Today) && !on(nothing, DayOn::ThisDay)); } let refused = |shape: Value| parse_where(&table, Some(&shape)).expect_err("refused"); for (shape, reason) in [ (json!({ "day": { "on": "yesterday" } }), WhereRefusal::OnWord { found: describe(&json!("yesterday")) }), (json!({ "day": { "on": true } }), WhereRefusal::OnWord { found: describe(&json!(true)) }), (json!({ "title": { "on": "today" } }), WhereRefusal::OnOnlyDate), (json!({ "minutes": { "on": "today" } }), WhereRefusal::OnOnlyDate), ] { let column = shape.as_object().unwrap().keys().next().unwrap().clone(); assert_eq!(refused(shape), RecordError::BadWhere { column, reason }); }}/// RULE (Cotton Trips, 12 Nov 2026): `{on: "from_today"}` holds today and every day after it, `{on: "before_today"}` every day before today: a trip's Upcoming keeps one that ends today or later, its Past one that ended before today. A moment is read as its day in the device's zone; nothing never holds.#[test]fn a_where_on_holds_from_today_or_before_today() { let table = lesson(); assert_eq!(parse_where(&table, Some(&json!({ "day": { "on": "from_today" } }))).unwrap(), vec![clause("day", Condition::On(DayOn::FromToday))]); assert_eq!(parse_where(&table, Some(&json!({ "day": { "on": "before_today" } }))).unwrap(), vec![clause("day", Condition::On(DayOn::BeforeToday))]); let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 12).unwrap(); let kolkata = chrono::FixedOffset::east_opt(19_800).unwrap(); let on = |value: Value, day: DayOn| on_day(&value, day, today, &kolkata); assert!(on(json!("2026-11-12"), DayOn::FromToday) && on(json!("2027-01-02"), DayOn::FromToday) && !on(json!("2026-11-11"), DayOn::FromToday)); assert!(on(json!("2026-11-11"), DayOn::BeforeToday) && !on(json!("2026-11-12"), DayOn::BeforeToday)); assert!(on(json!("2026-11-11T19:00:00Z"), DayOn::FromToday), "00:30 on the 12th in Kolkata is today there"); assert!(!on(Value::Null, DayOn::FromToday) && !on(Value::Null, DayOn::BeforeToday));}/// RULE (Cotton Trips, 13 Nov 2026): a day named against today over a range's last day reads the range's first day where the last holds nothing (the column whose `until` it is): a trip given only the day it starts is a trip of that one day, in Upcoming until it has passed and in Past after.#[test]fn a_where_on_a_ranges_last_day_reads_its_first_where_it_holds_none() { // An album runs from its first day until its last (Trips, the first such table, retired 22 Nov 2026). let trip = crate::kit::table("album").expect("the album table"); let clauses = parse_where(&trip, Some(&json!({ "ends_at": { "on": "from_today" } }))).unwrap(); assert_eq!(clauses[0].first_day.as_deref(), Some("starts_at")); assert_eq!(parse_where(&trip, Some(&json!({ "starts_at": { "on": "from_today" } }))).unwrap()[0].first_day, None); let zone = Zone { tz: chrono_tz::Asia::Kolkata, today: chrono::NaiveDate::from_ymd_opt(2026, 11, 13).unwrap() }; let data = |value: Value| value.as_object().cloned().unwrap(); let ahead = &clauses[0]; assert!(holds(&data(json!({ "starts_at": "2026-11-16" })), ahead, &zone)); assert!(!holds(&data(json!({ "starts_at": "2026-11-12" })), ahead, &zone)); assert!(!holds(&data(json!({ "starts_at": "2026-11-16", "ends_at": "2026-11-12" })), ahead, &zone), "a last day it holds is read"); assert!(!holds(&data(json!({})), ahead, &zone), "an album with no day is in neither");}/// RULE: `{before_days: n}` holds a date more than n days back and never one not kept ("not seen in two weeks"); `{ahead_days: n}` holds a date from yesterday to n days ahead, so today's day holds ("ends in the next two weeks"); both take a whole n of 1 or more on a date column, as within_days does.#[test]fn a_where_before_or_ahead_days_holds_a_date_in_its_window() { let table = lesson(); let before = parse_where(&table, Some(&json!({ "day": { "before_days": 14 } }))).unwrap(); assert_eq!(before, vec![clause("day", Condition::WithinDays(DayWindow::Before(14)))]); let ahead = parse_where(&table, Some(&json!({ "day": { "ahead_days": 14 } }))).unwrap(); assert_eq!(ahead, vec![clause("day", Condition::WithinDays(DayWindow::Ahead(14)))]); let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T12:00:00Z").unwrap().with_timezone(&chrono::Utc); let back = |value: Value| within_days(&value, DayWindow::Before(14), now); assert!(back(json!("2026-10-01")) && !back(json!("2026-10-20")) && !back(json!(null)) && !back(json!(""))); let soon = |value: Value| within_days(&value, DayWindow::Ahead(14), now); assert!(soon(json!("2026-10-23")), "today's day is its midnight, still ahead enough"); assert!(soon(json!("2026-11-06")) && !soon(json!("2026-11-07T12:00:01Z"))); assert!(!soon(json!("2026-10-21")) && !soon(json!(null))); for shape in [json!({ "day": { "before_days": 0 } }), json!({ "title": { "ahead_days": 7 } })] { assert!(matches!(parse_where(&table, Some(&shape)), Err(RecordError::BadWhere { .. })), "{shape}"); }}/// RULE: A `where` naming an unknown column, a value its column cannot hold, or a shape it does not spell is refused, never ignored.#[test]fn a_where_that_cannot_mean_what_it_says_is_refused() { let table = lesson(); let refused = |value: Value| parse_where(&table, Some(&value)).expect_err("refused"); assert_eq!( refused(json!({ "colour": "red" })), RecordError::UnknownColumn { plural: "Lessons".into(), column: "colour".into() } ); assert!(matches!( refused(json!({ "level": "expert" })), RecordError::NotAChoice { .. } )); assert!(matches!( refused(json!({ "fee": { "values": [1.5] } })), RecordError::NotWholeAmount { .. } )); for shape in [ json!({ "level": null }), json!({ "level": [] }), json!({ "level": [["advanced"]] }), json!({ "level": { "values": [] } }), json!({ "level": { "values": "advanced" } }), json!({ "level": { "values": [null] } }), json!({ "level": { "present": "yes" } }), json!({ "level": { "is": "advanced" } }), json!({ "level": { "values": ["advanced"], "present": true } }), json!("level"), ] { assert!( matches!(refused(shape.clone()), RecordError::BadWhere { .. }), "{shape}" ); }}// ── attachments ─────────────────────────────────────────────────────────────fn builtin(id: &str) -> TableDefinition { crate::definitions::builtin_table_definitions() .iter().cloned() .find(|definition| definition.id == id) .expect("a built-in")}/// RULE: A patch carries a record's pictures only on a table whose engine keeps them, as a list of `{kind, id, caption?}` or null.#[test]fn a_patch_carries_pictures_only_where_the_engine_keeps_them() { for id in ATTACHMENT_TABLES { let Some(table) = crate::definitions::builtin_table_definition(id).cloned() else { continue }; assert!(carries_attachments(&table), "{id}"); for value in [ json!([]), Value::Null, json!([{ "kind": "photo", "id": "photo:a" }, { "kind": "document", "id": "d", "caption": "the log" }]), json!([{ "kind": "photo", "id": "photo:a", "caption": null }]), ] { validate_patch(&table, &json!({ ATTACHMENTS_KEY: value })).expect("pictures"); } for value in [ json!("photo:a"), json!([{ "kind": "photo" }]), json!([{ "kind": "photo", "id": "photo:a", "caption": 3 }]), json!(["photo:a"]), ] { assert!( matches!( validate_patch(&table, &json!({ ATTACHMENTS_KEY: value.clone() })), Err(RecordError::WrongType { .. }) ), "{id}: {value}" ); } } // A table whose engine keeps no pictures, and a table a person defined. for table in [builtin("todo"), lesson()] { assert!(!carries_attachments(&table)); assert!(matches!( validate_patch(&table, &json!({ ATTACHMENTS_KEY: [] })), Err(RecordError::UnknownColumn { .. }) )); } // A create never carries them: they are filed on a record that exists. assert!(matches!( validate_create(&builtin("note"), &json!({ "title": "t", ATTACHMENTS_KEY: [] })), Err(RecordError::UnknownColumn { .. }) ));}/// RULE: Secret Copy's metadata is one increment and one exact timestamp, and a consumed once-only row cannot be reset, recopied or undone.#[test]fn reveal_metadata_is_monotonic_and_an_exact_instant() { let definition = TableDefinition::from_json(include_str!("../../test-fixtures/code_credential.json")).unwrap(); let patch = data(json!({"reveal_count":1,"last_revealed":"2026-10-02T09:00:00Z"})); assert!(validate_patch(&definition, &Value::Object(patch.clone())).is_ok()); assert!(validate_reveal_patch(&definition, &Data::new(), &patch).is_ok()); for bad in [json!({"reveal_count":0}), json!({"reveal_count":1}), json!({"reveal_count":1,"last_revealed":"2026-10-02"})] { assert!(validate_reveal_patch(&definition, &Data::new(), &data(bad)).is_err()); } for next in [patch.clone(), data(json!({"reveal_count":0})), data(json!({"last_revealed":null}))] { assert!(validate_reveal_patch(&definition, &patch, &next).is_err()); } let mut repeatable = definition.clone(); repeatable.columns.iter_mut().find(|c| c.key == "token").unwrap().reveal.as_mut().unwrap().once = false; assert!(validate_reveal_patch(&repeatable, &patch, &data(json!({"reveal_count":2,"last_revealed":"2026-10-02T09:01:00Z"}))).is_ok());}// ── where keys an engine answers ────────────────────────────────────────────/// RULE: A `where` key an engine answers is no column of its table, is taken only on that built-in and only as one record id, and every other table refuses it as an unknown column.#[test]fn an_engine_where_key_is_one_id_on_its_own_builtin_alone() { for (table, key) in ENGINE_WHERE_KEYS { let definition = builtin(table); assert!(definition.column(key).is_none(), "{table}.{key} is a column, not an engine key"); assert!(is_engine_where_key(&definition, key), "{table}.{key}"); } let photo = builtin("photo"); assert_eq!( parse_where(&photo, Some(&json!({ "addable_to": " album:trip:2026-09-10 " }))), Ok(vec![WhereClause { column: "addable_to".to_string(), condition: Condition::Is(json!("album:trip:2026-09-10")), first_day: None, }]) ); for wanted in [json!({ "values": ["album:trip:2026-09-10"] }), json!(""), json!(3), Value::Null] { let refused = parse_where(&photo, Some(&json!({ "addable_to": wanted.clone() }))); assert!( matches!(refused, Err(RecordError::BadWhere { ref column, .. }) if column == "addable_to"), "{wanted}: {refused:?}" ); } assert!(matches!( parse_where(&builtin("video"), Some(&json!({ "addable_to": "album:trip:2026-09-10" }))), Err(RecordError::UnknownColumn { .. }) )); assert!(matches!( parse_where(&lesson(), Some(&json!({ "addable_to": "x" }))), Err(RecordError::UnknownColumn { .. }) ));}// ── what a write changed beside the record ──────────────────────────────────/// RULE: What a write changed beside its record is an `@` key no column can be, said as `{was, now}` for each key that moved and nothing for one that did not, and read back from whichever side of the change holds it.#[test]fn what_moved_beside_a_record_is_said_as_was_and_now() { assert!(is_beside("@album_state") && !is_beside("album_id") && !is_beside("state")); let moved = beside_moved( &data(json!({ "@album_state": "open", "@album_cover": "p1" })), &data(json!({ "@album_state": "kept", "@album_cover": "p1" })), ); assert_eq!( Value::Object(moved), json!({ "@album_state": { "was": "open", "now": "kept" } }) ); assert!(beside_moved(&data(json!({ "title": "a" })), &data(json!({ "title": "b" }))).is_empty()); let create = change( "c1", Verb::Create, Some("r1"), Value::Null, json!({ "title": "Scales", "@album_state": { "was": "open", "now": "kept" } }), ); assert_eq!( Value::Object(beside_of(&create)), json!({ "@album_state": { "was": "open", "now": "kept" } }) ); assert_eq!(record_part(&create.after), json!({ "title": "Scales" })); assert_eq!(record_part(&Value::Null), Value::Null); let delete = change( "c2", Verb::Delete, Some("r1"), json!({ "title": "Scales", "@album_cover": { "was": "p1", "now": "p2" } }), Value::Null, ); assert_eq!( Value::Object(beside_of(&delete)), json!({ "@album_cover": { "was": "p1", "now": "p2" } }) );}/// RULE: An undo compares the record on its columns alone — what moved beside it never makes the record read as changed since, and never enters the patch or the data put back.#[test]fn an_undo_plans_on_the_record_alone_not_what_moved_beside_it() { let beside = json!({ "was": "derived", "now": "user" }); let create = change( "c1", Verb::Create, Some("r1"), Value::Null, json!({ "title": "Scales", "@album_state": beside }), ); assert_eq!( plan_undo(&create, &[], &live(json!({ "title": "Scales" })), None), Ok(Inverse::Delete { record_id: "r1".into() }) ); let update = change( "c2", Verb::Update, Some("r1"), json!({ "title": "Scales" }), json!({ "title": "Arpeggios", "@title_by": beside }), ); assert_eq!( plan_undo(&update, &[], &live(json!({ "title": "Arpeggios" })), None), Ok(Inverse::Patch { record_id: "r1".into(), patch: data(json!({ "title": "Scales" })), taken: vec![], }) ); let delete = change( "c3", Verb::Delete, Some("r1"), json!({ "title": "Scales", "@album_state": beside }), Value::Null, ); assert_eq!( plan_undo(&delete, &[], &Current::Record(None), None), Ok(Inverse::Restore { record_id: "r1".into(), data: data(json!({ "title": "Scales" })), }) );}/// RULE: A record read from memory holds a `where` entry exactly as SQL would narrow it — the same value (numbers by worth), any one of the values, or something / nothing, where absent, null and blank text are nothing and a list is never one value.#[test]fn a_record_held_in_memory_holds_a_where_as_sql_would_narrow_it() { let data: Data = serde_json::from_value(json!({ "state": "queued", "turns": 2, "cost": 1.0, "blank": " ", "none": null, "tags": ["a", "b"], })) .unwrap(); let cases: Vec<(WhereClause, bool)> = vec![ (clause("state", Condition::Is(json!("queued"))), true), (clause("state", Condition::Is(json!("done"))), false), (clause("state", Condition::Is(json!("Queued"))), false), (clause("turns", Condition::Is(json!(2.0))), true), (clause("cost", Condition::Is(json!(1))), true), (clause("turns", Condition::Is(json!("2"))), false), (clause("state", Condition::OneOf(vec![json!("done"), json!("queued")])), true), (clause("state", Condition::OneOf(vec![json!("done"), json!("failed")])), false), (clause("missing", Condition::OneOf(vec![json!("x")])), false), (clause("state", Condition::Present(true)), true), (clause("state", Condition::Present(false)), false), (clause("missing", Condition::Present(false)), true), (clause("none", Condition::Present(false)), true), (clause("blank", Condition::Present(false)), true), (clause("blank", Condition::Present(true)), false), (clause("turns", Condition::Present(true)), true), (clause("tags", Condition::Present(true)), true), (clause("tags", Condition::Is(json!("a"))), false), (clause("tags", Condition::OneOf(vec![json!("a")])), false), (clause("missing", Condition::Is(json!("x"))), false), ]; for (clause, held) in cases { assert_eq!(holds(&data, &clause, &where_zone(None)), held, "{clause:?}"); }}/// RULE: A column the data leaves out (or sets null) takes its default on create, a value given keeps, and a patch never applies a default — so a one-line row rests in its table's resting state and a clear stays a clear.#[test]fn a_create_fills_a_column_default_and_a_patch_never_does() { let mut table = lesson(); for column in table.columns.iter_mut() { column.default = match column.key.as_str() { "level" => Some(json!("beginner")), "paid" => Some(json!(false)), _ => None, }; } table.validate().expect("defaults of their own type"); let clean = validate_create(&table, &json!({ "title": "Scales", "level": null })).expect("fits"); assert_eq!( clean, data(json!({ "title": "Scales", "level": "beginner", "paid": false })) ); let given = validate_create(&table, &json!({ "title": "Scales", "level": "advanced", "paid": true })) .expect("fits"); assert_eq!(given["level"], json!("advanced")); assert_eq!(given["paid"], json!(true)); let patch = validate_patch(&table, &json!({ "level": null })).expect("a clear"); assert_eq!(patch, data(json!({ "level": null })));}/// RULE: A url column takes an absolute http(s) address with a host and nothing else — not a bare domain, another scheme, padding or a non-string — because a tap on it opens a browser and nothing else should.#[test]fn a_url_column_takes_only_a_web_address() { let column = Column { key: "site".into(), column_type: ColumnType::Url, ..column("notes") }; for ok in ["https://example.com", "http://example.com/path?q=1#x", "https://sub.example.co.uk:8443/"] { check_value(&column, &json!(ok)).unwrap_or_else(|e| panic!("{ok}: {e}")); } for bad in [ json!("example.com"), json!("ftp://example.com"), json!("mailto:a@b.c"), json!("javascript:alert(1)"), json!(" https://example.com"), json!("https://"), json!(""), json!(1), ] { assert!(check_value(&column, &bad).is_err(), "{bad}"); }}// ── tile summary ───────────────────────────────────────────────────────────/// RULE: a group head's figures (ruling 09:15 IST 17 Oct) are a tile's, worked out over that group's rows alone, and said as lines — the amount in its currency, then its label — so Months' "in" for a period never counts another period's rows, and a group with nothing to say says no line.#[test]fn a_group_head_says_its_figures_over_its_own_rows() { let mut definition = lesson(); definition.columns.push(crate::definitions::Column { key: "currency".into(), column_type: ColumnType::Text, ..column("notes") }); definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().column_type = ColumnType::Amount; definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().currency = Some("currency".into()); definition.group = Some(serde_json::from_value(json!({"column": "day", "summary": [ {"op": "sum", "column": "fee", "where": {"paid": true}, "label": "paid"}, {"op": "count", "label": "lessons"} ]})).unwrap()); definition.validate().expect("a group head over declared columns validates"); let rows = vec![ data(json!({ "title": "a", "day": "2026-10-09", "paid": true, "fee": 1000, "currency": "INR" })), data(json!({ "title": "b", "day": "2026-10-04", "paid": true, "fee": 2500, "currency": "INR" })), data(json!({ "title": "c", "day": "2026-10-09", "paid": true, "fee": 500, "currency": "INR" })), data(json!({ "title": "d", "day": "2026-10-04", "paid": false, "fee": 700, "currency": "INR" })), ]; let heads = group_heads(&definition, &rows, crate::records::page::Words::shipped(), &where_zone(None)).expect("heads"); let rupees = |minor| crate::records::amount::amount(minor, Some("INR"), crate::records::amount::MoneyWords::shipped()).said(crate::records::amount::MoneyForm::Money, crate::records::amount::MoneyWords::shipped()); assert_eq!(heads.iter().map(|head| head.value.clone()).collect::<Vec<_>>(), [json!("2026-10-09"), json!("2026-10-04")]); assert_eq!(heads[0].lines, [format!("{} paid", rupees(1500)), "2 lessons".to_string()]); assert_eq!(heads[1].lines, [format!("{} paid", rupees(2500)), "2 lessons".to_string()]); let mut unlabelled = definition.clone(); unlabelled.group.as_mut().unwrap().summary[1].label = None; assert!(unlabelled.validate().is_err(), "a head's line says what its figure is"); let mut plain = definition; plain.group.as_mut().unwrap().summary.clear(); assert!(group_heads(&plain, &rows, crate::records::page::Words::shipped(), &where_zone(None)).unwrap().is_empty(), "a group that says no figures has no heads");}/// RULE: a tile figure is computed once, here — a count over the rows its where keeps, a sum that stays whole, a min that skips blanks and reads a date as written, and an amount sum that says "mixed" rather than add two currencies together.#[test]fn a_tile_summary_counts_sums_and_picks_over_the_rows_its_where_keeps() { let mut definition = lesson(); definition.tile = crate::definitions::TileLayout { face: crate::definitions::TileFace::SlipList, summary: vec![ crate::definitions::TileSummary { op: SummaryOp::Count, column: None, where_: Some(crate::definitions::OrderedMap(vec![("paid".into(), json!(true))])), label: Some("paid".into()), }, crate::definitions::TileSummary { op: SummaryOp::Sum, column: Some("fee".into()), where_: Some(crate::definitions::OrderedMap(vec![("paid".into(), json!(false))])), label: Some("owed".into()), }, crate::definitions::TileSummary { op: SummaryOp::Min, column: Some("day".into()), where_: None, label: Some("next".into()), }, crate::definitions::TileSummary { op: SummaryOp::Max, column: Some("minutes".into()), where_: None, label: None, }, ], current: None, sparkline: None, chart: None, }; definition.validate().expect("a summary over declared columns validates"); let rows = vec![ data(json!({ "title": "a", "paid": true, "fee": 1000, "day": "2026-10-09", "minutes": 45 })), data(json!({ "title": "b", "paid": false, "fee": 2500, "day": "2026-10-04", "minutes": 60.5 })), data(json!({ "title": "c", "paid": false, "fee": 500 })), ]; let figures = summarize(&definition, &rows, crate::records::page::Words::shipped(), &where_zone(None)).expect("summarizes"); let values: Vec<Value> = figures.iter().map(|f| f.value.clone()).collect(); assert_eq!(values, vec![json!(1), json!(3000), json!("2026-10-04"), json!(60.5)]); assert_eq!(figures[1].label.as_deref(), Some("owed")); assert_eq!(figures[1].currency, None, "an amount column with no currency says none"); assert_eq!(serde_json::to_value(&figures[2]).unwrap(), json!({ "op": "min", "column": "day", "label": "next", "value": "2026-10-04", "words": "Sun 4 Oct next" })); // Each figure carries its words, so a face draws them and spells nothing. let words: Vec<&str> = figures.iter().map(|f| f.words.as_deref().unwrap_or_default()).collect(); assert_eq!(words, vec!["1 paid", "30 owed", "Sun 4 Oct next", "60.5"]); // A currency column read per row: one shared currency rides along, // two make the sum null and the currency "mixed". let mut priced = lesson(); priced.columns.push(crate::definitions::Column { key: "currency".into(), column_type: ColumnType::Text, ..column("notes") }); priced.columns.iter_mut().find(|c| c.key == "fee").unwrap().currency = Some("currency".into()); priced.tile.summary = vec![crate::definitions::TileSummary { op: SummaryOp::Sum, column: Some("fee".into()), where_: None, label: None }]; let same = vec![ data(json!({ "title": "a", "fee": 100, "currency": "GBP" })), data(json!({ "title": "b", "fee": 200, "currency": "GBP" })), ]; let figure = &summarize(&priced, &same, crate::records::page::Words::shipped(), &where_zone(None)).unwrap()[0]; assert_eq!((figure.value.clone(), figure.currency.as_deref()), (json!(300), Some("GBP"))); let mixed = vec![ data(json!({ "title": "a", "fee": 100, "currency": "GBP" })), data(json!({ "title": "b", "fee": 200, "currency": "USD" })), ]; let figure = &summarize(&priced, &mixed, crate::records::page::Words::shipped(), &where_zone(None)).unwrap()[0]; assert_eq!((figure.value.clone(), figure.currency.as_deref()), (Value::Null, Some("mixed"))); assert_eq!(figure.words.as_deref(), Some("mixed currencies")); assert_eq!(summarize(&priced, &[], crate::records::page::Words::shipped(), &where_zone(None)).unwrap()[0].value, json!(0), "a sum over nothing is zero");}/// RULE: A user table's date column read as an instant (`ago` or `calendar-datetime`) takes an RFC 3339 instant and a plain one refuses it, because a reading of a time of day needs the time and a bare date column must stay a day.#[test]fn a_date_read_as_an_instant_takes_one() { let definition = TableDefinition::from_json( &json!({ "id": "probe", "name": "Probe", "plural": "Probes", "picture": null, "builtin": false, "engine": null, "columns": [ { "key": "name", "type": "text", "required": true }, { "key": "day", "type": "date" }, { "key": "seen", "type": "date", "format": "ago" }, { "key": "due", "type": "date", "format": "calendar-datetime" } ], "title": "name", "slip": { "title": "name", "subtitle": null, "trailing": "due", "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [ { "heading": null, "columns": ["name", "day", "seen", "due"] } ], "instructions": "A synthetic probe." }) .to_string(), ) .unwrap_or_else(|e| panic!("a valid synthetic definition: {e}")); let column = |key: &str| definition.columns.iter().find(|c| c.key == key).unwrap(); let instant = json!("2026-10-15T01:30:00Z"); assert!(check_value_in(&definition, column("seen"), &instant).is_ok()); assert!(check_value_in(&definition, column("due"), &instant).is_ok()); assert!(check_value_in(&definition, column("due"), &json!("2026-10-15")).is_ok()); assert!(check_value_in(&definition, column("day"), &instant).is_err());}/// RULE: A definition-owned readonly fact cannot be forged through generic create or update; only its producer may fill it through the receipt writer.#[test]fn definition_owned_readonly_facts_refuse_authored_values() { let mut definition = lesson(); definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().readonly = Some(true); assert!(validate_create(&definition, &json!({"title":"Test","fee":1})).is_err()); assert!(validate_patch(&definition, &json!({"fee":1})).is_err()); assert!(validate_patch(&definition, &json!({"fee":null})).is_err()); assert!(validate_patch(&definition, &json!({"notes":"Owner note"})).is_ok());}/// RULE: An update that sends a readonly column with the value the row already holds is not a write to it and passes; a readonly column with a changed value is refused naming the column.#[test]fn unchanged_readonly_values_in_a_patch_are_not_writes() { let mut definition = lesson(); definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().readonly = Some(true); let stored: Data = json!({"title":"Test","fee":1}).as_object().unwrap().clone(); let unchanged = without_unchanged_readonly(&definition, &json!({"fee":1,"notes":"Owner note"}), &stored); assert_eq!(unchanged, json!({"notes":"Owner note"})); assert!(validate_patch(&definition, &unchanged).is_ok()); let changed = without_unchanged_readonly(&definition, &json!({"fee":2,"notes":"Owner note"}), &stored); assert_eq!(changed, json!({"fee":2,"notes":"Owner note"})); assert!(matches!(validate_patch(&definition, &changed), Err(RecordError::Readonly { column }) if column == "fee")); // A readonly column the row never held is unchanged only when the patch sends null. let absent: Data = json!({"title":"Test"}).as_object().unwrap().clone(); assert_eq!(without_unchanged_readonly(&definition, &json!({"fee":null}), &absent), json!({})); assert_eq!(without_unchanged_readonly(&definition, &json!({"fee":1}), &absent), json!({"fee":1}));}/// RULE: Only the table's authenticated producer may author readonly facts where it declares one; owner edits, the app and other identities must not forge producer state.#[test]fn declared_producer_alone_authors_readonly_facts() { let mut definition = lesson(); definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().readonly = Some(true); definition = TableDefinition::from_json(&{ let mut raw = serde_json::to_value(&definition).unwrap(); raw["producer"] = json!({"token_id":"synthetic-fold-token"}); raw.to_string() }).unwrap(); for author in [Author::Other, Author::App, Author::Token("other-token"), Author::Token(""), Author::Token("synthetic-fold-token")] { let allowed = author == Author::Token("synthetic-fold-token"); assert_eq!(validate_create_as(&definition, &json!({"title":"Test","fee":1}), author).is_ok(), allowed, "{author:?} creates"); for value in [json!(2), json!(null)] { assert_eq!(validate_patch_as(&definition, &json!({"fee":value}), author).is_ok(), allowed, "{author:?} patches"); } } assert!(validate_patch_as(&definition, &json!({"fee":"invalid amount"}), Author::Token("synthetic-fold-token")).is_err()); assert!(validate_patch_as(&definition, &json!({"invented":1}), Author::Token("synthetic-fold-token")).is_err()); assert!(validate_patch(&definition, &json!({"fee":2})).is_err(), "Undo and owner validation carry no producer identity");}/// RULE: A readonly column on a table with no engine and no producer is the app's to fill as it makes the record: the app's create may name it, while a token's or anyone else's create, and every patch (the app's too), is refused naming the column with the readonly line.#[test]fn the_app_fills_a_readonly_fact_at_create_and_nobody_edits_it() { let mut definition = lesson(); definition.columns.iter_mut().find(|c| c.key == "fee").unwrap().readonly = Some(true); assert!(definition.producer.is_none() && !definition.has_engine()); let made = validate_create_as(&definition, &json!({"title":"Test","fee":1}), Author::App).expect("the app makes the record whole"); assert_eq!(made["fee"], json!(1)); for author in [Author::Other, Author::Token("synthetic-token")] { assert!(matches!(validate_create_as(&definition, &json!({"title":"Test","fee":1}), author), Err(RecordError::Readonly { column }) if column == "fee"), "{author:?} cannot name it at create"); } for author in [Author::App, Author::Other, Author::Token("synthetic-token")] { assert!(matches!(validate_patch_as(&definition, &json!({"fee":2}), author), Err(RecordError::Readonly { column }) if column == "fee"), "{author:?} cannot edit it"); assert!(validate_patch_as(&definition, &json!({"notes":"Owner note"}), author).is_ok()); }}/// RULE: Account numbers keep their raw stored value but every typed read and query uses only the ending; middle digits must never identify a record through search.#[test]fn typed_account_number_projection_and_search_never_expose_middle_digits() { let mut definition = lesson(); definition.columns.push(serde_json::from_value(json!({"key":"account", "type":"account_number"})).unwrap()); definition.validate().unwrap(); let stored = json!({"title":"Synthetic savings","account":"12345678901234"}).as_object().unwrap().clone(); let mut read = stored.clone(); project_read_data(&definition, &mut read); assert_eq!(read["account"], json!("1234")); assert_eq!(stored["account"], json!("12345678901234")); project_read_data(&definition, &mut read); assert_eq!(read["account"], json!("1234")); assert!(!matches_query(&definition, &stored, "567890")); assert!(!matches_query(&definition, &stored, "12345678901234")); assert!(matches_query(&definition, &stored, "1234")); let mut account_title = definition.clone(); account_title.title = "account".into(); assert_eq!(receipt::record_name(&account_title, &Value::Object(stored.clone())), "1234"); for (stored, ending) in [("1234 5678-901234", "1234"), ("XX-1234", "1234"), ("07", "07"), ("unavailable", "")] { assert_eq!(account_number_ending(stored), ending); }}