ic-query 0.47.4

Internet Computer query library for CloudEngine, NNS, SNS, ICRC, system canisters, and public network metadata
Documentation
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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use super::*;
use crate::ic::IcDashboardReportProvenance;
#[cfg(feature = "dashboard-host")]
use crate::{
    HostCacheError,
    ic::{IcHostError, IcNodeStatusSource, IcNodeStatusSourceData, IcSourceRequest},
    progress::IgnoreQueryProgress,
    subnet_catalog::parse_utc_timestamp_secs,
};
#[cfg(feature = "dashboard-host")]
use std::{cell::Cell, fs, path::PathBuf, time::SystemTime};

#[test]
fn raw_operational_status_classification_is_conservative() {
    for (raw, expected) in [
        ("UP", IcNodeOperationalStatus::Up),
        ("DOWN", IcNodeOperationalStatus::Down),
        ("DISABLED", IcNodeOperationalStatus::Disabled),
        ("DEGRADED", IcNodeOperationalStatus::Degraded),
        ("FUTURE_STATUS", IcNodeOperationalStatus::Unknown),
    ] {
        assert_eq!(IcNodeOperationalStatus::from_raw(raw), expected);
    }
}

#[test]
fn node_count_comparison_covers_every_ordering() {
    for (left, right, expected) in [
        (1, 2, IcNodeCountComparison::Less),
        (2, 2, IcNodeCountComparison::Equal),
        (3, 2, IcNodeCountComparison::Greater),
    ] {
        assert_eq!(IcNodeCountComparison::from_counts(left, right), expected);
    }
}

#[test]
fn all_status_views_share_one_snapshot_and_attention_filter() {
    let snapshot = fixture_snapshot();

    let nodes = ic_node_status_report_from_snapshot(&snapshot, &IcNodeStatusView::attention())
        .expect("node report");
    let subnets = ic_subnet_status_report_from_snapshot(&snapshot, &IcNodeStatusView::attention())
        .expect("Subnet report");
    let providers =
        ic_node_provider_status_report_from_snapshot(&snapshot, &IcNodeStatusView::attention())
            .expect("provider report");

    assert_eq!(nodes.returned_node_count, 2);
    assert_eq!(subnets.returned_subnet_count, 1);
    assert_eq!(providers.returned_provider_count, 2);
    let assigned_provider = providers
        .providers
        .iter()
        .find(|provider| provider.node_provider_id == "aaaaa-aa")
        .expect("assigned provider");
    assert_eq!(assigned_provider.counts.assignment_statuses.assigned.up, 1);
    assert_eq!(
        assigned_provider.unassigned_up_vs_assigned_up,
        IcNodeCountComparison::Less
    );
    assert_eq!(
        assigned_provider.unassigned_non_up_vs_assigned_non_up,
        IcNodeCountComparison::Less
    );
    assert_eq!(
        assigned_provider.counts.assignment_statuses.assigned.down,
        1
    );
    let unassigned_provider = providers
        .providers
        .iter()
        .find(|provider| provider.node_provider_id == "2vxsx-fae")
        .expect("unassigned provider");
    assert_eq!(
        unassigned_provider
            .counts
            .assignment_statuses
            .unassigned
            .degraded,
        1
    );
    assert_eq!(
        unassigned_provider.unassigned_up_vs_assigned_up,
        IcNodeCountComparison::Equal
    );
    assert_eq!(
        unassigned_provider.unassigned_non_up_vs_assigned_non_up,
        IcNodeCountComparison::Greater
    );
    assert_eq!(
        providers.unassigned_up_vs_assigned_up_provider_counts,
        IcNodeCountComparisonCounts {
            less: 1,
            equal: 1,
            greater: 0,
        }
    );
    assert_eq!(
        providers.unassigned_non_up_vs_assigned_non_up_provider_counts,
        IcNodeCountComparisonCounts {
            less: 1,
            equal: 0,
            greater: 1,
        }
    );
    assert_eq!(nodes.observation, subnets.observation);
    assert_eq!(nodes.observation, providers.observation);
}

#[test]
fn aggregate_status_views_keep_snapshot_totals_when_selecting_rows() {
    let mut snapshot = fixture_snapshot();
    snapshot.nodes.push(fixture_node(
        "r7inp-6aaaa-aaaaa-aaabq-cai",
        "UP",
        "REPLICA",
        Some("rrkah-fqaaa-aaaaa-aaaaq-cai"),
        "ryjl3-tyaaa-aaaaa-aaaba-cai",
    ));
    snapshot
        .nodes
        .sort_unstable_by(|left, right| left.node_id.cmp(&right.node_id));
    snapshot.node_count = snapshot.nodes.len();
    snapshot.counts = node_status_group_counts(snapshot.nodes.iter());
    let all = IcNodeStatusView::attention().with_all(true);
    let all_subnets = ic_subnet_status_report_from_snapshot(&snapshot, &all).expect("all Subnets");
    let all_providers =
        ic_node_provider_status_report_from_snapshot(&snapshot, &all).expect("all providers");
    assert_eq!(all_subnets.subnet_count, 2);
    assert_eq!(all_subnets.attention_subnet_count, 1);
    assert_eq!(all_providers.provider_count, 3);
    assert_eq!(all_providers.attention_provider_count, 2);
    assert_eq!(
        all_providers.unassigned_up_vs_assigned_up_provider_counts,
        IcNodeCountComparisonCounts {
            less: 2,
            equal: 1,
            greater: 0,
        }
    );
    assert_eq!(
        all_providers.unassigned_non_up_vs_assigned_non_up_provider_counts,
        IcNodeCountComparisonCounts {
            less: 1,
            equal: 1,
            greater: 1,
        }
    );

    for (view, selected_row) in [
        (IcNodeStatusView::attention(), 1),
        (IcNodeStatusView::attention().with_target("rrk"), 0),
        (IcNodeStatusView::attention().with_target("ryj"), 1),
    ] {
        let report = ic_subnet_status_report_from_snapshot(&snapshot, &view).expect("Subnet view");
        assert_eq!(report.snapshot_node_count, 4);
        assert_eq!(report.assigned_node_count, 3);
        assert_eq!(report.subnet_count, all_subnets.subnet_count);
        assert_eq!(
            report.attention_subnet_count,
            all_subnets.attention_subnet_count
        );
        assert_eq!(report.returned_subnet_count, 1);
        assert_eq!(report.subnets, [all_subnets.subnets[selected_row].clone()]);
    }
    for (view, selected_rows) in [
        (IcNodeStatusView::attention(), vec![0, 1]),
        (IcNodeStatusView::attention().with_target("ryj"), vec![2]),
        (IcNodeStatusView::attention().with_target("2v"), vec![0]),
    ] {
        let report =
            ic_node_provider_status_report_from_snapshot(&snapshot, &view).expect("provider view");
        assert_eq!(report.snapshot_node_count, 4);
        assert_eq!(report.provider_count, all_providers.provider_count);
        assert_eq!(
            report.attention_provider_count,
            all_providers.attention_provider_count
        );
        assert_eq!(
            report.unassigned_up_vs_assigned_up_provider_counts,
            all_providers.unassigned_up_vs_assigned_up_provider_counts
        );
        assert_eq!(
            report.unassigned_non_up_vs_assigned_non_up_provider_counts,
            all_providers.unassigned_non_up_vs_assigned_non_up_provider_counts
        );
        assert_eq!(report.returned_provider_count, selected_rows.len());
        let expected = selected_rows
            .into_iter()
            .map(|index| all_providers.providers[index].clone())
            .collect::<Vec<_>>();
        assert_eq!(report.providers, expected);
    }
}

#[test]
fn status_text_separates_preambles_and_tables() {
    let snapshot = fixture_snapshot();
    let view = IcNodeStatusView::attention().with_all(true);
    let nodes = ic_node_status_report_from_snapshot(&snapshot, &view).expect("node report");
    let subnets = ic_subnet_status_report_from_snapshot(&snapshot, &view).expect("Subnet report");
    let providers =
        ic_node_provider_status_report_from_snapshot(&snapshot, &view).expect("provider report");
    let node_text = ic_node_status_report_text(&nodes);
    let subnet_text = ic_subnet_status_report_text(&subnets);
    let provider_text = ic_node_provider_status_report_text(&providers);

    assert!(
        node_text.contains("unknown=0/0/0\n\nNODE"),
        "node preamble must be visually separate from its table"
    );
    assert!(
        subnet_text.contains("assigned_nodes=2\n\nSUBNET"),
        "Subnet preamble must be visually separate from its table"
    );
    assert!(
        subnet_text.contains("\n\nnon-up node evidence:\nNODE"),
        "later evidence must be a separate visual section"
    );
    assert!(
        provider_text.contains("non_up=1/0/1\n\nNODE PROVIDER"),
        "provider preamble must be visually separate from its table"
    );
    assert!(provider_text.contains("UNASN VS ASN UP/NON-UP"));
    assert!(provider_text.contains("less/less"));
    assert!(provider_text.contains("equal/greater"));
}

#[test]
fn subnet_threshold_reports_down_and_conservative_non_up_distance_separately() {
    let report = ic_subnet_status_report_from_snapshot(
        &fixture_snapshot(),
        &IcNodeStatusView::attention().with_all(true),
    )
    .expect("Subnet report");
    let subnet = report.subnets.first().expect("one assigned Subnet");

    assert_eq!(subnet.statuses.total, 2);
    assert_eq!(subnet.fault_tolerance_node_count, 0);
    assert_eq!(subnet.additional_down_nodes_to_exceed_fault_tolerance, 0);
    assert_eq!(subnet.additional_non_up_nodes_to_exceed_fault_tolerance, 0);
    assert!(subnet.down_fault_tolerance_exceeded);
    assert!(subnet.conservative_non_up_fault_tolerance_exceeded);
}

#[test]
fn target_resolution_supports_unique_prefixes_and_rejects_ambiguity() {
    let snapshot = fixture_snapshot();
    let selected = ic_node_status_report_from_snapshot(
        &snapshot,
        &IcNodeStatusView::attention().with_target("ryj"),
    )
    .expect("unique prefix");
    assert_eq!(selected.returned_node_count, 1);
    assert_eq!(selected.nodes[0].status, "UP");

    let ambiguous = ic_node_status_report_from_snapshot(
        &snapshot,
        &IcNodeStatusView::attention().with_target("r"),
    )
    .expect_err("shared prefix is ambiguous");
    assert!(matches!(
        ambiguous,
        IcNodeStatusProjectionError::AmbiguousTarget { prefix, matches, .. }
            if prefix == "r" && matches.len() == 2
    ));
}

#[test]
fn pure_projections_reject_invalid_observation_provenance() {
    let view = IcNodeStatusView::attention().with_all(true);
    for field in [
        "schema_version",
        "network",
        "authority",
        "certified",
        "point_in_time_guaranteed",
        "source_endpoint",
        "fetched_at",
        "fetched_by",
        "cloud_engine_nodes_included",
    ] {
        let mut snapshot = fixture_snapshot();
        let source = &mut snapshot.observation.source;
        match field {
            "schema_version" => source.schema_version = 99,
            "network" => source.network = "other".to_string(),
            "authority" => source.authority = "other".to_string(),
            "certified" => source.certified = true,
            "point_in_time_guaranteed" => source.point_in_time_guaranteed = true,
            "source_endpoint" => source.source_endpoint = "invalid".to_string(),
            "fetched_at" => source.fetched_at = "invalid".to_string(),
            "fetched_by" => source.fetched_by.clear(),
            "cloud_engine_nodes_included" => {
                snapshot.observation.cloud_engine_nodes_included = true;
            }
            _ => unreachable!("fixture field"),
        }
        for result in [
            ic_node_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
            ic_subnet_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
            ic_node_provider_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
        ] {
            assert!(
                matches!(
                    result,
                    Err(IcNodeStatusProjectionError::InvalidSnapshot { .. })
                ),
                "invalid {field}: {result:?}"
            );
        }
    }
}

#[test]
fn pure_projections_reject_duplicate_or_unordered_snapshot_rows() {
    let mut duplicate = fixture_snapshot();
    duplicate.nodes[1].node_id = duplicate.nodes[0].node_id.clone();
    let mut unordered = fixture_snapshot();
    unordered.nodes.swap(0, 1);
    let view = IcNodeStatusView::attention().with_all(true);

    for snapshot in [duplicate, unordered] {
        for result in [
            ic_node_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
            ic_subnet_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
            ic_node_provider_status_report_from_snapshot(&snapshot, &view).map(|_| ()),
        ] {
            assert!(matches!(
                result,
                Err(IcNodeStatusProjectionError::InvalidSnapshot { .. })
            ));
        }
    }
}

#[test]
fn pure_projections_reject_invalid_raw_relation_evidence() {
    let mut snapshot = fixture_snapshot();
    snapshot.nodes[0].node_type = "UNASSIGNED".to_string();

    let error = ic_subnet_status_report_from_snapshot(
        &snapshot,
        &IcNodeStatusView::attention().with_all(true),
    )
    .expect_err("assigned UNASSIGNED node must be rejected");

    assert!(matches!(
        error,
        IcNodeStatusProjectionError::InvalidSnapshot { reason }
            if reason.contains("assigned subnet evidence")
    ));

    let mut invalid_scope = fixture_snapshot();
    invalid_scope.observation.cloud_engine_nodes_included = true;
    let scope_error = ic_node_status_report_from_snapshot(
        &invalid_scope,
        &IcNodeStatusView::attention().with_all(true),
    )
    .expect_err("unsupported source scope must be rejected");
    assert!(matches!(
        scope_error,
        IcNodeStatusProjectionError::InvalidSnapshot { reason }
            if reason.contains("default mainnet node scope")
    ));
}

#[cfg(feature = "dashboard-host")]
#[test]
fn non_mainnet_refresh_fails_before_calling_the_source() {
    let source = FixtureSource::default();
    let request = IcNodeStatusRefreshRequest::new(
        temp_dir("ic-node-status-network"),
        "local",
        "https://example.test/api/v3",
        fixture_now(),
        DEFAULT_IC_NODE_STATUS_REFRESH_LOCK_STALE_SECONDS,
    );

    let error = refresh_ic_node_status_snapshot_with_source(&request, &source)
        .expect_err("local network is unsupported");

    assert!(matches!(
        error,
        IcNodeStatusHostError::UnsupportedNetwork { network } if network == "local"
    ));
    assert_eq!(source.calls.get(), 0);
}

#[cfg(feature = "dashboard-host")]
#[test]
fn stale_reads_reuse_fresh_cache_and_refresh_expired_cache() {
    let root = temp_dir("ic-node-status-stale");
    let source = FixtureSource::default();
    let now = fixture_now();
    let request = refresh_request(&root, now);
    let mut events = Vec::new();
    let mut progress = |event| events.push(event);

    let initial =
        load_or_refresh_stale_ic_node_status_snapshot_with_source(&request, &source, &mut progress)
            .expect("missing cache refreshes");
    assert_eq!(initial.node_count, 1);
    assert_eq!(source.calls.get(), 1);

    let fresh_request = refresh_request(&root, now + DEFAULT_IC_NODE_STATUS_STALE_AFTER_SECONDS);
    load_or_refresh_stale_ic_node_status_snapshot_with_source(
        &fresh_request,
        &source,
        &mut progress,
    )
    .expect("cache at threshold remains fresh");
    assert_eq!(source.calls.get(), 1);

    let stale_request =
        refresh_request(&root, now + DEFAULT_IC_NODE_STATUS_STALE_AFTER_SECONDS + 1);
    let stale = load_or_refresh_stale_ic_node_status_snapshot_with_source(
        &stale_request,
        &source,
        &mut progress,
    )
    .expect("expired cache refreshes");
    assert_eq!(source.calls.get(), 2);
    assert_eq!(
        stale.observation.cache.expect("cache evidence").age_seconds,
        0
    );
    assert_eq!(events.len(), 2);
    assert!(events.iter().all(|event| matches!(
        event,
        crate::QueryProgressEvent::CacheRefresh { component, .. }
            if component == "IC node status"
    )));

    fs::remove_dir_all(root).expect("remove fixture cache");
}

#[cfg(feature = "dashboard-host")]
#[test]
fn malformed_cache_recovers_while_strict_load_remains_typed() {
    let root = temp_dir("ic-node-status-invalid");
    let source = FixtureSource::default();
    let now = fixture_now();
    let request = refresh_request(&root, now);
    let cache_path = ic_node_status_cache_path(&root, "ic");
    crate::cache_file::write_managed_text_atomically(&root, &cache_path, "not-json")
        .expect("write malformed cache");

    let strict = load_cached_ic_node_status_snapshot(&request.cache, now)
        .expect_err("strict load rejects malformed cache");
    assert!(matches!(
        strict,
        IcNodeStatusHostError::Cache(HostCacheError::ParseCache { .. })
    ));

    let mut progress = IgnoreQueryProgress;
    let recovered = load_or_refresh_missing_ic_node_status_snapshot_with_source(
        &request,
        &source,
        &mut progress,
    )
    .expect("read-through policy repairs malformed cache");
    assert_eq!(recovered.node_count, 1);
    assert_eq!(source.calls.get(), 1);

    fs::remove_dir_all(root).expect("remove fixture cache");
}

#[cfg(feature = "dashboard-host")]
#[test]
fn noncanonical_cache_order_is_invalid_and_read_through_repairs_it() {
    let root = temp_dir("ic-node-status-cache-order");
    let now = fixture_now();
    let request = refresh_request(&root, now);
    let source = RowsSource {
        nodes: fixture_snapshot().nodes,
    };
    refresh_ic_node_status_snapshot_with_source(&request, &source).expect("create cache");
    let cache_path = ic_node_status_cache_path(&root, "ic");
    let mut cache: serde_json::Value =
        serde_json::from_slice(&fs::read(&cache_path).expect("read fixture cache"))
            .expect("parse fixture cache");
    let nodes = cache["nodes"].as_array_mut().expect("cached node rows");
    nodes.swap(0, 1);
    fs::write(
        &cache_path,
        serde_json::to_vec_pretty(&cache).expect("serialize reordered cache"),
    )
    .expect("write reordered cache");

    let strict = load_cached_ic_node_status_snapshot(&request.cache, now)
        .expect_err("strict load rejects noncanonical cache ordering");
    assert!(matches!(
        strict,
        IcNodeStatusHostError::InvalidCache { reason, .. }
            if reason.contains("strict canonical node-id order")
    ));

    let repair_source = FixtureSource::default();
    let mut progress = IgnoreQueryProgress;
    let repaired = load_or_refresh_missing_ic_node_status_snapshot_with_source(
        &request,
        &repair_source,
        &mut progress,
    )
    .expect("read-through repairs noncanonical cache ordering");
    assert_eq!(repaired.node_count, 1);
    assert_eq!(repair_source.calls.get(), 1);

    fs::remove_dir_all(root).expect("remove fixture cache");
}

#[cfg(feature = "dashboard-host")]
#[test]
fn invalid_cached_provenance_is_strictly_rejected_and_read_through_refreshes() {
    let root = temp_dir("ic-node-status-cache-provenance");
    let now = fixture_now();
    let request = refresh_request(&root, now);
    let source = FixtureSource::default();
    refresh_ic_node_status_snapshot_with_source(&request, &source).expect("create cache");
    let cache_path = ic_node_status_cache_path(&root, "ic");
    let valid_cache: serde_json::Value =
        serde_json::from_slice(&fs::read(&cache_path).expect("read fixture cache"))
            .expect("parse fixture cache");

    for (field, value) in [
        ("certified", serde_json::json!(true)),
        ("point_in_time_guaranteed", serde_json::json!(true)),
        ("authority", serde_json::json!("other")),
        ("source_endpoint", serde_json::json!("invalid")),
        ("fetched_at", serde_json::json!("invalid")),
        ("fetched_at", serde_json::json!("2099-01-01T00:00:00Z")),
        ("fetched_by", serde_json::json!("")),
        ("cloud_engine_nodes_included", serde_json::json!(true)),
    ] {
        let mut invalid_cache = valid_cache.clone();
        invalid_cache[field] = value;
        let bytes = serde_json::to_vec_pretty(&invalid_cache).expect("serialize invalid cache");
        fs::write(&cache_path, &bytes).expect("write invalid cache");
        let strict = load_cached_ic_node_status_snapshot(&request.cache, now);
        assert!(
            matches!(strict, Err(IcNodeStatusHostError::InvalidCache { .. })),
            "invalid {field}: {strict:?}"
        );
        assert_eq!(fs::read(&cache_path).expect("read retained cache"), bytes);

        let repair_source = FixtureSource::default();
        let mut progress = IgnoreQueryProgress;
        let repaired = load_or_refresh_missing_ic_node_status_snapshot_with_source(
            &request,
            &repair_source,
            &mut progress,
        )
        .expect("read-through refreshes invalid observation");
        assert_eq!(repair_source.calls.get(), 1);
        assert_eq!(repaired.node_count, 1);
        assert!(!repaired.observation.source.certified);
        assert!(!repaired.observation.source.point_in_time_guaranteed);
        assert!(
            repaired
                .observation
                .cache
                .expect("cache evidence")
                .cache_fresh
        );
    }

    let retained = fs::read(&cache_path).expect("read complete cache");
    let failed_refresh =
        refresh_ic_node_status_snapshot_with_source(&request, &RowsSource { nodes: Vec::new() });
    assert!(matches!(
        failed_refresh,
        Err(IcNodeStatusHostError::Source(
            IcHostError::InvalidSourceData { .. }
        ))
    ));
    assert_eq!(
        fs::read(&cache_path).expect("read retained complete cache"),
        retained
    );
    fs::remove_dir_all(root).expect("remove fixture cache");
}

#[cfg(feature = "dashboard-host")]
#[test]
fn forced_refresh_reports_atomic_replacement() {
    let root = temp_dir("ic-node-status-force");
    let source = FixtureSource::default();
    let request = refresh_request(&root, fixture_now());

    let created = refresh_ic_node_status_snapshot_with_source(&request, &source)
        .expect("create complete cache");
    let replaced = refresh_ic_node_status_snapshot_with_source(&request, &source)
        .expect("replace complete cache");

    assert!(!created.replaced_existing_cache);
    assert!(replaced.replaced_existing_cache);
    assert_eq!(source.calls.get(), 2);
    assert_eq!(
        load_cached_ic_node_status_snapshot(&request.cache, request.now_unix_secs)
            .expect("strictly load replacement")
            .node_count,
        1
    );

    fs::remove_dir_all(root).expect("remove fixture cache");
}

#[cfg(feature = "dashboard-host")]
#[test]
fn custom_source_rows_are_sorted_and_preserve_unknown_status() {
    let source = RowsSource {
        nodes: vec![
            fixture_node(
                "rrkah-fqaaa-aaaaa-aaaaq-cai",
                "FUTURE_STATUS",
                "UNASSIGNED",
                None,
                "2vxsx-fae",
            ),
            fixture_node(
                "aaaaa-aa",
                "UP",
                "REPLICA",
                Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
                "aaaaa-aa",
            ),
        ],
    };
    let request = IcNodeStatusSnapshotRequest::new("https://example.test/api/v3", fixture_now());

    let snapshot = crate::ic::build_ic_node_status_snapshot_with_source(&request, &source)
        .expect("valid custom snapshot");

    assert_eq!(snapshot.nodes[0].node_id, "aaaaa-aa");
    assert_eq!(snapshot.counts.statuses.unknown, 1);
    assert_eq!(snapshot.counts.statuses.up, 1);
}

#[cfg(feature = "dashboard-host")]
#[test]
fn custom_source_rejects_duplicate_nodes_and_inconsistent_provider_names() {
    let request = IcNodeStatusSnapshotRequest::new("https://example.test/api/v3", fixture_now());
    let duplicate = fixture_node(
        "aaaaa-aa",
        "UP",
        "REPLICA",
        Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
        "2vxsx-fae",
    );
    let duplicate_error = crate::ic::build_ic_node_status_snapshot_with_source(
        &request,
        &RowsSource {
            nodes: vec![duplicate.clone(), duplicate],
        },
    )
    .expect_err("duplicate node id");
    assert!(matches!(
        duplicate_error,
        IcHostError::InvalidSourceData { .. }
    ));

    let mut conflicting = fixture_node(
        "rrkah-fqaaa-aaaaa-aaaaq-cai",
        "UP",
        "UNASSIGNED",
        None,
        "2vxsx-fae",
    );
    conflicting.node_provider_name = "Conflicting provider name".to_string();
    let provider_error = crate::ic::build_ic_node_status_snapshot_with_source(
        &request,
        &RowsSource {
            nodes: vec![
                fixture_node(
                    "aaaaa-aa",
                    "UP",
                    "REPLICA",
                    Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
                    "2vxsx-fae",
                ),
                conflicting,
            ],
        },
    )
    .expect_err("provider name conflict");
    assert!(matches!(
        provider_error,
        IcHostError::InvalidSourceData { .. }
    ));
}

#[cfg(feature = "dashboard-host")]
#[test]
fn custom_source_rejects_invalid_principals_assignment_and_scope_evidence() {
    let request = IcNodeStatusSnapshotRequest::new("https://example.test/api/v3", fixture_now());
    let mut invalid_principal = fixture_node(
        "aaaaa-aa",
        "UP",
        "REPLICA",
        Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
        "2vxsx-fae",
    );
    invalid_principal.node_id = "not-a-principal".to_string();
    let contradictory = fixture_node(
        "aaaaa-aa",
        "UP",
        "UNASSIGNED",
        Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
        "2vxsx-fae",
    );
    let mut cloud_engine = fixture_node(
        "aaaaa-aa",
        "UP",
        "REPLICA",
        Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
        "2vxsx-fae",
    );
    cloud_engine.cloud_engine_subnet_id = Some("rrkah-fqaaa-aaaaa-aaaaq-cai".to_string());

    for node in [invalid_principal, contradictory, cloud_engine] {
        let error = crate::ic::build_ic_node_status_snapshot_with_source(
            &request,
            &RowsSource { nodes: vec![node] },
        )
        .expect_err("invalid source row");
        assert!(matches!(error, IcHostError::InvalidSourceData { .. }));
    }
}

#[cfg(feature = "dashboard-host")]
#[test]
fn custom_source_rejects_rows_above_the_fixed_ceiling() {
    let row = fixture_node(
        "aaaaa-aa",
        "UP",
        "REPLICA",
        Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
        "2vxsx-fae",
    );
    let row_count = usize::try_from(MAX_IC_NODE_STATUS_ROWS).expect("row ceiling") + 1;
    let request = IcNodeStatusSnapshotRequest::new("https://example.test/api/v3", fixture_now());

    let error = crate::ic::build_ic_node_status_snapshot_with_source(
        &request,
        &RowsSource {
            nodes: vec![row; row_count],
        },
    )
    .expect_err("oversized source collection");

    assert!(matches!(error, IcHostError::InvalidSourceData { .. }));
}

#[cfg(feature = "dashboard-host")]
#[test]
fn custom_source_rejects_an_empty_mainnet_snapshot() {
    let request = IcNodeStatusSnapshotRequest::new("https://example.test/api/v3", fixture_now());

    let error = crate::ic::build_ic_node_status_snapshot_with_source(
        &request,
        &RowsSource { nodes: Vec::new() },
    )
    .expect_err("empty mainnet snapshot");

    assert!(matches!(
        error,
        IcHostError::InvalidSourceData { reason }
            if reason.contains("at least one row")
    ));
}

fn fixture_snapshot() -> IcNodeStatusSnapshot {
    let subnet_id = "ryjl3-tyaaa-aaaaa-aaaba-cai";
    let mut nodes = vec![
        fixture_node("aaaaa-aa", "DOWN", "REPLICA", Some(subnet_id), "aaaaa-aa"),
        fixture_node(
            "ryjl3-tyaaa-aaaaa-aaaba-cai",
            "UP",
            "REPLICA",
            Some(subnet_id),
            "aaaaa-aa",
        ),
        fixture_node(
            "rrkah-fqaaa-aaaaa-aaaaq-cai",
            "DEGRADED",
            "UNASSIGNED",
            None,
            "2vxsx-fae",
        ),
    ];
    nodes.sort_unstable_by(|left, right| left.node_id.cmp(&right.node_id));
    let counts = node_status_group_counts(nodes.iter());
    IcNodeStatusSnapshot {
        observation: IcNodeStatusObservation {
            source: IcDashboardReportProvenance {
                schema_version: IC_NODE_STATUS_SCHEMA_VERSION,
                network: "ic".to_string(),
                authority: "official_ic_dashboard_api".to_string(),
                source_endpoint: "https://example.test/api/v3".to_string(),
                fetched_at: "2026-08-04T12:00:00Z".to_string(),
                fetched_by: "fixture".to_string(),
                certified: false,
                point_in_time_guaranteed: false,
            },
            scope: IcNodeStatusScope::DashboardMainnetDefault,
            cloud_engine_nodes_included: false,
            cache: None,
        },
        node_count: 3,
        counts,
        nodes,
    }
}

fn fixture_node(
    node_id: &str,
    status: &str,
    node_type: &str,
    subnet_id: Option<&str>,
    node_provider_id: &str,
) -> IcNodeStatusRow {
    IcNodeStatusRow {
        node_id: node_id.to_string(),
        node_operator_id: "ryjl3-tyaaa-aaaaa-aaaba-cai".to_string(),
        node_provider_id: node_provider_id.to_string(),
        node_provider_name: format!("Provider {node_provider_id}"),
        node_type: node_type.to_string(),
        node_reward_type: "Type3".to_string(),
        status: status.to_string(),
        alert_name: (status != "UP").then(|| "fixture alert".to_string()),
        subnet_id: subnet_id.map(str::to_string),
        cloud_engine_subnet_id: None,
        data_center_id: "dc1".to_string(),
        data_center_name: "Data center".to_string(),
        owner: "Owner".to_string(),
        region: "Europe,FR".to_string(),
        guestos_version: Some("version".to_string()),
        guestos_tee_active: Some(false),
        ip_address: None,
        ipv4_connectivity_status: Some(true),
        node_hardware_generation: None,
    }
}

#[cfg(feature = "dashboard-host")]
#[derive(Default)]
struct FixtureSource {
    calls: Cell<usize>,
}

#[cfg(feature = "dashboard-host")]
struct RowsSource {
    nodes: Vec<IcNodeStatusRow>,
}

#[cfg(feature = "dashboard-host")]
impl IcNodeStatusSource for RowsSource {
    fn fetch_node_status_snapshot(
        &self,
        request: &IcSourceRequest,
    ) -> Result<IcNodeStatusSourceData, IcHostError> {
        Ok(IcNodeStatusSourceData {
            source: request.clone(),
            scope: IcNodeStatusScope::DashboardMainnetDefault,
            cloud_engine_nodes_included: false,
            nodes: self.nodes.clone(),
        })
    }
}

#[cfg(feature = "dashboard-host")]
impl IcNodeStatusSource for FixtureSource {
    fn fetch_node_status_snapshot(
        &self,
        request: &IcSourceRequest,
    ) -> Result<IcNodeStatusSourceData, IcHostError> {
        self.calls.set(self.calls.get() + 1);
        Ok(IcNodeStatusSourceData {
            source: request.clone(),
            scope: IcNodeStatusScope::DashboardMainnetDefault,
            cloud_engine_nodes_included: false,
            nodes: vec![fixture_node(
                "aaaaa-aa",
                "DOWN",
                "REPLICA",
                Some("ryjl3-tyaaa-aaaaa-aaaba-cai"),
                "2vxsx-fae",
            )],
        })
    }
}

#[cfg(feature = "dashboard-host")]
fn refresh_request(root: &std::path::Path, now_unix_secs: u64) -> IcNodeStatusRefreshRequest {
    IcNodeStatusRefreshRequest::new(
        root,
        "ic",
        "https://example.test/api/v3",
        now_unix_secs,
        DEFAULT_IC_NODE_STATUS_REFRESH_LOCK_STALE_SECONDS,
    )
}

#[cfg(feature = "dashboard-host")]
fn fixture_now() -> u64 {
    parse_utc_timestamp_secs("2026-08-04T12:00:00Z").expect("fixture timestamp")
}

#[cfg(feature = "dashboard-host")]
fn temp_dir(label: &str) -> PathBuf {
    let nonce = SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock")
        .as_nanos();
    std::env::temp_dir().join(format!("{label}-{nonce}"))
}