ic-query 0.50.0

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
use super::{fixtures::*, *};
use crate::cache_file::{CacheFileError, HostCacheError};
use crate::nns::{LiveNnsSource, NnsSourceRequest};
#[cfg(unix)]
use std::os::unix::fs::symlink;
use std::{
    future::Future,
    sync::atomic::{AtomicUsize, Ordering},
    task::{Context, Poll},
};

struct PendingSource;

impl SubnetCatalogSource for PendingSource {
    fn fetch_catalog<'a>(
        &'a self,
        _request: &'a NnsSourceRequest,
    ) -> SubnetCatalogSourceFuture<'a> {
        Box::pin(std::future::pending())
    }
}

struct WrongEndpointSource;

impl SubnetCatalogSource for WrongEndpointSource {
    fn fetch_catalog<'a>(
        &'a self,
        _request: &'a NnsSourceRequest,
    ) -> SubnetCatalogSourceFuture<'a> {
        Box::pin(async { Ok(fixture_catalog()) })
    }
}

#[test]
fn refresh_exports_protect_a_live_sources_separate_history_root_before_collection() {
    let root = temp_dir("ic-query-catalog-separate-history-export");
    let history_root = temp_dir("ic-query-catalog-source-history-export");
    let source =
        LiveSubnetCatalogSource::with_progress(|_| panic!("export rejected before collection"))
            .with_history_cache(&history_root);
    let paths: [_; 2] = source
        .history_cache_paths()
        .expect("configured history paths")
        .into();
    for output in paths {
        crate::cache_file::write_managed_text_atomically(
            &history_root,
            output,
            "preserved evidence",
        )
        .expect("seed protected bytes");
        let mut request = refresh_request(&root);
        request.output_path = Some(output.to_path_buf());
        for dry_run in [true, false] {
            request.dry_run = dry_run;
            let error = refresh_subnet_catalog_with_source(&request, &source)
                .expect_err("source-owned history export alias");
            assert!(matches!(
                error,
                SubnetCatalogHostError::Cache(HostCacheError::Operation {
                    source: CacheFileError::OutputAliasesManagedPath { .. },
                    ..
                })
            ));
            assert_eq!(
                fs::read_to_string(output).expect("protected bytes"),
                "preserved evidence"
            );
            assert!(!subnet_catalog_refresh_lock_path(&root, "ic").exists());
        }
    }
    assert!(!root.exists());
    fs::remove_dir_all(history_root).expect("cleanup history root");
}

#[test]
fn live_catalog_source_rejects_non_mainnet_before_agent_construction() {
    let request = NnsSourceRequest::new(
        "local",
        "not a valid replica endpoint",
        "2026-07-29T00:00:00Z",
        "test",
    );

    let error = crate::runtime::block_on_current_thread(LiveNnsSource.fetch_catalog(&request))
        .expect("test runtime")
        .expect_err("unsupported network");

    assert!(matches!(
        error,
        SubnetCatalogHostError::UnsupportedNetwork { network } if network == "local"
    ));
}

#[test]
fn public_async_catalog_fetch_rejects_non_mainnet_before_agent_construction() {
    let request = NnsSourceRequest::new(
        "local",
        "not a valid replica endpoint",
        "2026-07-29T00:00:00Z",
        "test",
    );

    let error = crate::runtime::block_on_current_thread(fetch_subnet_catalog_async(&request))
        .expect("test runtime")
        .expect_err("unsupported network");

    assert!(matches!(
        error,
        SubnetCatalogHostError::UnsupportedNetwork { network } if network == "local"
    ));
}

#[test]
fn refresh_writes_catalog_atomically_and_removes_lock() {
    let root = temp_dir("ic-query-subnet-refresh");
    let mut catalog = fixture_catalog();
    catalog.provenance.registry_version = 987_654;
    catalog.provenance.fetched_at = "1970-01-01T00:00:00Z".to_string();
    catalog.provenance.source_endpoints = vec![DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT.to_string()];
    catalog.canonicalize_and_seal().expect("reseal fixture");
    let source = FixtureRefreshSource::ok(catalog);
    let request = refresh_request(&root);

    let report = refresh_subnet_catalog_with_source(&request, &source).expect("refresh catalog");
    let cached =
        load_cached_subnet_catalog(&cache_only_load_request(&root)).expect("cached catalog");
    let lock_path = PathBuf::from(&report.refresh_lock_path);
    assert_eq!(
        fs::read(&report.catalog_path).expect("read published catalog bytes"),
        catalog_to_pretty_json(cached.catalog.raw())
            .expect("pretty catalog JSON")
            .into_bytes(),
    );

    let _ = fs::remove_dir_all(root);
    assert!(report.wrote_catalog);
    assert!(!report.replaced_existing_catalog);
    assert_eq!(report.registry_version, 987_654);
    assert_eq!(report.assurance, CatalogAssurance::UncertifiedQuery);
    assert!(report.agreement_digest.is_none());
    assert_eq!(report.registry_query_call_count, 5);
    assert_eq!(
        report.source_endpoints,
        vec![DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT.to_string()]
    );
    assert_eq!(report.catalog_digest, cached.catalog.raw().catalog_digest);
    assert_eq!(cached.catalog.provenance().registry_version, 987_654);
    assert!(!lock_path.exists());
}

#[test]
fn async_multi_endpoint_refresh_publishes_matching_agreement_evidence() {
    let root = temp_dir("ic-query-subnet-refresh-agreement");
    let alpha = "https://alpha.example";
    let beta = "https://beta.example";
    let source = AgreementFixtureSource::new(AgreementFixtureMode::Matching, beta);
    let mut request = refresh_request(&root);
    request.source =
        CatalogSourceSelection::multi_endpoint_agreement(vec![beta.to_string(), alpha.to_string()]);

    let report =
        futures::executor::block_on(refresh_subnet_catalog_with_source_async(&request, &source))
            .expect("matching endpoints refresh");
    let cached =
        load_cached_subnet_catalog(&cache_only_load_request(&root)).expect("agreement cache");

    assert_eq!(source.call_count(), 2);
    assert_eq!(report.assurance, CatalogAssurance::MultiEndpointAgreement);
    assert_eq!(
        report.source_endpoints,
        vec![alpha.to_string(), beta.to_string()]
    );
    assert_eq!(report.registry_query_call_count, 10);
    assert_eq!(report.registry_records.len(), 8);
    assert!(report.registry_records.iter().all(|evidence| {
        evidence.requested_registry_version == report.registry_version
            && report.source_endpoints.contains(&evidence.source_endpoint)
    }));
    assert_eq!(
        report.agreement_digest,
        cached.catalog.provenance().agreement_digest
    );
    assert!(report.agreement_digest.is_some());
    assert_eq!(
        cached.catalog.provenance().assurance,
        CatalogAssurance::MultiEndpointAgreement
    );
    let _ = fs::remove_dir_all(root);
}

#[test]
fn detailed_agreement_mismatch_retains_every_completed_endpoint_record() {
    let root = temp_dir("ic-query-subnet-detailed-agreement-mismatch");
    let alpha = "https://alpha.example";
    let beta = "https://beta.example";
    let source = AgreementFixtureSource::new(AgreementFixtureMode::PayloadMismatch, beta);
    let request = SubnetCatalogLoadRequest::cache_only(cache_request(&root), 1_780_531_300)
        .with_policy(CatalogReadPolicy::ForceRefresh {
            source: CatalogSourceSelection::multi_endpoint_agreement(vec![
                alpha.to_string(),
                beta.to_string(),
            ]),
        });

    let failure = futures::executor::block_on(load_subnet_catalog_detailed_with_source_async(
        &request, &source,
    ))
    .expect_err("mismatched endpoint evidence");

    assert_eq!(failure.stage, SubnetCatalogLoadStage::RefreshFailed);
    assert_eq!(failure.registry_records.len(), 8);
    assert!(
        failure.registry_records.iter().all(|evidence| {
            evidence.source_endpoint == alpha || evidence.source_endpoint == beta
        })
    );
    assert!(!subnet_catalog_path(&root, MAINNET_NETWORK).exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn agreement_rejects_version_and_payload_mismatch_without_publishing() {
    for (name, mode) in [
        ("version", AgreementFixtureMode::VersionMismatch),
        ("payload", AgreementFixtureMode::PayloadMismatch),
    ] {
        let root = temp_dir(&format!("ic-query-subnet-agreement-{name}"));
        write_catalog(&root, fixture_catalog());
        let beta = "https://beta.example";
        let source = AgreementFixtureSource::new(mode, beta);
        let mut request = refresh_request(&root);
        request.source = CatalogSourceSelection::multi_endpoint_agreement(vec![
            "https://alpha.example".to_string(),
            beta.to_string(),
        ]);

        let error = futures::executor::block_on(refresh_subnet_catalog_with_source_async(
            &request, &source,
        ))
        .expect_err("mismatched endpoint evidence");
        let cached =
            load_cached_subnet_catalog(&cache_only_load_request(&root)).expect("original cache");

        assert!(matches!(
            error,
            SubnetCatalogHostError::AgreementMismatch { endpoint, .. } if endpoint == beta
        ));
        assert_eq!(cached.catalog.provenance().registry_version, 123_456);
        assert!(!subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK).exists());
        let _ = fs::remove_dir_all(root);
    }
}

#[test]
fn invalid_agreement_selection_is_rejected_before_source_or_cache_io() {
    for endpoints in [
        vec![
            "https://same.example".to_string(),
            "https://same.example:8443".to_string(),
        ],
        vec!["https://only.example".to_string()],
        vec![
            "https://one.example".to_string(),
            "https://two.example".to_string(),
            "https://three.example".to_string(),
            "https://four.example".to_string(),
        ],
    ] {
        let root = temp_dir("ic-query-subnet-invalid-agreement");
        let source =
            AgreementFixtureSource::new(AgreementFixtureMode::Matching, "https://none.example");
        let mut request = refresh_request(&root);
        request.source = CatalogSourceSelection::multi_endpoint_agreement(endpoints);

        let error = futures::executor::block_on(refresh_subnet_catalog_with_source_async(
            &request, &source,
        ))
        .expect_err("invalid selection");

        assert!(matches!(
            error,
            SubnetCatalogHostError::InvalidSourceSelection { .. }
        ));
        assert_eq!(source.call_count(), 0);
        assert!(!subnet_catalog_path(&root, MAINNET_NETWORK).exists());
        let _ = fs::remove_dir_all(root);
    }
}

#[test]
fn agreement_endpoint_failure_keeps_exact_endpoint_context() {
    let root = temp_dir("ic-query-subnet-agreement-endpoint-error");
    let beta = "https://beta.example";
    let source = AgreementFixtureSource::new(AgreementFixtureMode::EndpointFailure, beta);
    let mut request = refresh_request(&root);
    request.source = CatalogSourceSelection::multi_endpoint_agreement(vec![
        "https://alpha.example".to_string(),
        beta.to_string(),
    ]);

    let error =
        futures::executor::block_on(refresh_subnet_catalog_with_source_async(&request, &source))
            .expect_err("endpoint fails");

    assert!(matches!(
        error,
        SubnetCatalogHostError::AgreementEndpoint { endpoint, .. } if endpoint == beta
    ));
    assert_eq!(source.call_count(), 2);
    assert!(!subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK).exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn cancelled_async_refresh_drops_its_owned_lock_without_publishing() {
    let root = temp_dir("ic-query-subnet-refresh-cancelled");
    let request = refresh_request(&root);
    let lock_path = subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK);
    let mut future = Box::pin(refresh_subnet_catalog_with_source_async(
        &request,
        &PendingSource,
    ));
    let waker = futures::task::noop_waker();
    let mut context = Context::from_waker(&waker);

    assert!(matches!(future.as_mut().poll(&mut context), Poll::Pending));
    assert!(lock_path.exists());
    drop(future);

    assert!(!lock_path.exists());
    assert!(!subnet_catalog_path(&root, MAINNET_NETWORK).exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn custom_source_must_echo_the_exact_requested_endpoint() {
    let root = temp_dir("ic-query-subnet-source-endpoint-mismatch");
    let requested = "https://other.example";
    let mut request = refresh_request(&root);
    request.source = CatalogSourceSelection::uncertified_query(requested);

    let error = futures::executor::block_on(refresh_subnet_catalog_with_source_async(
        &request,
        &WrongEndpointSource,
    ))
    .expect_err("source endpoint must match request");

    assert!(matches!(
        error,
        SubnetCatalogHostError::SourceEvidenceMismatch {
            requested: actual_request,
            actual_endpoints,
            ..
        } if actual_request == requested
            && actual_endpoints == [DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT]
    ));
    assert!(!subnet_catalog_path(&root, MAINNET_NETWORK).exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn refresh_rejects_output_aliasing_catalog_without_changing_cache() {
    for dry_run in [true, false] {
        let root = temp_dir("ic-query-subnet-refresh-output-alias");
        let mut original_catalog = fixture_catalog();
        original_catalog.provenance.fetched_by = "original-cache".to_string();
        original_catalog
            .canonicalize_and_seal()
            .expect("seal original");
        write_catalog(&root, original_catalog);
        let path = subnet_catalog_path(&root, MAINNET_NETWORK);
        let original = fs::read(&path).expect("original catalog");
        let request = refresh_request(&root)
            .with_dry_run(dry_run)
            .with_output_path(&path);

        let result = refresh_subnet_catalog_with_source(
            &request,
            &FixtureRefreshSource::ok(fixture_catalog()),
        );

        assert!(matches!(
            result,
            Err(SubnetCatalogHostError::Cache(HostCacheError::Operation {
                source: CacheFileError::OutputAliasesManagedPath { .. },
                ..
            }))
        ));
        assert_eq!(fs::read(&path).expect("preserved catalog"), original);
        assert!(!subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK).exists());
        let _ = fs::remove_dir_all(root);
    }
}

#[test]
fn refresh_rejects_output_aliases_before_fetching_or_creating_catalog_and_lock() {
    let root = temp_dir("ic-query-subnet-refresh-output-preflight");
    for output_path in [
        subnet_catalog_path(&root, MAINNET_NETWORK),
        subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK),
        crate::subnet_catalog::subnet_catalog_history_path(&root, MAINNET_NETWORK),
        crate::subnet_catalog::subnet_catalog_history_lock_path(&root, MAINNET_NETWORK),
    ] {
        let request = refresh_request(&root)
            .with_dry_run(true)
            .with_output_path(output_path);
        let error = refresh_subnet_catalog_with_source(&request, &FixtureRefreshSource::err())
            .expect_err("invalid output fails before the failing source is called");
        assert!(matches!(
            error,
            SubnetCatalogHostError::Cache(HostCacheError::Operation {
                source: CacheFileError::OutputAliasesManagedPath { .. },
                ..
            })
        ));
        assert!(!root.exists());
    }
}

#[cfg(unix)]
#[test]
fn refresh_rechecks_output_aliases_after_source_collection() {
    struct AliasingSource {
        output_path: PathBuf,
        catalog_path: PathBuf,
        fixture: FixtureRefreshSource,
        hard_link: bool,
    }

    impl SubnetCatalogSource for AliasingSource {
        fn fetch_catalog<'a>(
            &'a self,
            request: &'a NnsSourceRequest,
        ) -> SubnetCatalogSourceFuture<'a> {
            Box::pin(async move {
                if self.hard_link {
                    fs::hard_link(&self.catalog_path, &self.output_path).expect("late hard link");
                } else {
                    symlink(&self.catalog_path, &self.output_path).expect("late symlink");
                }
                self.fixture.fetch_catalog(request).await
            })
        }
    }

    for hard_link in [true, false] {
        let root = temp_dir("ic-query-subnet-refresh-late-output-alias");
        write_catalog(&root, fixture_catalog());
        let catalog_path = subnet_catalog_path(&root, MAINNET_NETWORK);
        let original = fs::read(&catalog_path).expect("original catalog");
        let output_path = root.join("export.json");
        let source = AliasingSource {
            output_path: output_path.clone(),
            catalog_path: catalog_path.clone(),
            fixture: FixtureRefreshSource::ok(fixture_catalog()),
            hard_link,
        };
        let request = refresh_request(&root)
            .with_dry_run(true)
            .with_output_path(output_path);
        let error = refresh_subnet_catalog_with_source(&request, &source)
            .expect_err("alias introduced during collection is rejected");
        assert!(matches!(
            error,
            SubnetCatalogHostError::Cache(HostCacheError::Operation {
                source: CacheFileError::OutputAliasesManagedPath { .. },
                ..
            })
        ));
        assert_eq!(
            fs::read(&catalog_path).expect("preserved catalog"),
            original
        );
        assert!(!subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK).exists());
        let _ = fs::remove_dir_all(root);
    }
}

#[test]
fn refresh_dry_run_writes_output_without_replacing_cache() {
    let root = temp_dir("ic-query-subnet-refresh-dry-run");
    let mut catalog = fixture_catalog();
    catalog.provenance.fetched_at = "1970-01-01T00:00:00Z".to_string();
    catalog.provenance.source_endpoints = vec![DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT.to_string()];
    catalog.canonicalize_and_seal().expect("reseal fixture");
    let output_path = root.join("catalog-export.json");
    let source = FixtureRefreshSource::ok(catalog);
    let mut request = refresh_request(&root);
    request.dry_run = true;
    request.output_path = Some(output_path.clone());

    let report = refresh_subnet_catalog_with_source(&request, &source).expect("dry-run");

    assert!(!report.wrote_catalog);
    assert!(!subnet_catalog_path(&request.cache.cache_root, MAINNET_NETWORK).exists());
    assert!(output_path.exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn refresh_dry_run_distinct_output_preserves_existing_catalog_bytes() {
    let root = temp_dir("ic-query-subnet-refresh-dry-run-existing");
    let mut original_catalog = fixture_catalog();
    original_catalog.provenance.fetched_by = "original-cache".to_string();
    original_catalog
        .canonicalize_and_seal()
        .expect("seal original");
    write_catalog(&root, original_catalog);
    let path = subnet_catalog_path(&root, MAINNET_NETWORK);
    let original = fs::read(&path).expect("original catalog");
    let output_path = root.join("catalog-export.json");
    let request = refresh_request(&root)
        .with_dry_run(true)
        .with_output_path(&output_path);
    let report =
        refresh_subnet_catalog_with_source(&request, &FixtureRefreshSource::ok(fixture_catalog()))
            .expect("distinct dry-run output");

    assert!(!report.wrote_catalog);
    assert!(report.replaced_existing_catalog);
    assert_eq!(fs::read(&path).expect("preserved catalog"), original);
    assert_ne!(fs::read(&output_path).expect("export"), original);
    let _ = fs::remove_dir_all(root);
}

#[test]
fn refresh_failure_preserves_existing_catalog_and_removes_lock() {
    let root = temp_dir("ic-query-subnet-refresh-failure");
    write_catalog(&root, fixture_catalog());
    let source = FixtureRefreshSource::err();
    let request = refresh_request(&root);

    let err = refresh_subnet_catalog_with_source(&request, &source).expect_err("refresh fails");
    let cached =
        load_cached_subnet_catalog(&cache_only_load_request(&root)).expect("cached catalog");
    let lock_path = subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK);

    assert!(matches!(
        err,
        SubnetCatalogHostError::Catalog(CatalogError::EmptySubnets)
    ));
    assert_eq!(cached.catalog.provenance().registry_version, 123_456);
    assert!(!lock_path.exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn refresh_existing_fresh_lock_fails_fast() {
    let root = temp_dir("ic-query-subnet-refresh-locked");
    let request = refresh_request(&root);
    let lock_path = subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK);
    write_refresh_lock_for_test(&lock_path, &request, request.now_unix_secs * 1_000);

    let err = refresh_subnet_catalog_with_source(&request, &FixtureRefreshSource::err())
        .expect_err("lock held");

    let _ = fs::remove_dir_all(root);
    assert!(matches!(
        err,
        SubnetCatalogHostError::Cache(HostCacheError::Operation {
            source: CacheFileError::RefreshAlreadyInProgress { .. },
            ..
        })
    ));
}

#[test]
fn refresh_rejects_stale_lock_without_removing_it() {
    let root = temp_dir("ic-query-subnet-refresh-stale-lock");
    let mut catalog = fixture_catalog();
    catalog.provenance.fetched_at = "1970-01-01T00:00:00Z".to_string();
    catalog.provenance.source_endpoints = vec![DEFAULT_SUBNET_CATALOG_SOURCE_ENDPOINT.to_string()];
    catalog.canonicalize_and_seal().expect("reseal fixture");
    let source = FixtureRefreshSource::ok(catalog);
    let request = refresh_request(&root);
    let lock_path = subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK);
    let stale_started_at = (request.now_unix_secs - request.lock_stale_after_seconds - 1) * 1_000;
    write_refresh_lock_for_test(&lock_path, &request, stale_started_at);

    let err = refresh_subnet_catalog_with_source(&request, &source)
        .expect_err("stale lock requires manual cleanup");

    assert!(matches!(
        err,
        SubnetCatalogHostError::Cache(HostCacheError::Operation {
            source: CacheFileError::StaleRefreshLock { .. },
            ..
        })
    ));
    assert!(lock_path.exists());
    let _ = fs::remove_dir_all(root);
}

#[test]
fn concurrent_endpoint_cancellation_preserves_cache_and_allows_immediate_retry() {
    struct TrackedSource {
        started: AtomicUsize,
        dropped: AtomicUsize,
    }
    struct Guard<'a>(&'a AtomicUsize);
    impl Drop for Guard<'_> {
        fn drop(&mut self) {
            self.0.fetch_add(1, Ordering::SeqCst);
        }
    }
    impl SubnetCatalogSource for TrackedSource {
        fn fetch_catalog<'a>(&'a self, _: &'a NnsSourceRequest) -> SubnetCatalogSourceFuture<'a> {
            Box::pin(async move {
                self.started.fetch_add(1, Ordering::SeqCst);
                let _guard = Guard(&self.dropped);
                std::future::pending().await
            })
        }
    }
    let root = temp_dir("ic-query-concurrent-cancel");
    write_catalog(&root, fixture_catalog());
    let path = subnet_catalog_path(&root, MAINNET_NETWORK);
    let before = fs::read(&path).unwrap();
    let mut request = refresh_request(&root);
    request.source = CatalogSourceSelection::multi_endpoint_agreement(vec![
        "https://a.example".into(),
        "https://b.example".into(),
        "https://c.example".into(),
    ]);
    let source = TrackedSource {
        started: AtomicUsize::new(0),
        dropped: AtomicUsize::new(0),
    };
    let mut future = Box::pin(refresh_subnet_catalog_with_source_async(&request, &source));
    let waker = futures::task::noop_waker();
    assert!(
        future
            .as_mut()
            .poll(&mut Context::from_waker(&waker))
            .is_pending()
    );
    assert_eq!(source.started.load(Ordering::SeqCst), 2);
    drop(future);
    assert_eq!(source.dropped.load(Ordering::SeqCst), 2);
    assert_eq!(fs::read(&path).unwrap(), before);
    assert!(!subnet_catalog_refresh_lock_path(&root, MAINNET_NETWORK).exists());
    let retry = AgreementFixtureSource::new(AgreementFixtureMode::Matching, "https://b.example");
    futures::executor::block_on(refresh_subnet_catalog_with_source_async(&request, &retry))
        .unwrap();
    assert_eq!(retry.call_count(), 3);
    let _ = fs::remove_dir_all(root);
}