Cotton code
599 lines · 19.0 KB · RustRaw
//! The rule this file exists to hold still: a group's KEEP is decided by a//! written order, so two runs over the same rows name the same keep and the//! owner is never asked twice about the same pair.use std::collections::HashSet;use super::*;const ZERO: &str = "0000000000000000";/// `ZERO` with `bits` low bits flipped — the TypeScript test's own helper.fn flipped(bits: u32) -> String {    let mut value: u64 = 0;    for i in 0..bits {        value |= 1u64 << i;    }    format!("{value:016x}")}fn photo(id: &str, phash: Option<&str>) -> PhotoForDuplicates {    PhotoForDuplicates {        id: format!("photo:{id}"),        phash: phash.map(str::to_string),        favourite: false,        width: Some(100),        height: Some(100),        size_bytes: 1000,        taken_at: "2026-01-01T00:00:00.000Z".to_string(),    }}fn propose(photos: &[PhotoForDuplicates]) -> Vec<DuplicateProposal> {    propose_duplicates(photos, &ProposeDuplicatesOptions::default()).expect("hashes are hex")}fn arrows(proposals: &[DuplicateProposal]) -> Vec<String> {    proposals        .iter()        .map(|p| format!("{}>{}", p.keep_id, p.copy_id))        .collect()}// ── phashDistance ────────────────────────────────────────────────────────────#[test]fn counts_differing_bits() {    assert_eq!(phash_distance(ZERO, ZERO), Ok(0));    assert_eq!(phash_distance(ZERO, &flipped(1)), Ok(1));    assert_eq!(phash_distance(ZERO, &flipped(8)), Ok(8));    assert_eq!(phash_distance(ZERO, &"f".repeat(16)), Ok(64));    assert_eq!(        phash_distance("a1b2c3d4e5f60718", "a1b2c3d4e5f60718"),        Ok(0)    );}#[test]fn refuses_anything_that_is_not_16_hex_characters() {    assert_eq!(        phash_distance("abc", ZERO),        Err(DuplicatesError::HashLength { a: 3, b: 16 })    );    assert_eq!(        phash_distance("abc", ZERO).unwrap_err().to_string(),        "phashDistance: a hash is 16 hex characters (got 3 and 16)"    );    assert_eq!(        phash_distance("zzzzzzzzzzzzzzzz", ZERO),        Err(DuplicatesError::NotHex)    );    assert_eq!(        phash_distance("zzzzzzzzzzzzzzzz", ZERO)            .unwrap_err()            .to_string(),        "phashDistance: not hex"    );}/// Twelve distances and twelve refusals read out of Node, not reasoned out.////// Two of them corrected a guess. UPPERCASE hex is ACCEPTED — `parseInt` does/// not care about case, so `A1B2…` and `a1b2…` are zero apart rather than a/// throw, in flat contradiction of the "16 lowercase hex" the row comment/// promises. And the LENGTH is counted in UTF-16 code units: fourteen zeroes/// plus one emoji is sixteen units long and is refused for not being hex,/// while `é` plus fifteen zeroes is also sixteen and also not hex — but an/// emoji in a fifteen-character string reads as SEVENTEEN and is refused for/// its length instead.#[test]fn phash_distance_matches_the_typescript_on_every_odd_shape() {    let cases: &[(&str, &str, Result<u32, DuplicatesError>)] = &[        (ZERO, ZERO, Ok(0)),        (ZERO, "0000000000000001", Ok(1)),        (ZERO, "00000000000000ff", Ok(8)),        (ZERO, "ffffffffffffffff", Ok(64)),        ("a1b2c3d4e5f60718", "a1b2c3d4e5f60718", Ok(0)),        ("a1b2c3d4e5f60718", "a1b2c3d4e5f60719", Ok(1)),        // Uppercase reads exactly like lowercase.        ("A1B2C3D4E5F60718", "a1b2c3d4e5f60718", Ok(0)),        ("FFFFFFFFFFFFFFFF", ZERO, Ok(64)),        ("0f0f0f0f0f0f0f0f", "f0f0f0f0f0f0f0f0", Ok(64)),        ("deadbeefdeadbeef", "deadbeefdeadbeee", Ok(1)),        ("123456789abcdef0", "0fedcba987654321", Ok(36)),        (ZERO, "0000000000000fff", Ok(12)),        ("000000000000000A", ZERO, Ok(2)),        // Refusals, each with the reason Node gave.        (            "abc",            ZERO,            Err(DuplicatesError::HashLength { a: 3, b: 16 }),        ),        ("zzzzzzzzzzzzzzzz", ZERO, Err(DuplicatesError::NotHex)),        ("", "", Err(DuplicatesError::HashLength { a: 0, b: 0 })),        (ZERO, " 000000000000000", Err(DuplicatesError::NotHex)),        (ZERO, "00000000000000+0", Err(DuplicatesError::NotHex)),        (            ZERO,            "0000000000000\u{e9}0",            Err(DuplicatesError::HashLength { a: 16, b: 15 }),        ),        (            "\u{1F600}000000000000",            ZERO,            Err(DuplicatesError::HashLength { a: 14, b: 16 }),        ),        // Sixteen UTF-16 units, and not hex — the emoji is two of them.        (            "\u{1F600}00000000000000",            ZERO,            Err(DuplicatesError::NotHex),        ),        ("\u{e9}000000000000000", ZERO, Err(DuplicatesError::NotHex)),        ("000000000000000g", ZERO, Err(DuplicatesError::NotHex)),    ];    for (a, b, expected) in cases {        assert_eq!(            &phash_distance(a, b),            expected,            "phash_distance({a:?}, {b:?})"        );    }    // Arabic-Indic digits are digits to a human and `NaN` to `parseInt`.    assert_eq!(        phash_distance(&"\u{0660}".repeat(16), ZERO),        Err(DuplicatesError::NotHex)    );}/// The `flipped` helper both test files build their hashes with, pinned/// against what Node printed — otherwise every distance below would be/// asserting against a bug in the fixture.#[test]fn the_flipped_helper_prints_what_node_printed() {    assert_eq!(flipped(1), "0000000000000001");    assert_eq!(flipped(2), "0000000000000003");    assert_eq!(flipped(3), "0000000000000007");    assert_eq!(flipped(6), "000000000000003f");    assert_eq!(flipped(8), "00000000000000ff");    assert_eq!(flipped(12), "0000000000000fff");}// ── chooseKeep, the rule in order ────────────────────────────────────────────fn keep_of(members: &[PhotoForDuplicates]) -> String {    choose_keep(members).expect("non-empty").id.clone()}#[test]fn the_favourite_first() {    let members = vec![        PhotoForDuplicates {            width: Some(10),            height: Some(10),            ..photo("a", Some(ZERO))        },        PhotoForDuplicates {            favourite: true,            width: Some(1),            height: Some(1),            ..photo("b", Some(ZERO))        },    ];    assert_eq!(keep_of(&members), "photo:b");}#[test]fn then_the_most_pixels() {    assert_eq!(        keep_of(&[            PhotoForDuplicates {                width: Some(10),                height: Some(10),                ..photo("a", Some(ZERO))            },            PhotoForDuplicates {                width: Some(20),                height: Some(20),                ..photo("b", Some(ZERO))            },        ]),        "photo:b"    );    // Unknown dimensions count as zero pixels.    assert_eq!(        keep_of(&[            PhotoForDuplicates {                width: None,                height: None,                ..photo("a", Some(ZERO))            },            PhotoForDuplicates {                width: Some(1),                height: Some(1),                ..photo("b", Some(ZERO))            },        ]),        "photo:b"    );}#[test]fn then_the_most_bytes() {    assert_eq!(        keep_of(&[            PhotoForDuplicates {                size_bytes: 10,                ..photo("a", Some(ZERO))            },            PhotoForDuplicates {                size_bytes: 20,                ..photo("b", Some(ZERO))            },        ]),        "photo:b"    );}#[test]fn then_the_earliest_taken() {    assert_eq!(        keep_of(&[            PhotoForDuplicates {                taken_at: "2026-02-01T00:00:00.000Z".to_string(),                ..photo("a", Some(ZERO))            },            PhotoForDuplicates {                taken_at: "2026-01-01T00:00:00.000Z".to_string(),                ..photo("b", Some(ZERO))            },        ]),        "photo:b"    );}#[test]fn then_the_lowest_id_total_never_a_tie() {    assert_eq!(        keep_of(&[photo("b", Some(ZERO)), photo("a", Some(ZERO))]),        "photo:a"    );    assert_eq!(choose_keep(&[]), Err(DuplicatesError::EmptyGroup));    assert_eq!(        choose_keep(&[]).unwrap_err().to_string(),        "chooseKeep: empty group"    );}/// Eight groups run through the TypeScript, the keep read off its answer.////// The last two are the ones worth having. Three photos of equal pixel COUNT/// but different shapes (200×50, 100×100, 50×200) and equal bytes fall all the/// way through to the id — the rule counts pixels, not resolution. And/// `taken_at` is compared as a STRING: an offset-bearing instant/// (`…000+05:30`) sorts BEFORE the same moment written `…000Z`, because `+` is/// a lower code unit than `Z`, so the "earliest taken" clause is really/// "earliest spelled" the day a row stops being written in UTC.#[test]fn choose_keep_matches_the_typescript_on_every_tiebreak() {    let five = vec![        PhotoForDuplicates {            width: Some(4000),            height: Some(3000),            size_bytes: 900,            ..photo("e", Some(ZERO))        },        PhotoForDuplicates {            width: Some(4000),            height: Some(3000),            size_bytes: 900,            taken_at: "2025-12-31T23:59:59.999Z".to_string(),            ..photo("d", Some(ZERO))        },        PhotoForDuplicates {            width: Some(4000),            height: Some(3000),            size_bytes: 5000,            ..photo("c", Some(ZERO))        },        PhotoForDuplicates {            width: Some(8000),            height: Some(1500),            size_bytes: 5000,            ..photo("b", Some(ZERO))        },        PhotoForDuplicates {            favourite: true,            width: Some(1),            height: Some(1),            size_bytes: 1,            ..photo("a", Some(ZERO))        },    ];    assert_eq!(keep_of(&five), "photo:a");    let same_pixels = vec![        PhotoForDuplicates {            width: Some(200),            height: Some(50),            size_bytes: 77,            ..photo("z", Some(ZERO))        },        PhotoForDuplicates {            width: Some(100),            height: Some(100),            size_bytes: 77,            ..photo("y", Some(ZERO))        },        PhotoForDuplicates {            width: Some(50),            height: Some(200),            size_bytes: 77,            ..photo("x", Some(ZERO))        },    ];    assert_eq!(keep_of(&same_pixels), "photo:x");    let spellings = vec![        PhotoForDuplicates {            taken_at: "2026-01-01T00:00:00.000+05:30".to_string(),            ..photo("a", Some(ZERO))        },        PhotoForDuplicates {            taken_at: "2026-01-01T00:00:00.000Z".to_string(),            ..photo("b", Some(ZERO))        },    ];    assert_eq!(keep_of(&spellings), "photo:a");}// ── proposeDuplicates ────────────────────────────────────────────────────────#[test]fn groups_photos_within_the_distance_and_names_one_keep_per_group() {    let photos = vec![        PhotoForDuplicates {            size_bytes: 3000,            ..photo("a", Some(ZERO))        },        photo("b", Some(&flipped(3))),        photo("c", Some(&flipped(6))),        photo("far", Some(&"f".repeat(16))),        photo("unhashed", None),    ];    assert_eq!(        propose(&photos),        vec![            DuplicateProposal {                keep_id: "photo:a".to_string(),                copy_id: "photo:b".to_string(),                distance: 3,            },            DuplicateProposal {                keep_id: "photo:a".to_string(),                copy_id: "photo:c".to_string(),                distance: 6,            },        ]    );    assert_eq!(DUPLICATE_MAX_DISTANCE, 8);}/// A chain joins even when the ends are far apart: a–b six bits, b–c six bits,/// a–c twelve. One group of three, because a group is a connected component/// and not a clique.#[test]fn is_a_connected_component() {    let a = ZERO.to_string();    let b = flipped(6);    let c = flipped(12);    assert_eq!(phash_distance(&a, &c), Ok(12));    let out = propose(&[        photo("a", Some(&a)),        photo("b", Some(&b)),        photo("c", Some(&c)),    ]);    let mut copies: Vec<&str> = out.iter().map(|p| p.copy_id.as_str()).collect();    copies.sort_unstable();    assert_eq!(copies, vec!["photo:b", "photo:c"]);    let keeps: HashSet<&str> = out.iter().map(|p| p.keep_id.as_str()).collect();    assert_eq!(keeps.len(), 1);    // The copy's distance is measured to the KEEP, whatever it is.    for proposal in &out {        assert!(proposal.distance <= 12);    }}#[test]fn with_a_focus_only_groups_touching_a_focused_photo_are_proposed() {    let photos = vec![        photo("a", Some(ZERO)),        photo("b", Some(&flipped(2))),        photo("x", Some(&"f".repeat(16))),        photo("y", Some(&format!("{}e", "f".repeat(15)))),    ];    let mut all = arrows(&propose(&photos));    all.sort();    assert_eq!(all, vec!["photo:a>photo:b", "photo:x>photo:y"]);    let focus: HashSet<String> = ["photo:y".to_string()].into_iter().collect();    assert_eq!(        arrows(            &propose_duplicates(                &photos,                &ProposeDuplicatesOptions {                    focus: Some(&focus),                    ..ProposeDuplicatesOptions::default()                }            )            .expect("hashes are hex")        ),        vec!["photo:x>photo:y"]    );    let elsewhere: HashSet<String> = ["photo:unrelated".to_string()].into_iter().collect();    assert_eq!(        propose_duplicates(            &photos,            &ProposeDuplicatesOptions {                focus: Some(&elsewhere),                ..ProposeDuplicatesOptions::default()            }        ),        Ok(vec![])    );}#[test]fn proposes_nothing_for_a_lone_photo_or_an_empty_set() {    assert_eq!(propose(&[]), vec![]);    assert_eq!(propose(&[photo("a", Some(ZERO))]), vec![]);}/// Four whole answers read out of Node over one eight-photo library, so the/// grouping, the keep, the reported distance and the OUTPUT ORDER are all/// pinned at once.////// The favourite is `photo:fav`, two bits from zero, so it is the keep of the/// whole a–b–c–d chain even though `photo:a` is bigger — and every distance is/// then measured to IT, which is why `photo:d` reports 10 and not the 12 it/// sits from `photo:a`. Tightening `max_distance` to 2 breaks the chain but/// leaves the pairs; widening it to 64 swallows the far pair into the one/// group.#[test]fn the_whole_grouping_matches_a_golden_read_out_of_node() {    let library = vec![        PhotoForDuplicates {            size_bytes: 3000,            ..photo("a", Some(ZERO))        },        photo("b", Some(&flipped(3))),        photo("c", Some(&flipped(6))),        photo("d", Some(&flipped(12))),        photo("far", Some(&"f".repeat(16))),        photo("far2", Some(&format!("{}e", "f".repeat(15)))),        photo("unhashed", None),        PhotoForDuplicates {            favourite: true,            width: Some(1),            height: Some(1),            ..photo("fav", Some(&flipped(2)))        },    ];    let golden = |json: &str| -> Vec<DuplicateProposal> {        serde_json::from_str(json).expect("golden JSON parses")    };    assert_eq!(        propose(&library),        golden(            r#"[              {"keepId":"photo:far","copyId":"photo:far2","distance":1},              {"keepId":"photo:fav","copyId":"photo:a","distance":2},              {"keepId":"photo:fav","copyId":"photo:b","distance":1},              {"keepId":"photo:fav","copyId":"photo:c","distance":4},              {"keepId":"photo:fav","copyId":"photo:d","distance":10}            ]"#        )    );    assert_eq!(        propose_duplicates(            &library,            &ProposeDuplicatesOptions {                max_distance: Some(2),                focus: None,            }        )        .expect("hashes are hex"),        golden(            r#"[              {"keepId":"photo:far","copyId":"photo:far2","distance":1},              {"keepId":"photo:fav","copyId":"photo:a","distance":2},              {"keepId":"photo:fav","copyId":"photo:b","distance":1}            ]"#        )    );    let focus: HashSet<String> = ["photo:far2".to_string()].into_iter().collect();    assert_eq!(        propose_duplicates(            &library,            &ProposeDuplicatesOptions {                max_distance: None,                focus: Some(&focus),            }        )        .expect("hashes are hex"),        golden(r#"[{"keepId":"photo:far","copyId":"photo:far2","distance":1}]"#)    );    assert_eq!(        propose_duplicates(            &library,            &ProposeDuplicatesOptions {                max_distance: Some(64),                focus: None,            }        )        .expect("hashes are hex"),        golden(            r#"[              {"keepId":"photo:fav","copyId":"photo:a","distance":2},              {"keepId":"photo:fav","copyId":"photo:b","distance":1},              {"keepId":"photo:fav","copyId":"photo:c","distance":4},              {"keepId":"photo:fav","copyId":"photo:d","distance":10},              {"keepId":"photo:fav","copyId":"photo:far","distance":62},              {"keepId":"photo:fav","copyId":"photo:far2","distance":63}            ]"#        )    );}/// A malformed hash on a hashed photo stops the pass rather than quietly/// grouping around it — the TypeScript throws here, and a grouping computed/// from a hash nobody could read is not a grouping.#[test]fn a_malformed_hash_refuses_the_whole_pass() {    assert_eq!(        propose_duplicates(            &[photo("a", Some(ZERO)), photo("b", Some("nope"))],            &ProposeDuplicatesOptions::default()        ),        Err(DuplicatesError::HashLength { a: 16, b: 4 })    );}/// Two rows carrying the same id cannot make the comparator panic. Rust's own/// `sort_by` is entitled to abort on a comparator that answers "greater" for/// two equal values, which is exactly what the id clause does; the merge sort/// in `super` is why this returns an answer instead.#[test]fn a_repeated_id_is_answered_rather_than_aborted() {    let twins = vec![        photo("a", Some(ZERO)),        photo("a", Some(ZERO)),        photo("a", Some(ZERO)),        photo("b", Some(&flipped(1))),    ];    let out = propose(&twins);    assert!(out.iter().all(|p| p.keep_id == "photo:a"));    assert_eq!(        out.iter().map(|p| p.copy_id.as_str()).collect::<Vec<_>>(),        vec!["photo:b"]    );}#[test]fn the_wire_shape_is_the_typescript_object() {    let proposal = DuplicateProposal {        keep_id: "photo:a".to_string(),        copy_id: "photo:b".to_string(),        distance: 3,    };    assert_eq!(        serde_json::to_string(&proposal).expect("serialises"),        r#"{"keepId":"photo:a","copyId":"photo:b","distance":3}"#    );}