//! The thumbnail cache's two questions, against a real seeded file.//!//! Every digest, picture and instant here is synthetic//! ([nothing-real-ever-goes-in-cotton-s-public-tree]), and the crate reads no//! clock, so a failure is reproducible.usesuper::*;usecrate::media_ledger::{enqueue_media, media_by_key, MediaEnqueueInput};usecrate::test_support::{seeded_file, WORKSPACE};const THIS_PHONE: &str = "device:01J0000000000000000000000A";constT0: &str = "2026-09-16T09:00:00.000Z";/// The two shapes, exactly as `cotton-client` derives them from/// `cotton_core::media::keys` — spelled here because this crate cannot see that/// one, and asserted against in `cotton-client`'s own suite.fn photo_shape() -> KeyShape {KeyShape::new(format!("{WORKSPACE}/photos/"), ".t256.jpg")}fn video_shape() -> KeyShape {KeyShape::new(format!("{WORKSPACE}/videos/"), ".t256.jpg")}fn digest(mark: char) -> String { mark.to_string().repeat(64)}fn file() -> Driver { seeded_file(THIS_PHONE)}/// A picture, with a digest and the moment it was taken.fn photo(db: &Driver, mark: char, taken_at: &str) {let sha = digest(mark); db.run("INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)", &[SqlValue::Text(format!("photo:{sha}")),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(format!("{WORKSPACE}/photos/{sha}.heic")),SqlValue::Text(sha),SqlValue::Text("image/heic".to_string()),SqlValue::Integer(4_000_000),SqlValue::Text(taken_at.to_string()),SqlValue::Text(T0.to_string()),SqlValue::Text(T0.to_string()), ], ) .expect("the photo row");}fn video(db: &Driver, mark: char, taken_at: &str) {let sha = digest(mark); db.run("INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)", &[SqlValue::Text(format!("video:{sha}")),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(format!("{WORKSPACE}/videos/{sha}.mp4")),SqlValue::Text(sha),SqlValue::Text("video/mp4".to_string()),SqlValue::Integer(90_000_000),SqlValue::Text(taken_at.to_string()),SqlValue::Text(T0.to_string()),SqlValue::Text(T0.to_string()), ], ) .expect("the video row");}fn arrived(db: &Driver, key: &str, sha256: &str) { record_thumb( db, &ThumbArrived { key, workspace_id: WORKSPACE, sha256, size_bytes: 12_000, local_path: "/var/cache/thumbs/x.t256.jpg", now: T0, }, ) .expect("records the thumbnail");}fn wanted(db: &Driver, after: Option<&ThumbWanted>, limit: i64) -> Vec<String> { thumbs_wanted(db, WORKSPACE, &photo_shape(), &video_shape(), None, after, limit) .expect("the work list") .into_iter() .map(|row| row.key) .collect()}// ─────────────────────────────────────────────────────────────────────────────// thumbs_wanted// ─────────────────────────────────────────────────────────────────────────────#[test]fn wants_every_photo_and_film_thumbnail_newest_first() {let db = file(); photo(&db, 'a', "2026-01-01T00:00:00.000Z"); video(&db, 'b', "2026-06-01T00:00:00.000Z"); photo(&db, 'c', "2026-09-01T00:00:00.000Z");// Newest first, because that is what a person opens: a library arriving on// a second phone is scrolled from the top. assert_eq!( wanted(&db, None, 10), vec![ photo_shape().key(&digest('c')), video_shape().key(&digest('b')), photo_shape().key(&digest('a')), ] );}#[test]fn stops_wanting_a_thumbnail_the_moment_its_file_is_on_this_device() {let db = file(); photo(&db, 'a', "2026-01-01T00:00:00.000Z"); photo(&db, 'c', "2026-09-01T00:00:00.000Z");let newest = photo_shape().key(&digest('c')); arrived(&db, &newest, &digest('z'));// THE WHOLE RESUME STORY. A pass cut short by its time budget asks the same// question again next tick; what it already fetched has dropped out, so it// picks up where it stopped without a cursor anywhere on disk. assert_eq!(wanted(&db, None, 10), vec![photo_shape().key(&digest('a'))]);}#[test]fn a_row_with_no_local_file_is_still_wanted() {let db = file(); photo(&db, 'a', "2026-01-01T00:00:00.000Z");let key = photo_shape().key(&digest('a')); arrived(&db, &key, &digest('z'));// The cache was wiped: the row remembers the thumbnail, the disk does not. db.run("UPDATE _media SET local_path = NULL WHERE key = ?", &[SqlValue::Text(key.clone())], ) .expect("clears the path"); assert_eq!( wanted(&db, None, 10), vec![key],"a ledger row that names no file is not a thumbnail" );}#[test]fn a_media_row_of_another_tier_is_not_a_thumbnail() {let db = file(); photo(&db, 'a', "2026-01-01T00:00:00.000Z");// The ORIGINAL is on this device. That says nothing about the thumbnail,// and a query that matched on the key alone would think it did. enqueue_media( &db, &MediaEnqueueInput { key: photo_shape().key(&digest('a')), workspace_id: WORKSPACE.to_string(), sha256: digest('a'), content_type: "image/heic".to_string(), size_bytes: 4_000_000, local_path: Some("/var/media/aa/a.heic".to_string()), state: Some("synced".to_string()), after: None, after_row_id: None, tier: None, captured_here: false, now: T0.to_string(), }, ) .expect("the original's row"); assert_eq!(wanted(&db, None, 10), vec![photo_shape().key(&digest('a'))]);}#[test]fn pages_within_a_pass_on_the_pair_that_is_actually_unique() {let db = file();// A whole import shares one instant — which is why the cursor is// `(taken_at, key)` and not `taken_at` alone.let shared = "2026-05-05T05:05:05.000Z"; photo(&db, 'a', shared); photo(&db, 'b', shared); photo(&db, 'c', shared);let first = thumbs_wanted(&db, WORKSPACE, &photo_shape(), &video_shape(), None, None, 2) .expect("the first page"); assert_eq!(first.len(), 2);let cursor = first[1].clone();let second = wanted(&db, Some(&cursor), 2);letmut every: Vec<String> = first.iter().map(|row| row.key.clone()).collect(); every.extend(second); every.sort();letmut expected = vec![ photo_shape().key(&digest('a')), photo_shape().key(&digest('b')), photo_shape().key(&digest('c')), ]; expected.sort(); assert_eq!(every, expected, "no row repeated and none skipped");}#[test]fn a_pass_that_asked_for_everything_and_got_nothing_ends() {let db = file(); photo(&db, 'a', "2026-01-01T00:00:00.000Z");let only = thumbs_wanted(&db, WORKSPACE, &photo_shape(), &video_shape(), None, None, 10) .expect("the work list");let cursor = only[0].clone();// The server held none of them. The cursor past the last row answers empty,// which is what stops the pass rather than looping on the same page. assert!(wanted(&db, Some(&cursor), 10).is_empty());}// ─────────────────────────────────────────────────────────────────────────────// record_thumb// ─────────────────────────────────────────────────────────────────────────────#[test]fn a_thumbnail_is_born_synced_because_it_came_down_not_up() {let db = file();let key = photo_shape().key(&digest('a')); arrived(&db, &key, &digest('z'));let row = media_by_key(&db, &key).expect("reads").expect("a row");// `pending` is the drain's queue for bytes going UP. A thumbnail the server// just sent down would be uploaded straight back at it. assert_eq!(row.state, "synced"); assert_eq!(row.content_type, "image/jpeg"); assert_eq!(row.local_path.as_deref(), Some("/var/cache/thumbs/x.t256.jpg"));// The THUMBNAIL's own digest, never the picture's: `_media.sha256` is a// content address of the file at `local_path`. assert_eq!(row.sha256, digest('z')); assert_eq!(local_thumb_count(&db, WORKSPACE).expect("counts"), 1);}#[test]fn recording_the_same_thumbnail_twice_is_one_row() {let db = file();let key = photo_shape().key(&digest('a')); arrived(&db, &key, &digest('z')); record_thumb( &db, &ThumbArrived { key: &key, workspace_id: WORKSPACE, sha256: &digest('y'), size_bytes: 13_000, local_path: "/var/cache/thumbs/again.t256.jpg", now: "2026-09-17T09:00:00.000Z", }, ) .expect("records it again"); assert_eq!(local_thumb_count(&db, WORKSPACE).expect("counts"), 1);let row = media_by_key(&db, &key).expect("reads").expect("a row"); assert_eq!(row.size_bytes, 13_000); assert_eq!( row.local_path.as_deref(),Some("/var/cache/thumbs/again.t256.jpg") );// `created_at` is the FIRST time; only `updated_at` moves. assert_eq!(row.created_at, T0); assert_eq!(row.updated_at, "2026-09-17T09:00:00.000Z");}#[test]fn a_count_of_thumbnails_is_this_workspaces_own() {let db = file(); arrived(&db, &photo_shape().key(&digest('a')), &digest('z'));let other = "22222222-2222-4222-8222-222222222222"; record_thumb( &db, &ThumbArrived { key: &format!("{other}/photos/{}.t256.jpg", digest('b')), workspace_id: other, sha256: &digest('y'), size_bytes: 12_000, local_path: "/var/cache/thumbs/other.t256.jpg", now: T0, }, ) .expect("records it"); assert_eq!(local_thumb_count(&db, WORKSPACE).expect("counts"), 1);}/// The folder a status's bytes are kept under, as `cotton-client` spells it/// for a phone (`message_media_prefix(file, STATUS_MEDIA_FOLDER)`).fn statuses_folder() -> String { format!("{WORKSPACE}/messages/statuses/")}/// A status's key, and a chat's: the two places a picture can have been seen.fn status_key(mark: char) -> String { format!("{}{}.jpg", statuses_folder(), digest(mark))}fn chat_key(mark: char) -> String { format!("{WORKSPACE}/messages/thread-1/{}.jpg", digest(mark))}/// A picture or a film as the media index derives one from where it was seen:/// the row carries the key of the sighting it was born from.fn derived(db: &Driver, kind: &str, mark: char, key: &str, taken_at: &str) {let sha = digest(mark);let (table, content_type) = match kind {"photo" => ("cotton_photos", "image/jpeg"), _ => ("cotton_videos", "video/mp4"), }; db.run(// `table` is one of two literals chosen above, never data. &format!("INSERT INTO {table} (id, workspace_id, key, sha256, content_type, size_bytes, \ taken_at, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)" ), &[SqlValue::Text(format!("{kind}:{sha}")),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(key.to_string()),SqlValue::Text(sha),SqlValue::Text(content_type.to_string()),SqlValue::Integer(200_000),SqlValue::Text(taken_at.to_string()),SqlValue::Text(T0.to_string()),SqlValue::Text(T0.to_string()), ], ) .expect("the derived row");}/// One place `kind:<digest>` was seen: a message, with the key it had there.fn sighting(db: &Driver, kind: &str, mark: char, source_id: &str, thread_id: &str, key: &str, seen_at: &str) { db.run("INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \ source_id, thread_id, key, seen_at, created_at, updated_at) \ VALUES (?,?,?,?,'message',?,?,?,?,?,?)", &[SqlValue::Text(format!("sighting:{kind}:{mark}:{source_id}")),SqlValue::Text(WORKSPACE.to_string()),SqlValue::Text(kind.to_string()),SqlValue::Text(format!("{kind}:{}", digest(mark))),SqlValue::Text(source_id.to_string()),SqlValue::Text(thread_id.to_string()),SqlValue::Text(key.to_string()),SqlValue::Text(seen_at.to_string()),SqlValue::Text(T0.to_string()),SqlValue::Text(T0.to_string()), ], ) .expect("the sighting row");}/// The work list a PHONE asks for: the statuses folder named.fn wanted_on_a_phone(db: &Driver) -> Vec<String> {let folder = statuses_folder(); thumbs_wanted(db, WORKSPACE, &photo_shape(), &video_shape(), Some(&folder), None, 100) .expect("the work list") .into_iter() .map(|row| row.key) .collect()}// ─────────────────────────────────────────────────────────────────────────────// What a phone never collects// ─────────────────────────────────────────────────────────────────────────────/// RULE (architect, 12 Oct 2026, the phone's thumbnail sweep): "a status/// sighting never produces a phone thumbnail; a people-media sighting does,/// whatever its age."////// Why it is a rule and not a tidy-up: a status is a stranger's 24-hour post,/// there are thousands of them in a WhatsApp history, and a phone holds what/// its person chose to keep — a sweep that filled the phone's cache with them/// would be the phone keeping exactly what the brief says it never does. And/// why the second sentence is in the same test: the cut must be by WHERE a/// picture was seen and never by how old it is — thumbnails are what make a/// twelve-year-old chat readable, so a predicate that grew an age clause, or/// that dropped every row with a status sighting, would empty the chats.////// Both arms of the UNION are here (a photo and a film of each kind), and so/// is a Mac: with no folder named its list is every row, which is also what/// proves these fixtures WOULD be wanted were it not for the clause.#[test]fn a_status_sighting_never_produces_a_phone_thumbnail_and_a_people_media_sighting_does_whatever_its_age() {let db = file();// Seen only in a status: a photo ('a') and a film ('b'). derived(&db, "photo", 'a', &status_key('a'), "2026-09-10T00:00:00.000Z"); sighting(&db, "photo", 'a', "story-a", "statuses", &status_key('a'), "2026-09-10T00:00:00.000Z"); derived(&db, "video", 'b', &status_key('b'), "2026-09-09T00:00:00.000Z"); sighting(&db, "video", 'b', "story-b", "statuses", &status_key('b'), "2026-09-09T00:00:00.000Z");// Sent by a person in a chat, twelve years ago: a photo ('c') and a film ('d'). derived(&db, "photo", 'c', &chat_key('c'), "2014-03-01T00:00:00.000Z"); sighting(&db, "photo", 'c', "message-c", "thread-1", &chat_key('c'), "2014-03-01T00:00:00.000Z"); derived(&db, "video", 'd', &chat_key('d'), "2014-02-01T00:00:00.000Z"); sighting(&db, "video", 'd', "message-d", "thread-1", &chat_key('d'), "2014-02-01T00:00:00.000Z"); assert_eq!( wanted_on_a_phone(&db), vec![photo_shape().key(&digest('c')), video_shape().key(&digest('d'))],"the chat's picture and film, twelve years old, and neither status" ); assert_eq!( wanted(&db, None, 100), vec![ photo_shape().key(&digest('a')), video_shape().key(&digest('b')), photo_shape().key(&digest('c')), video_shape().key(&digest('d')), ],"a Mac names no folder and its sweep is untouched: all four" );}/// The same bytes can be a status one day and a chat picture another — one/// digest, one library row. A PEOPLE SIGHTING WINS: somebody sent it to this/// person, so it is theirs to scroll past in the chat, whichever of the two/// the row happened to be born from.#[test]fn a_picture_seen_in_a_status_and_in_a_chat_is_a_chat_picture() {let db = file();// Born from the status, then also seen in a chat. derived(&db, "photo", 'a', &status_key('a'), "2026-09-10T00:00:00.000Z"); sighting(&db, "photo", 'a', "story-a", "statuses", &status_key('a'), "2026-09-10T00:00:00.000Z"); sighting(&db, "photo", 'a', "message-a", "thread-1", &chat_key('a'), "2026-09-11T00:00:00.000Z");// Born from the chat, then also posted as a status. derived(&db, "video", 'b', &chat_key('b'), "2026-09-08T00:00:00.000Z"); sighting(&db, "video", 'b', "message-b", "thread-1", &chat_key('b'), "2026-09-08T00:00:00.000Z"); sighting(&db, "video", 'b', "story-b", "statuses", &status_key('b'), "2026-09-09T00:00:00.000Z"); assert_eq!( wanted_on_a_phone(&db), vec![photo_shape().key(&digest('a')), video_shape().key(&digest('b'))] );}/// The row alone is enough to say "status": a sighting is written AFTER its/// row and that write can fail (the index steps over a failed row), so a/// status's picture with no sighting at all must still be left out — and a/// camera-roll picture, which has no sighting either, must still be wanted.#[test]fn a_status_row_with_no_sighting_is_still_a_status_and_a_library_picture_with_none_is_still_wanted() {let db = file(); derived(&db, "photo", 'a', &status_key('a'), "2026-09-10T00:00:00.000Z"); photo(&db, 'b', "2026-09-09T00:00:00.000Z"); assert_eq!(wanted_on_a_phone(&db), vec![photo_shape().key(&digest('b'))]);}