indicatrix-cut 0.7.2

Desktop faceting-design editor: library browsing, spectral 3D rendering, material retargeting, and a solid inspection view.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! Tests for the mirror sync pipeline, built against [`fixtures::FakeTransport`], a
//! scripted, in-memory [`LibraryTransport`](crate::bridge::library::mirror::options::LibraryTransport).

mod fixtures;
mod revision;

use super::pass::run_mirror_sync;
use crate::{
    bridge::library::mirror::options::{MirrorOptions, MirrorOutcome, mirror_source_id},
    settings::WorkerSettings,
};
use fixtures::{FakeTransport, design_record, design_summary, temp_db};
use indicatrix_net::library::{AttachedFileMeta, DesignRecord, DesignSummary};
use indicatrix_vault::model::{
    detail::FacetingDiagramDetail, entry::FacetingDiagramEntry, file::AttachedFile,
};
use std::sync::atomic::{AtomicBool, Ordering};

#[test]
fn a_local_only_design_survives_a_mirror_sync() {
    let (db, path) = temp_db();
    // A design that exists ONLY locally (a user's own `.asc` import) -- a synthetic
    // `local://` URL, exactly `indicatrix_vault::local::import_asc`'s convention.
    let local_entry_id = {
        let guard = db.lock().unwrap();
        guard
            .save_diagram_entry(
                &FacetingDiagramEntry {
                    title: "My Own Trichecker".to_string(),
                    url: "local://my_trichecker.asc".to_string(),
                    design_id: String::new(),
                },
                indicatrix_vault::local::LOCAL_SOURCE_ID,
            )
            .unwrap()
    };
    {
        let guard = db.lock().unwrap();
        guard
            .save_diagram_detail(
                &FacetingDiagramDetail {
                    shape: Some("Trichecker".to_string()),
                    attached_files: vec![AttachedFile {
                        name: "my_trichecker.asc".to_string(),
                        url: String::new(),
                        content: b"a real user file".to_vec(),
                    }],
                    ..FacetingDiagramDetail::default()
                },
                local_entry_id,
            )
            .unwrap();
    }

    let remote_summary = design_summary(1, "Round Brilliant", "https://example.test/1", "v1");
    let remote_design = design_record(1, "Round Brilliant", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![remote_summary], vec![remote_design]);

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:example.test:9443",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    assert!(matches!(outcome, MirrorOutcome::Completed(c) if c.new_count == 1));

    // The local-only design is completely untouched: still there, same title, same
    // attachment content -- sync never deleted or altered it.
    let guard = db.lock().unwrap();
    let local_full = guard.get_diagram_full(local_entry_id).unwrap().unwrap();
    assert_eq!(local_full.title, "My Own Trichecker");
    assert_eq!(local_full.url, "local://my_trichecker.asc");
    assert_eq!(local_full.attached_files.len(), 1);
    assert_eq!(local_full.attached_files[0].content, b"a real user file");
    // And the remote design was actually added alongside it -- total count is both.
    assert_eq!(guard.get_total_count().unwrap(), 2);
    drop(guard);

    std::fs::remove_file(&path).ok();
}

/// unlike [`a_local_only_design_survives_a_mirror_sync`] (a local row and a
/// remote design at DIFFERENT urls, which never touch each other regardless of any
/// guard), this scripts a remote design whose `url` is IDENTICAL to a pre-existing
/// local row's -- exactly the collision a worker serving its own `local://` imports
/// (or a coincidentally-matching hand import) can produce. The local row must survive
/// completely untouched, and the attempt must be counted as
/// `local_conflicts_skipped`, never as `new_count`/`updated_count`/`failed`.
#[test]
fn a_remote_design_colliding_with_an_unmirrored_local_urls_identity_is_left_untouched() {
    let (db, path) = temp_db();
    let collision_url = "local://collide.asc";
    let local_entry_id = {
        let guard = db.lock().unwrap();
        guard
            .save_diagram_entry(
                &FacetingDiagramEntry {
                    title: "Local Original".to_string(),
                    url: collision_url.to_string(),
                    design_id: String::new(),
                },
                indicatrix_vault::local::LOCAL_SOURCE_ID,
            )
            .unwrap()
    };
    {
        let guard = db.lock().unwrap();
        guard
            .save_diagram_detail(
                &FacetingDiagramDetail {
                    attached_files: vec![AttachedFile {
                        name: "collide.asc".to_string(),
                        url: String::new(),
                        content: b"original local bytes".to_vec(),
                    }],
                    ..FacetingDiagramDetail::default()
                },
                local_entry_id,
            )
            .unwrap();
    }

    let remote_summary = design_summary(1, "Remote Version", collision_url, "v1");
    let remote_design = design_record(1, "Remote Version", collision_url, "v1");
    let transport = FakeTransport::new(vec![remote_summary], vec![remote_design]);

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.local_conflicts_skipped, 1);
    assert_eq!(counts.new_count, 0);
    assert_eq!(counts.updated_count, 0);
    assert_eq!(counts.failed, 0);

    let guard = db.lock().unwrap();
    assert_eq!(
        guard.get_total_count().unwrap(),
        1,
        "the collision must never be inserted as a second row"
    );
    let local_full = guard.get_diagram_full(local_entry_id).unwrap().unwrap();
    assert_eq!(local_full.title, "Local Original");
    assert_eq!(local_full.attached_files.len(), 1);
    assert_eq!(
        local_full.attached_files[0].content,
        b"original local bytes"
    );
    assert_eq!(
        guard.get_mirror_state(collision_url).unwrap(),
        None,
        "a skipped conflict must never be marked as synced"
    );
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn a_new_design_is_saved_with_its_attachment() {
    let (db, path) = temp_db();
    let mut record = design_record(1, "Round Brilliant", "https://example.test/1", "v1");
    record.attachments = vec![AttachedFileMeta {
        id: 100,
        name: "schedule.pdf".to_string(),
        url: "https://example.test/schedule.pdf".to_string(),
        size: 5,
    }];
    let summary = design_summary(1, "Round Brilliant", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![summary], vec![record]).with_attachment(
        100,
        "schedule.pdf",
        vec![1, 2, 3, 4, 5],
    );

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.new_count, 1);
    assert_eq!(counts.attachments_fetched, 1);
    assert_eq!(counts.attachment_bytes_fetched, 5);

    let guard = db.lock().unwrap();
    let full = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    assert_eq!(full.len(), 1);
    let entry_id = full[0].id;
    let record = guard.get_diagram_full(entry_id).unwrap().unwrap();
    assert_eq!(record.attached_files.len(), 1);
    assert_eq!(record.attached_files[0].content, vec![1, 2, 3, 4, 5]);
    drop(guard);
    std::fs::remove_file(&path).ok();
}

/// `source_citation`/`pdf_file`/`gem_file`/`shape_category` (added to
/// `DesignRecord` under `PROTOCOL_VERSION` v15) must survive a mirror sync into the
/// local `diagram_details` row -- `save_diagram_detail` fully replaces that row on
/// every sync, so leaving any of these four unmapped in `sync::design::build_detail`
/// would silently blank them, exactly like the eight ratio/symmetry fields the
/// pre-existing test coverage on this module already pins.
#[test]
fn a_synced_designs_citation_and_shape_category_fields_are_saved_locally() {
    let (db, path) = temp_db();
    let mut record = design_record(1, "Competition Entry", "https://example.test/1", "v1");
    record.source_citation = Some("Lapidary Journal, May 1994, p95".to_string());
    record.pdf_file = Some("2002SSCMasters.pdf".to_string());
    record.gem_file = Some("USFG-SSC-2020-Novice-1.gem".to_string());
    record.shape_category = Some("5".to_string());
    let summary = design_summary(1, "Competition Entry", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![summary], vec![record]);

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    assert!(matches!(outcome, MirrorOutcome::Completed(c) if c.new_count == 1));

    let guard = db.lock().unwrap();
    let items = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    let full = guard.get_diagram_full(items[0].id).unwrap().unwrap();
    assert_eq!(
        full.source_citation.as_deref(),
        Some("Lapidary Journal, May 1994, p95")
    );
    assert_eq!(full.pdf_file.as_deref(), Some("2002SSCMasters.pdf"));
    assert_eq!(full.gem_file.as_deref(), Some("USFG-SSC-2020-Novice-1.gem"));
    assert_eq!(full.shape_category.as_deref(), Some("5"));
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn a_second_sync_of_an_unchanged_catalogue_skips_every_design_and_makes_no_fetch_design_calls() {
    let (db, path) = temp_db();
    let summary = design_summary(1, "Round Brilliant", "https://example.test/1", "v1");
    let record = design_record(1, "Round Brilliant", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![summary], vec![record]);

    let first = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    assert!(matches!(first, MirrorOutcome::Completed(c) if c.new_count == 1));
    assert_eq!(transport.fetch_design_calls.load(Ordering::Relaxed), 1);

    let second = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = second else {
        panic!("expected Completed, got {second:?}");
    };
    assert_eq!(counts.skipped_unchanged, 1);
    assert_eq!(counts.new_count, 0);
    assert_eq!(counts.updated_count, 0);
    // The whole point: a no-op resync makes exactly one more Search and ZERO
    // FetchDesign/FetchAttachment calls beyond the first sync's.
    assert_eq!(transport.search_calls.load(Ordering::Relaxed), 2);
    assert_eq!(transport.fetch_design_calls.load(Ordering::Relaxed), 1);
    assert_eq!(transport.fetch_attachment_calls.load(Ordering::Relaxed), 0);

    std::fs::remove_file(&path).ok();
}

#[test]
fn a_changed_design_is_refetched_and_updated_in_place() {
    let (db, path) = temp_db();
    let summary_v1 = design_summary(1, "Round Brilliant", "https://example.test/1", "v1");
    let record_v1 = design_record(1, "Round Brilliant", "https://example.test/1", "v1");
    let transport_v1 = FakeTransport::new(vec![summary_v1], vec![record_v1]);
    let _ = run_mirror_sync(
        &db,
        &transport_v1,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );

    // The remote design's L/W ratio changed -- both its summary and design hashes
    // move (see `design_summary`/`design_record`'s shared `content_hash` input).
    let summary_v2 = design_summary(1, "Round Brilliant", "https://example.test/1", "v2-updated");
    let record_v2 = design_record(1, "Round Brilliant", "https://example.test/1", "v2-updated");
    let transport_v2 = FakeTransport::new(vec![summary_v2], vec![record_v2]);

    let outcome = run_mirror_sync(
        &db,
        &transport_v2,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.updated_count, 1);
    assert_eq!(counts.new_count, 0);

    let guard = db.lock().unwrap();
    let items = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    assert_eq!(
        items.len(),
        1,
        "must update the existing row, not add a second one"
    );
    assert_eq!(items[0].lw_ratio.as_deref(), Some("v2-updated"));
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn cancelling_mid_sync_leaves_earlier_designs_committed_and_the_rest_untouched() {
    let (db, path) = temp_db();
    let summaries = vec![
        design_summary(1, "First", "https://example.test/1", "v1"),
        design_summary(2, "Second", "https://example.test/2", "v1"),
        design_summary(3, "Third", "https://example.test/3", "v1"),
    ];
    let designs = vec![
        design_record(1, "First", "https://example.test/1", "v1"),
        design_record(2, "Second", "https://example.test/2", "v1"),
        design_record(3, "Third", "https://example.test/3", "v1"),
    ];
    let transport = FakeTransport::new(summaries, designs);
    let cancel = AtomicBool::new(false);

    let mut processed_count = 0;
    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &cancel,
        |progress| {
            processed_count = progress.processed;
            // Cancel right after the first design commits, before the second is
            // ever looked at.
            if progress.processed == 1 {
                cancel.store(true, Ordering::Relaxed);
            }
        },
    );
    assert_eq!(processed_count, 1);
    let MirrorOutcome::Cancelled(counts) = outcome else {
        panic!("expected Cancelled, got {outcome:?}");
    };
    assert_eq!(counts.new_count, 1);

    let guard = db.lock().unwrap();
    // Exactly one design landed -- the second and third were never even fetched
    // (FetchDesign was called exactly once), so nothing about them exists locally,
    // not even a half-written row.
    assert_eq!(guard.get_total_count().unwrap(), 1);
    assert_eq!(transport.fetch_design_calls.load(Ordering::Relaxed), 1);
    assert_eq!(*transport.fetched_entry_ids.borrow(), vec![1]);
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn an_oversized_attachment_is_skipped_but_the_design_is_still_saved() {
    let (db, path) = temp_db();
    let mut record = design_record(1, "Round Brilliant", "https://example.test/1", "v1");
    record.attachments = vec![
        AttachedFileMeta {
            id: 100,
            name: "huge.pdf".to_string(),
            url: String::new(),
            size: 1000,
        },
        AttachedFileMeta {
            id: 101,
            name: "small.pdf".to_string(),
            url: String::new(),
            size: 5,
        },
    ];
    let summary = design_summary(1, "Round Brilliant", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![summary], vec![record])
        .with_attachment(100, "huge.pdf", vec![0u8; 1000])
        .with_attachment(101, "small.pdf", vec![9, 9, 9, 9, 9]);

    let options = MirrorOptions {
        max_attachment_bytes: 500,
    };
    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        options,
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.new_count, 1, "the design itself must still be saved");
    assert_eq!(counts.attachments_fetched, 1);
    assert_eq!(counts.attachments_skipped_too_large, 1);
    assert_eq!(
        transport.fetch_attachment_calls.load(Ordering::Relaxed),
        1,
        "the oversized attachment's bytes must never even be requested"
    );

    let guard = db.lock().unwrap();
    let items = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    let full = guard.get_diagram_full(items[0].id).unwrap().unwrap();
    assert_eq!(full.attached_files.len(), 1);
    assert_eq!(full.attached_files[0].name, "small.pdf");
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn a_failed_fetch_is_counted_and_never_marked_synced() {
    let (db, path) = temp_db();
    // The summary claims entry_id 1, but the transport's `designs` map has nothing
    // for it -- simulating a design that vanished between Search and FetchDesign.
    let summary = design_summary(1, "Ghost", "https://example.test/1", "v1");
    let transport = FakeTransport::new(vec![summary], Vec::new());

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.failed, 1);
    assert_eq!(counts.new_count, 0);

    let guard = db.lock().unwrap();
    assert_eq!(guard.get_total_count().unwrap(), 0);
    assert_eq!(
        guard.get_mirror_state("https://example.test/1").unwrap(),
        None
    );
    drop(guard);
    std::fs::remove_file(&path).ok();
}

/// The scenario the held-connection task exists to handle: a mid-sync connection
/// drop. In production, `LibrarySession` (see `bridge::library::client`) hides a
/// RECOVERABLE drop entirely -- it reconnects and retries the same request, so
/// `run_mirror_sync` never even sees a failure (see
/// `library_client::tests::request_with_reconnect_reconnects_once_after_a_dead_connection_and_succeeds`
/// for that half, proven with no live socket). This test covers the other half: what
/// `run_mirror_sync` itself does when a design's connection drop could NOT be
/// recovered (the reconnect attempt also failed) -- exactly what
/// `FakeTransport::with_fetch_design_failure` scripts. The sync must not abort: it
/// counts that one design as failed, leaves it exactly as it was locally (so the next
/// sync retries it, same as `a_failed_fetch_is_counted_and_never_marked_synced`), and
/// keeps going to fetch and save every OTHER design in the catalogue.
#[test]
fn a_design_whose_connection_could_not_be_recovered_is_skipped_but_the_rest_of_the_sync_completes()
{
    let (db, path) = temp_db();
    let summaries = vec![
        design_summary(1, "First", "https://example.test/1", "v1"),
        design_summary(2, "Second", "https://example.test/2", "v1"),
        design_summary(3, "Third", "https://example.test/3", "v1"),
    ];
    let designs = vec![
        design_record(1, "First", "https://example.test/1", "v1"),
        design_record(2, "Second", "https://example.test/2", "v1"),
        design_record(3, "Third", "https://example.test/3", "v1"),
    ];
    let transport = FakeTransport::new(summaries, designs).with_fetch_design_failure(2);

    let mut processed_count = 0;
    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |progress| processed_count = progress.processed,
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!(
            "an unrecoverable connection drop for ONE design must not abort the whole \
             sync, got {outcome:?}"
        );
    };
    assert_eq!(
        processed_count, 3,
        "every design was still examined, including after the drop"
    );
    assert_eq!(counts.total_found, 3);
    assert_eq!(
        counts.new_count, 2,
        "designs 1 and 3 still land despite design 2's failure"
    );
    assert_eq!(counts.failed, 1);

    let guard = db.lock().unwrap();
    assert_eq!(guard.get_total_count().unwrap(), 2);
    let items = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    let titles: std::collections::HashSet<&str> = items.iter().map(|i| i.title.as_str()).collect();
    assert!(titles.contains("First"));
    assert!(titles.contains("Third"));
    assert!(
        !titles.contains("Second"),
        "the design whose connection could not be recovered must never be half-saved, \
         titles were: {titles:?}"
    );
    assert_eq!(
        guard.get_mirror_state("https://example.test/2").unwrap(),
        None,
        "never marked synced, so the next sync retries it -- same as any other failed fetch"
    );
    drop(guard);
    std::fs::remove_file(&path).ok();
}

#[test]
fn mirror_source_id_is_distinct_per_worker_address() {
    let a = WorkerSettings {
        address: "10.0.0.5:9443".to_string(),
        ..WorkerSettings::default()
    };
    let b = WorkerSettings {
        address: "10.0.0.6:9443".to_string(),
        ..WorkerSettings::default()
    };
    assert_ne!(mirror_source_id(&a), mirror_source_id(&b));
}

#[test]
fn a_multi_page_mirror_reaches_designs_beyond_the_first_page() {
    let (db, path) = temp_db();
    let entries: Vec<(i64, &str)> = vec![
        (1, "First"),
        (2, "Second"),
        (3, "Third"),
        (4, "Fourth"),
        (5, "Fifth"),
    ];
    let summaries: Vec<DesignSummary> = entries
        .iter()
        .map(|(id, title)| design_summary(*id, title, &format!("https://example.test/{id}"), "v1"))
        .collect();
    let designs: Vec<DesignRecord> = entries
        .iter()
        .map(|(id, title)| design_record(*id, title, &format!("https://example.test/{id}"), "v1"))
        .collect();
    // 5 designs at 2 rows per SearchPage reply: pages of [1,2], [3,4], [5] -- the
    // last page is short, so exactly 3 round trips, not 5 and not 1.
    let transport = FakeTransport::new(summaries, designs).with_page_size(2);

    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(
        counts.total_found, 5,
        "every design across every page must be counted, not just the first page's"
    );
    assert_eq!(counts.new_count, 5);
    assert_eq!(transport.search_calls.load(Ordering::Relaxed), 3);
    assert_eq!(transport.fetch_design_calls.load(Ordering::Relaxed), 5);

    let guard = db.lock().unwrap();
    assert_eq!(guard.get_total_count().unwrap(), 5);
    let items = guard
        .search_diagrams(
            "",
            "All",
            "All",
            &indicatrix_vault::model::filter::RangeFilter::default(),
        )
        .unwrap();
    let titles: std::collections::HashSet<&str> = items.iter().map(|i| i.title.as_str()).collect();
    // The whole point: "Fourth" and "Fifth" sat past the first page and must have
    // actually landed locally, not just been counted.
    assert!(titles.contains("Fourth"), "titles were: {titles:?}");
    assert!(titles.contains("Fifth"), "titles were: {titles:?}");
    drop(guard);
    std::fs::remove_file(&path).ok();
}

/// "Local delete wins" must hold after the remote design CHANGES, not only while its
/// hash still matches: deleting a mirrored design tombstones its mirror state, and a
/// later pass skips the tombstoned url before fetching anything.
#[test]
fn a_locally_deleted_design_is_not_resurrected_when_the_remote_changes() {
    let (db, path) = temp_db();
    let url = "https://example.test/1";
    let first = run_mirror_sync(
        &db,
        &FakeTransport::new(
            vec![design_summary(1, "Round Brilliant", url, "v1")],
            vec![design_record(1, "Round Brilliant", url, "v1")],
        ),
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    assert!(matches!(first, MirrorOutcome::Completed(c) if c.new_count == 1));

    {
        let guard = db.lock().unwrap();
        let id = guard.diagram_entry_id_for_url(url).unwrap().unwrap();
        guard.delete_diagram_entry(id).unwrap();
    }

    // The remote design changed: its summary hash no longer matches the stored one.
    let transport = FakeTransport::new(
        vec![design_summary(1, "Round Brilliant", url, "v2-updated")],
        vec![design_record(1, "Round Brilliant", url, "v2-updated")],
    );
    let outcome = run_mirror_sync(
        &db,
        &transport,
        "remote-library:w",
        MirrorOptions::default(),
        &AtomicBool::new(false),
        |_| {},
    );
    let MirrorOutcome::Completed(counts) = outcome else {
        panic!("expected Completed, got {outcome:?}");
    };
    assert_eq!(counts.new_count, 0);
    assert_eq!(counts.updated_count, 0);
    assert_eq!(counts.failed, 0);
    assert_eq!(counts.orphaned_mirror_states, 1);
    assert_eq!(counts.skipped_deleted, 1);
    assert_eq!(
        transport.fetch_design_calls.load(Ordering::Relaxed),
        0,
        "a tombstoned design must not even be fetched"
    );

    let guard = db.lock().unwrap();
    assert_eq!(guard.get_total_count().unwrap(), 0);
    assert_eq!(guard.diagram_entry_id_for_url(url).unwrap(), None);
    let state = guard.get_mirror_state(url).unwrap().unwrap();
    assert!(state.deleted_locally, "the tombstone must survive the pass");
    drop(guard);
    std::fs::remove_file(&path).ok();
}