ic-query 0.52.1

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
//! Module: subnet_catalog::host::cache
//!
//! Responsibility: load validated catalogs under explicit caller freshness policy.
//! Does not own: live Registry collection, cache paths, or report rendering.
//! Boundary: returns validated snapshot authority separately from observable acquisition state.

use super::{
    CatalogSourceSelection, LiveSubnetCatalogSource, SubnetCatalogFailureCacheDisposition,
    SubnetCatalogHostError, SubnetCatalogLoadFailure, SubnetCatalogLoadStage,
    SubnetCatalogRefreshRequest, SubnetCatalogRefreshTrigger, SubnetCatalogSource,
    SubnetCatalogSourceFailure, SubnetCatalogSubject, error::enforce_mainnet_network,
    failure::subject_from_catalog_error,
    refresh::refresh_subnet_catalog_detailed_with_progress_async, subnet_catalog_path,
};
use crate::{QueryProgress, progress::IgnoreQueryProgress};
use crate::{
    cache_file::{BoundedManagedFileReadError, HostCacheError, read_bounded_managed_file},
    runtime::block_on_current_thread,
    subnet_catalog::{
        CatalogAssurance, CatalogSnapshotAuthorityEvidence, CatalogValidationContext,
        DEFAULT_CATALOG_MAX_FUTURE_SKEW_SECONDS, DEFAULT_REFRESH_LOCK_STALE_SECONDS,
        MAINNET_REGISTRY_CANISTER_ID, ValidatedSubnetCatalog, catalog_stale_status,
    },
};
use serde::{Deserialize, Serialize};
use std::{io, path::PathBuf};

///
/// SubnetCatalogCacheRequest
///
/// Cache root and network identity used to locate a Subnet Catalog snapshot.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubnetCatalogCacheRequest {
    /// Caller-owned cache root.
    pub cache_root: PathBuf,
    /// Canonical network identity.
    pub network: String,
}

impl SubnetCatalogCacheRequest {
    /// Build one cache identity.
    #[must_use]
    pub fn new(cache_root: impl Into<PathBuf>, network: impl Into<String>) -> Self {
        Self {
            cache_root: cache_root.into(),
            network: network.into(),
        }
    }
}

///
/// CatalogReadPolicy
///
/// Exact cache and network behavior authorized for one catalog load.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CatalogReadPolicy {
    /// Load valid content within the fixed 64 MiB read ceiling without a network call.
    CacheOnly,
    /// Refresh only when the cache is absent.
    RefreshMissing {
        /// Explicit live Registry source used only when content is absent.
        source: CatalogSourceSelection,
    },
    /// Refresh when the cache is absent, oversized, or recoverably invalid.
    RefreshMissingOrInvalid {
        /// Explicit live Registry source used for authorized repair.
        source: CatalogSourceSelection,
    },
    /// Refresh absent, recoverably invalid, or older valid content.
    RefreshMissingInvalidOrOlderThan {
        /// Explicit live Registry source used for authorized refresh.
        source: CatalogSourceSelection,
        /// Maximum accepted age of an otherwise valid catalog.
        max_age_seconds: u64,
    },
    /// Always collect and atomically replace the complete catalog.
    ForceRefresh {
        /// Explicit live Registry source used for forced collection.
        source: CatalogSourceSelection,
    },
}

impl CatalogReadPolicy {
    pub(super) const fn source(&self) -> Option<&CatalogSourceSelection> {
        match self {
            Self::CacheOnly => None,
            Self::RefreshMissing { source }
            | Self::RefreshMissingOrInvalid { source }
            | Self::RefreshMissingInvalidOrOlderThan { source, .. }
            | Self::ForceRefresh { source } => Some(source),
        }
    }
}

///
/// SubnetCatalogLoadRequest
///
/// Caller-owned cache identity, time, and exact read policy.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SubnetCatalogLoadRequest {
    /// Cache identity.
    pub cache: SubnetCatalogCacheRequest,
    /// Caller-supplied current Unix time.
    pub now_unix_secs: u64,
    /// Maximum accepted future timestamp skew.
    pub max_future_skew_seconds: u64,
    /// Minimum authority level accepted from cache or refresh.
    pub minimum_assurance: CatalogAssurance,
    /// Authorized cache and network behavior.
    pub policy: CatalogReadPolicy,
}

impl SubnetCatalogLoadRequest {
    /// Build a cache-only request with the default future-skew allowance.
    #[must_use]
    pub const fn cache_only(cache: SubnetCatalogCacheRequest, now_unix_secs: u64) -> Self {
        Self {
            cache,
            now_unix_secs,
            max_future_skew_seconds: DEFAULT_CATALOG_MAX_FUTURE_SKEW_SECONDS,
            minimum_assurance: CatalogAssurance::UncertifiedQuery,
            policy: CatalogReadPolicy::CacheOnly,
        }
    }

    /// Build a missing-or-invalid read-through request.
    #[must_use]
    pub const fn refresh_missing_or_invalid(
        cache: SubnetCatalogCacheRequest,
        source: CatalogSourceSelection,
        now_unix_secs: u64,
    ) -> Self {
        Self {
            cache,
            now_unix_secs,
            max_future_skew_seconds: DEFAULT_CATALOG_MAX_FUTURE_SKEW_SECONDS,
            minimum_assurance: CatalogAssurance::UncertifiedQuery,
            policy: CatalogReadPolicy::RefreshMissingOrInvalid { source },
        }
    }

    /// Build a missing/invalid/stale read-through request.
    #[must_use]
    pub const fn refresh_missing_invalid_or_older_than(
        cache: SubnetCatalogCacheRequest,
        source: CatalogSourceSelection,
        now_unix_secs: u64,
        max_age_seconds: u64,
    ) -> Self {
        Self {
            cache,
            now_unix_secs,
            max_future_skew_seconds: DEFAULT_CATALOG_MAX_FUTURE_SKEW_SECONDS,
            minimum_assurance: CatalogAssurance::UncertifiedQuery,
            policy: CatalogReadPolicy::RefreshMissingInvalidOrOlderThan {
                source,
                max_age_seconds,
            },
        }
    }

    /// Override the maximum accepted future timestamp skew.
    #[must_use]
    pub const fn with_max_future_skew_seconds(mut self, seconds: u64) -> Self {
        self.max_future_skew_seconds = seconds;
        self
    }

    /// Require loaded evidence to meet at least this assurance level.
    #[must_use]
    pub const fn with_minimum_assurance(mut self, minimum: CatalogAssurance) -> Self {
        self.minimum_assurance = minimum;
        self
    }

    /// Replace the exact cache/network policy.
    #[must_use]
    pub fn with_policy(mut self, policy: CatalogReadPolicy) -> Self {
        self.policy = policy;
        self
    }
}

///
/// CacheDisposition
///
/// Observable result of applying one catalog read policy.
///

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheDisposition {
    /// Existing validated cache content was used.
    CacheHit,
    /// Missing content was collected and published.
    RefreshedMissing,
    /// Recoverably invalid content was replaced.
    RefreshedInvalid,
    /// Valid but older-than-policy content was replaced.
    RefreshedStale,
    /// Caller explicitly required replacement.
    ForcedRefresh,
}

impl CacheDisposition {
    /// Return the stable JSON and report label.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::CacheHit => "cache_hit",
            Self::RefreshedMissing => "refreshed_missing",
            Self::RefreshedInvalid => "refreshed_invalid",
            Self::RefreshedStale => "refreshed_stale",
            Self::ForcedRefresh => "forced_refresh",
        }
    }
}

///
/// CatalogLoadOutcome
///
/// Validated catalog, supplying path, and observable cache disposition.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CatalogLoadOutcome {
    /// Cache path read or published by this acquisition.
    pub path: PathBuf,
    /// Validated catalog whose authority is independent of acquisition state.
    pub catalog: ValidatedSubnetCatalog,
    /// Transient result of applying the requested cache policy.
    pub disposition: CacheDisposition,
}

impl CatalogLoadOutcome {
    /// Return stable authority derived only from the validated catalog snapshot.
    #[must_use]
    pub fn snapshot_authority(&self) -> CatalogSnapshotAuthorityEvidence {
        self.catalog.snapshot_authority()
    }
}

/// Load a catalog without making a live network call.
pub fn load_cached_subnet_catalog(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    load_cached_subnet_catalog_detailed(request).map_err(SubnetCatalogLoadFailure::into_source)
}

/// Load a catalog locally while retaining typed failure provenance.
pub fn load_cached_subnet_catalog_detailed(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    if request.policy != CatalogReadPolicy::CacheOnly {
        return Err(load_failure(
            request,
            SubnetCatalogLoadStage::RequestValidation,
            SubnetCatalogFailureCacheDisposition::NotExamined,
            SubnetCatalogSourceFailure::from_source(SubnetCatalogHostError::InvalidReadPolicy {
                reason: "load_cached_subnet_catalog requires CatalogReadPolicy::CacheOnly"
                    .to_string(),
            }),
        ));
    }
    load_cached_with_disposition_detailed(request, CacheDisposition::CacheHit)
        .map_err(|failure| cache_load_failure(request, true, failure))
}

/// Apply an explicit catalog read policy using the live mainnet source when authorized.
pub fn load_subnet_catalog(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    load_subnet_catalog_detailed(request).map_err(SubnetCatalogLoadFailure::into_source)
}

/// Apply an explicit catalog read policy while retaining typed failure provenance.
pub fn load_subnet_catalog_detailed(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    match block_on_current_thread(load_subnet_catalog_detailed_async(request)) {
        Ok(result) => result,
        Err(source) => Err(runtime_load_failure(request, source)),
    }
}

/// Apply an explicit catalog read policy using a caller-supplied fixture or live source.
pub fn load_subnet_catalog_with_source(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    load_subnet_catalog_detailed_with_source(request, source)
        .map_err(SubnetCatalogLoadFailure::into_source)
}

/// Apply a catalog read policy with a supplied source and progress sink.
pub fn load_subnet_catalog_with_source_and_progress(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
    progress: &mut (dyn QueryProgress + Send),
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    match block_on_current_thread(load_subnet_catalog_detailed_with_progress_async(
        request, source, progress,
    )) {
        Ok(result) => result.map_err(SubnetCatalogLoadFailure::into_source),
        Err(error) => Err(runtime_load_failure(request, error).into_source()),
    }
}

/// Apply a catalog read policy with a supplied source and typed failure provenance.
pub fn load_subnet_catalog_detailed_with_source(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    match block_on_current_thread(load_subnet_catalog_detailed_with_source_async(
        request, source,
    )) {
        Ok(result) => result,
        Err(error) => Err(runtime_load_failure(request, error)),
    }
}

/// Apply a catalog read policy on the caller's async runtime using the live source.
pub async fn load_subnet_catalog_async(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    load_subnet_catalog_detailed_async(request)
        .await
        .map_err(SubnetCatalogLoadFailure::into_source)
}

/// Apply a catalog policy asynchronously while retaining typed failure provenance.
pub async fn load_subnet_catalog_detailed_async(
    request: &SubnetCatalogLoadRequest,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    let source = LiveSubnetCatalogSource::default().with_history_cache(&request.cache.cache_root);
    load_subnet_catalog_detailed_with_source_async(request, &source).await
}

/// Apply a catalog read policy on the caller's async runtime using a supplied source.
pub async fn load_subnet_catalog_with_source_async(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
) -> Result<CatalogLoadOutcome, SubnetCatalogHostError> {
    load_subnet_catalog_detailed_with_source_async(request, source)
        .await
        .map_err(SubnetCatalogLoadFailure::into_source)
}

/// Apply a catalog policy asynchronously with a supplied source and typed failures.
pub async fn load_subnet_catalog_detailed_with_source_async(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    load_subnet_catalog_detailed_with_progress_async(request, source, &mut IgnoreQueryProgress)
        .await
}

async fn load_subnet_catalog_detailed_with_progress_async(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
    progress: &mut (dyn QueryProgress + Send),
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    enforce_mainnet_network(&request.cache.network).map_err(|source| {
        load_failure(
            request,
            SubnetCatalogLoadStage::RequestValidation,
            SubnetCatalogFailureCacheDisposition::NotExamined,
            SubnetCatalogSourceFailure::new(
                None,
                Some(SubnetCatalogSubject::Network(request.cache.network.clone())),
                source,
            ),
        )
    })?;
    match &request.policy {
        CatalogReadPolicy::CacheOnly => {
            load_cached_with_disposition_detailed(request, CacheDisposition::CacheHit)
                .map_err(|failure| cache_load_failure(request, true, failure))
        }
        CatalogReadPolicy::ForceRefresh { .. } => {
            refresh_then_load_detailed(
                request,
                source,
                progress,
                CacheDisposition::ForcedRefresh,
                SubnetCatalogRefreshTrigger::Forced,
            )
            .await
        }
        policy => {
            match load_cached_with_disposition_detailed(request, CacheDisposition::CacheHit) {
                Ok(cached) => {
                    let max_age_seconds = match policy {
                        CatalogReadPolicy::RefreshMissingInvalidOrOlderThan {
                            max_age_seconds,
                            ..
                        } => Some(*max_age_seconds),
                        _ => None,
                    };
                    if max_age_seconds.is_some_and(|max_age_seconds| {
                        catalog_stale_status(
                            cached.catalog.raw(),
                            request.now_unix_secs,
                            max_age_seconds,
                        )
                        .catalog_stale
                    }) {
                        refresh_then_load_detailed(
                            request,
                            source,
                            progress,
                            CacheDisposition::RefreshedStale,
                            SubnetCatalogRefreshTrigger::Stale,
                        )
                        .await
                    } else {
                        Ok(cached)
                    }
                }
                Err(failure)
                    if matches!(
                        failure.source,
                        SubnetCatalogHostError::MissingCatalog { .. }
                    ) =>
                {
                    refresh_then_load_detailed(
                        request,
                        source,
                        progress,
                        CacheDisposition::RefreshedMissing,
                        SubnetCatalogRefreshTrigger::Missing,
                    )
                    .await
                }
                Err(failure)
                    if matches!(
                        policy,
                        CatalogReadPolicy::RefreshMissingOrInvalid { .. }
                            | CatalogReadPolicy::RefreshMissingInvalidOrOlderThan { .. }
                    ) && matches!(
                        failure.source,
                        SubnetCatalogHostError::Catalog(_)
                            | SubnetCatalogHostError::CachedCatalogTooLarge { .. }
                    ) =>
                {
                    refresh_then_load_detailed(
                        request,
                        source,
                        progress,
                        CacheDisposition::RefreshedInvalid,
                        SubnetCatalogRefreshTrigger::Rejected,
                    )
                    .await
                }
                Err(failure) => Err(cache_load_failure(request, false, failure)),
            }
        }
    }
}

fn load_cached_with_disposition_detailed(
    request: &SubnetCatalogLoadRequest,
    disposition: CacheDisposition,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogSourceFailure>> {
    enforce_mainnet_network(&request.cache.network).map_err(|source| {
        SubnetCatalogSourceFailure::new(
            None,
            Some(SubnetCatalogSubject::Network(request.cache.network.clone())),
            source,
        )
    })?;
    let path = subnet_catalog_path(&request.cache.cache_root, &request.cache.network);
    let Some(data) = read_bounded_managed_file(
        &request.cache.cache_root,
        &path,
        crate::cache_file::MAX_JSON_SNAPSHOT_BYTES,
        None,
    )
    .map_err(|error| {
        SubnetCatalogSourceFailure::new(
            None,
            Some(SubnetCatalogSubject::CachePath(path.clone())),
            bounded_catalog_read_error(error),
        )
    })?
    else {
        return Err(SubnetCatalogSourceFailure::new(
            None,
            Some(SubnetCatalogSubject::CachePath(path.clone())),
            SubnetCatalogHostError::MissingCatalog { path },
        ));
    };
    let raw = serde_json::from_slice::<crate::subnet_catalog::RawSubnetCatalog>(&data)
        .map_err(crate::subnet_catalog::CatalogError::from)
        .and_then(|catalog| {
            catalog.validate()?;
            Ok(catalog)
        })
        .map_err(|source| {
            let subject = subject_from_catalog_error(&source);
            SubnetCatalogSourceFailure::new(None, subject, SubnetCatalogHostError::Catalog(source))
        })?;
    let registry_version = raw.provenance.registry_version;
    let validation = CatalogValidationContext::new(
        &request.cache.network,
        MAINNET_REGISTRY_CANISTER_ID,
        request.now_unix_secs,
        request.max_future_skew_seconds,
    );
    let catalog = ValidatedSubnetCatalog::try_from_raw(raw, &validation).map_err(|source| {
        let subject = subject_from_catalog_error(&source);
        SubnetCatalogSourceFailure::new(
            Some(registry_version),
            subject,
            SubnetCatalogHostError::Catalog(source),
        )
    })?;
    enforce_minimum_assurance(catalog.provenance().assurance, request.minimum_assurance)
        .map_err(|source| SubnetCatalogSourceFailure::new(Some(registry_version), None, source))?;
    Ok(CatalogLoadOutcome {
        path,
        catalog,
        disposition,
    })
}

fn bounded_catalog_read_error(error: BoundedManagedFileReadError) -> SubnetCatalogHostError {
    match error {
        BoundedManagedFileReadError::Operation(source) => super::error::subnet_cache_error(source),
        BoundedManagedFileReadError::Read { path, source } => HostCacheError::ReadCache {
            component: "subnet catalog",
            path,
            source,
        }
        .into(),
        BoundedManagedFileReadError::LimitExceeded {
            path,
            actual,
            maximum,
        } => SubnetCatalogHostError::CachedCatalogTooLarge {
            path,
            actual,
            maximum,
        },
        BoundedManagedFileReadError::Accounting { path } => HostCacheError::ReadCache {
            component: "subnet catalog",
            path,
            source: io::Error::new(
                io::ErrorKind::InvalidData,
                "catalog byte count cannot be represented",
            ),
        }
        .into(),
    }
}

async fn refresh_then_load_detailed(
    request: &SubnetCatalogLoadRequest,
    source: &dyn SubnetCatalogSource,
    progress: &mut (dyn QueryProgress + Send),
    disposition: CacheDisposition,
    trigger: SubnetCatalogRefreshTrigger,
) -> Result<CatalogLoadOutcome, Box<SubnetCatalogLoadFailure>> {
    let source_selection = request.policy.source().ok_or_else(|| {
        load_failure(
            request,
            SubnetCatalogLoadStage::RefreshAttempted,
            SubnetCatalogFailureCacheDisposition::RefreshAttempted(trigger),
            SubnetCatalogSourceFailure::from_source(SubnetCatalogHostError::InvalidReadPolicy {
                reason: "refresh policy is missing its source selection".to_string(),
            }),
        )
    })?;
    enforce_minimum_assurance(source_selection.assurance(), request.minimum_assurance).map_err(
        |source| {
            let (stage, cache_disposition) = if trigger == SubnetCatalogRefreshTrigger::Forced {
                (
                    SubnetCatalogLoadStage::CacheBypass,
                    SubnetCatalogFailureCacheDisposition::CacheBypassed,
                )
            } else {
                (
                    SubnetCatalogLoadStage::RefreshAttempted,
                    SubnetCatalogFailureCacheDisposition::RefreshAttempted(trigger),
                )
            };
            load_failure(
                request,
                stage,
                cache_disposition,
                SubnetCatalogSourceFailure::from_source(source),
            )
        },
    )?;
    let refresh_request = SubnetCatalogRefreshRequest::new(
        request.cache.clone(),
        source_selection.clone(),
        request.now_unix_secs,
        DEFAULT_REFRESH_LOCK_STALE_SECONDS,
    )
    .with_max_future_skew_seconds(request.max_future_skew_seconds);
    let refresh =
        refresh_subnet_catalog_detailed_with_progress_async(&refresh_request, source, progress)
            .await
            .map_err(|failure| {
                load_failure(
                    request,
                    SubnetCatalogLoadStage::RefreshFailed,
                    SubnetCatalogFailureCacheDisposition::RefreshFailed(trigger),
                    failure,
                )
            })?;
    load_cached_with_disposition_detailed(request, disposition).map_err(|mut failure| {
        if failure.registry_version.is_none() {
            failure.registry_version = Some(refresh.registry_version);
        }
        post_refresh_load_failure(request, trigger, failure)
    })
}

fn post_refresh_load_failure(
    request: &SubnetCatalogLoadRequest,
    trigger: SubnetCatalogRefreshTrigger,
    failure: Box<SubnetCatalogSourceFailure>,
) -> Box<SubnetCatalogLoadFailure> {
    load_failure(
        request,
        SubnetCatalogLoadStage::PostRefreshCacheLoadFailed,
        SubnetCatalogFailureCacheDisposition::PostRefreshLoadFailed(trigger),
        failure,
    )
}

fn cache_load_failure(
    request: &SubnetCatalogLoadRequest,
    cache_only: bool,
    failure: Box<SubnetCatalogSourceFailure>,
) -> Box<SubnetCatalogLoadFailure> {
    let (stage, cache_disposition) = match &failure.source {
        SubnetCatalogHostError::UnsupportedNetwork { .. } => (
            SubnetCatalogLoadStage::RequestValidation,
            SubnetCatalogFailureCacheDisposition::NotExamined,
        ),
        SubnetCatalogHostError::MissingCatalog { .. } => (
            SubnetCatalogLoadStage::CacheAbsence,
            SubnetCatalogFailureCacheDisposition::CacheMissing,
        ),
        SubnetCatalogHostError::Catalog(_)
        | SubnetCatalogHostError::CachedCatalogTooLarge { .. }
        | SubnetCatalogHostError::InsufficientAssurance { .. } => (
            SubnetCatalogLoadStage::CacheRejection,
            SubnetCatalogFailureCacheDisposition::CacheRejected,
        ),
        _ if cache_only => (
            SubnetCatalogLoadStage::CacheOnlyLoad,
            SubnetCatalogFailureCacheDisposition::CacheOnly,
        ),
        _ => (
            SubnetCatalogLoadStage::CacheLookup,
            SubnetCatalogFailureCacheDisposition::CacheReadFailed,
        ),
    };
    load_failure(request, stage, cache_disposition, failure)
}

fn runtime_load_failure(
    request: &SubnetCatalogLoadRequest,
    source: crate::runtime::RuntimeError,
) -> Box<SubnetCatalogLoadFailure> {
    load_failure(
        request,
        SubnetCatalogLoadStage::RuntimeAdapter,
        SubnetCatalogFailureCacheDisposition::NotExamined,
        SubnetCatalogSourceFailure::from_source(SubnetCatalogHostError::RuntimeAdapter(source)),
    )
}

fn load_failure(
    request: &SubnetCatalogLoadRequest,
    stage: SubnetCatalogLoadStage,
    cache_disposition: SubnetCatalogFailureCacheDisposition,
    failure: Box<SubnetCatalogSourceFailure>,
) -> Box<SubnetCatalogLoadFailure> {
    SubnetCatalogLoadFailure::from_source_failure(request, stage, cache_disposition, failure)
}

const fn enforce_minimum_assurance(
    actual: CatalogAssurance,
    required: CatalogAssurance,
) -> Result<(), SubnetCatalogHostError> {
    if actual.satisfies(required) {
        Ok(())
    } else {
        Err(SubnetCatalogHostError::InsufficientAssurance { required, actual })
    }
}

#[cfg(test)]
mod detailed_failure_tests {
    use super::*;

    #[test]
    fn post_refresh_cache_load_failure_has_a_distinct_typed_stage_and_disposition() {
        let request = SubnetCatalogLoadRequest::cache_only(
            SubnetCatalogCacheRequest::new("/tmp/ic-query-post-refresh-test", "ic"),
            123,
        );
        let source = SubnetCatalogSourceFailure::new(
            Some(9001),
            Some(SubnetCatalogSubject::CachePath(PathBuf::from(
                "/tmp/ic-query-post-refresh-test/catalog.json",
            ))),
            SubnetCatalogHostError::MissingCatalog {
                path: PathBuf::from("/tmp/ic-query-post-refresh-test/catalog.json"),
            },
        );

        let failure =
            post_refresh_load_failure(&request, SubnetCatalogRefreshTrigger::Missing, source);

        assert_eq!(
            failure.stage,
            SubnetCatalogLoadStage::PostRefreshCacheLoadFailed
        );
        assert_eq!(
            failure.cache_disposition,
            SubnetCatalogFailureCacheDisposition::PostRefreshLoadFailed(
                SubnetCatalogRefreshTrigger::Missing
            )
        );
        assert_eq!(failure.registry_version, Some(9001));
    }
}