Skip to main content

postproject_core/
resolution.rs

1//! Explainable and deterministic media-resolution results.
2
3use std::{cmp::Reverse, collections::BTreeSet};
4
5use crate::{
6    ContentStructure, DecisionBase, Error, ErrorKind, MAX_SEQUENCE_EXCEPTIONS, MediaRoot,
7    RepresentationId, ResourceId, Result, SequenceNaming, uri::normalize_uri,
8};
9
10/// A deterministic confidence value in basis points from 0 through 10,000.
11#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
12pub struct Confidence(u16);
13
14impl Confidence {
15    /// Certain confidence used only for verified identity evidence.
16    pub const CERTAIN: Self = Self(10_000);
17
18    /// Creates a confidence value, rejecting values above 100%.
19    ///
20    /// # Errors
21    ///
22    /// Returns [`ErrorKind::InvalidArgument`] when `value` exceeds 10,000.
23    pub fn from_basis_points(value: u16) -> Result<Self> {
24        if value > 10_000 {
25            return Err(Error::new(
26                ErrorKind::InvalidArgument,
27                "confidence must not exceed 10,000 basis points",
28            ));
29        }
30        Ok(Self(value))
31    }
32
33    /// Returns the confidence in basis points.
34    #[must_use]
35    pub const fn basis_points(self) -> u16 {
36        self.0
37    }
38}
39
40/// A machine-inspectable reason supporting or opposing a resolution candidate.
41#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
42#[non_exhaustive]
43pub enum EvidenceKind {
44    /// A persisted locator is currently available.
45    KnownLocatorAvailable,
46    /// The complete stored fingerprint matches.
47    ExactFingerprintMatch,
48    /// A cryptographic full-file digest matches.
49    FullHashMatch,
50    /// A sampled or otherwise partial fingerprint matches.
51    PartialFingerprintMatch,
52    /// The byte size matches.
53    FileSizeMatch,
54    /// The final path component matches.
55    FileNameMatch,
56    /// The path relative to a media root is similar.
57    RelativePathSimilarity,
58    /// The candidate is contained in a configured media root.
59    MediaRootRelation,
60    /// A logical media root has no mapping on this machine.
61    MediaRootUnmapped,
62    /// A mapped media root cannot currently be searched.
63    MediaRootUnavailable,
64    /// Present content does not match its stored fingerprint evidence.
65    FingerprintMismatch,
66    /// Stored fingerprint evidence exists only in domains the resolver cannot
67    /// compute, so content identity was not checked.
68    FingerprintNotVerified,
69    /// A searched directory held more entries than the per-directory budget,
70    /// so part of it was not searched.
71    SearchTruncated,
72    /// Another candidate has equivalent credible evidence.
73    ConflictingCandidate,
74    /// Candidate discovery or verification could not complete safely.
75    DiscoveryError,
76}
77
78/// Structured evidence with optional human-readable context.
79#[derive(Clone, Debug, Eq, PartialEq)]
80pub struct ResolutionEvidence {
81    kind: EvidenceKind,
82    detail: Option<String>,
83}
84
85impl ResolutionEvidence {
86    /// Creates a structured evidence item.
87    #[must_use]
88    pub fn new(kind: EvidenceKind, detail: Option<String>) -> Self {
89        Self { kind, detail }
90    }
91
92    /// Returns the machine-readable evidence kind.
93    #[must_use]
94    pub const fn kind(&self) -> EvidenceKind {
95        self.kind
96    }
97
98    /// Returns optional diagnostic context.
99    #[must_use]
100    pub fn detail(&self) -> Option<&str> {
101        self.detail.as_deref()
102    }
103}
104
105/// A possible resource locator considered by the resolver.
106#[derive(Clone, Debug, Eq, PartialEq)]
107pub struct ResolutionCandidate {
108    uri: String,
109    confidence: Confidence,
110    evidence: Vec<ResolutionEvidence>,
111    media_root: Option<String>,
112    sequence_naming: Option<SequenceNaming>,
113}
114
115impl ResolutionCandidate {
116    /// Creates a candidate with an absolute URI and at least one evidence item.
117    ///
118    /// # Errors
119    ///
120    /// Returns [`ErrorKind::InvalidArgument`] when `uri` is invalid or relative,
121    /// or when `evidence` is empty.
122    pub fn new(
123        uri: impl Into<String>,
124        confidence: Confidence,
125        evidence: Vec<ResolutionEvidence>,
126    ) -> Result<Self> {
127        let uri = normalize_uri(uri, "resolution candidate")?;
128        if evidence.is_empty() {
129            return Err(Error::new(
130                ErrorKind::InvalidArgument,
131                "resolution candidate must contain evidence",
132            ));
133        }
134        Ok(Self {
135            uri,
136            confidence,
137            evidence,
138            media_root: None,
139            sequence_naming: None,
140        })
141    }
142
143    /// Records the naming of the image-sequence files the candidate was found
144    /// under, so confirmation can record it with the locator.
145    #[must_use]
146    pub fn with_sequence_naming(mut self, naming: SequenceNaming) -> Self {
147        self.sequence_naming = Some(naming);
148        self
149    }
150
151    /// Returns the naming of the sequence files at the candidate, present
152    /// exactly for a candidate of an image-sequence resource.
153    #[must_use]
154    pub const fn sequence_naming(&self) -> Option<&SequenceNaming> {
155        self.sequence_naming.as_ref()
156    }
157
158    /// Associates the candidate with the logical media root it was found
159    /// under, so confirmation can record the portable root name.
160    ///
161    /// # Errors
162    ///
163    /// Returns an invalid-argument error for an invalid logical root name.
164    pub fn with_media_root(mut self, name: impl Into<String>) -> Result<Self> {
165        let name = name.into();
166        MediaRoot::validate_name(&name)?;
167        self.media_root = Some(name);
168        Ok(self)
169    }
170
171    /// Returns the logical media root the candidate was found under, if any.
172    /// A candidate found in an unnamed search directory has none.
173    #[must_use]
174    pub fn media_root(&self) -> Option<&str> {
175        self.media_root.as_deref()
176    }
177
178    /// Returns the candidate URI.
179    #[must_use]
180    pub fn uri(&self) -> &str {
181        &self.uri
182    }
183
184    /// Returns the deterministic confidence value.
185    #[must_use]
186    pub const fn confidence(&self) -> Confidence {
187        self.confidence
188    }
189
190    /// Returns the inspectable supporting evidence.
191    #[must_use]
192    pub fn evidence(&self) -> &[ResolutionEvidence] {
193        &self.evidence
194    }
195}
196
197/// The outcome of resolving one storage resource.
198#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
199#[non_exhaustive]
200pub enum ResourceResolutionState {
201    /// A persisted locator is currently online.
202    OnlineAtKnownLocator,
203    /// One candidate has exact identity evidence.
204    ResolvedExact,
205    /// One candidate is credible but lacks exact verification.
206    ResolvedProbable,
207    /// No credible candidate was found.
208    Offline,
209    /// Multiple candidates require an explicit decision.
210    Ambiguous,
211    /// Candidate discovery or verification could not complete safely.
212    Error,
213}
214
215/// An explainable result for one resource, independent of representation shape.
216#[derive(Clone, Debug, Eq, PartialEq)]
217pub struct ResourceResolution {
218    resource_id: ResourceId,
219    state: ResourceResolutionState,
220    candidates: Vec<ResolutionCandidate>,
221    evidence: Vec<ResolutionEvidence>,
222    missing_frames: Vec<i64>,
223}
224
225impl ResourceResolution {
226    /// Creates a resource result and sorts candidates deterministically.
227    ///
228    /// # Errors
229    ///
230    /// Returns [`ErrorKind::InvalidArgument`] when the candidate count is
231    /// inconsistent with `state`.
232    pub fn new(
233        resource_id: ResourceId,
234        state: ResourceResolutionState,
235        mut candidates: Vec<ResolutionCandidate>,
236        evidence: Vec<ResolutionEvidence>,
237    ) -> Result<Self> {
238        candidates.sort_by(|left, right| {
239            (
240                Reverse(left.confidence),
241                left.uri.as_str(),
242                &left.sequence_naming,
243            )
244                .cmp(&(
245                    Reverse(right.confidence),
246                    right.uri.as_str(),
247                    &right.sequence_naming,
248                ))
249        });
250        let valid_count = match state {
251            ResourceResolutionState::OnlineAtKnownLocator
252            | ResourceResolutionState::ResolvedExact
253            | ResourceResolutionState::ResolvedProbable => candidates.len() == 1,
254            ResourceResolutionState::Offline | ResourceResolutionState::Error => {
255                candidates.is_empty()
256            }
257            ResourceResolutionState::Ambiguous => candidates.len() >= 2,
258        };
259        if !valid_count {
260            return Err(Error::new(
261                ErrorKind::InvalidArgument,
262                "candidate count is inconsistent with resource resolution state",
263            ));
264        }
265        Ok(Self {
266            resource_id,
267            state,
268            candidates,
269            evidence,
270            missing_frames: Vec::new(),
271        })
272    }
273
274    /// Adds observed missing image-sequence frames in canonical order.
275    ///
276    /// # Errors
277    ///
278    /// Returns [`ErrorKind::InvalidArgument`] when the diagnostic exceeds the
279    /// bounded sequence-exception limit.
280    pub fn with_missing_frames(mut self, mut missing_frames: Vec<i64>) -> Result<Self> {
281        if missing_frames.len() > MAX_SEQUENCE_EXCEPTIONS {
282            return Err(Error::new(
283                ErrorKind::InvalidArgument,
284                format!("resolution has more than {MAX_SEQUENCE_EXCEPTIONS} missing frames"),
285            ));
286        }
287        missing_frames.sort_unstable();
288        missing_frames.dedup();
289        self.missing_frames = missing_frames;
290        Ok(self)
291    }
292
293    /// Returns the resolved resource identity.
294    #[must_use]
295    pub const fn resource_id(&self) -> ResourceId {
296        self.resource_id
297    }
298
299    /// Returns the resource outcome.
300    #[must_use]
301    pub const fn state(&self) -> ResourceResolutionState {
302        self.state
303    }
304
305    /// Returns candidates in deterministic best-first order.
306    #[must_use]
307    pub fn candidates(&self) -> &[ResolutionCandidate] {
308        &self.candidates
309    }
310
311    /// Returns resource-wide evidence and diagnostics.
312    #[must_use]
313    pub fn evidence(&self) -> &[ResolutionEvidence] {
314        &self.evidence
315    }
316
317    /// Returns sorted frames observed absent while resolving this resource.
318    #[must_use]
319    pub fn missing_frames(&self) -> &[i64] {
320        &self.missing_frames
321    }
322}
323
324/// Aggregated availability of a complete representation.
325#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
326#[non_exhaustive]
327pub enum RepresentationAvailability {
328    /// Every required resource and frame is resolvable.
329    Online,
330    /// Some required content is resolvable and some is unavailable.
331    Partial,
332    /// No required content is resolvable.
333    Offline,
334    /// A required resource has multiple plausible candidates.
335    Ambiguous,
336    /// Required resource resolution could not complete safely.
337    Error,
338}
339
340/// The machine-inspectable category of a representation availability issue.
341#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
342#[non_exhaustive]
343pub enum AvailabilityIssueKind {
344    /// A resource has no credible online candidate.
345    OfflineResource,
346    /// A resource has multiple plausible candidates.
347    AmbiguousResource,
348    /// Resolution of a resource failed safely.
349    ResourceError,
350    /// Known frames are absent from an image sequence.
351    MissingFrames,
352}
353
354/// A resource- or frame-specific availability diagnostic.
355#[derive(Clone, Debug, Eq, PartialEq)]
356pub struct AvailabilityIssue {
357    resource_id: ResourceId,
358    required: bool,
359    kind: AvailabilityIssueKind,
360    frames: Vec<i64>,
361}
362
363impl AvailabilityIssue {
364    /// Returns the affected resource or compact sequence resource.
365    #[must_use]
366    pub const fn resource_id(&self) -> ResourceId {
367        self.resource_id
368    }
369
370    /// Returns whether this content is required for a complete representation.
371    #[must_use]
372    pub const fn is_required(&self) -> bool {
373        self.required
374    }
375
376    /// Returns the diagnostic category.
377    #[must_use]
378    pub const fn kind(&self) -> AvailabilityIssueKind {
379        self.kind
380    }
381
382    /// Returns sorted missing frames for [`AvailabilityIssueKind::MissingFrames`].
383    #[must_use]
384    pub fn frames(&self) -> &[i64] {
385        &self.frames
386    }
387}
388
389/// Representation-level availability with ordered per-resource detail.
390#[derive(Clone, Debug, Eq, PartialEq)]
391pub struct RepresentationResolution {
392    representation_id: RepresentationId,
393    availability: RepresentationAvailability,
394    resources: Vec<ResourceResolution>,
395    issues: Vec<AvailabilityIssue>,
396    required_resources: BTreeSet<ResourceId>,
397}
398
399/// Copied verified locations and the coherent database decision they belong to.
400#[derive(Clone, Debug, Eq, PartialEq)]
401pub struct RelinkSelection {
402    base: DecisionBase,
403    representation_id: RepresentationId,
404    locations: Vec<(ResourceId, ResolutionCandidate)>,
405}
406
407impl RelinkSelection {
408    /// Original coherent decision; not a filesystem snapshot.
409    #[must_use]
410    pub const fn base(&self) -> DecisionBase {
411        self.base
412    }
413
414    /// Representation explicitly selected by the caller.
415    #[must_use]
416    pub const fn representation_id(&self) -> RepresentationId {
417        self.representation_id
418    }
419
420    /// Complete required coverage, plus independently verified optional members.
421    #[must_use]
422    pub fn locations(&self) -> &[(ResourceId, ResolutionCandidate)] {
423        &self.locations
424    }
425}
426
427impl RepresentationResolution {
428    /// Aggregates resource results according to content-structure requiredness.
429    ///
430    /// Optional package members produce diagnostics but do not reduce aggregate
431    /// availability. Known missing sequence frames make an otherwise online
432    /// sequence partial.
433    ///
434    /// # Errors
435    ///
436    /// Returns [`ErrorKind::InvalidArgument`] unless the resource results match
437    /// the structure's resources exactly and without duplicates.
438    pub fn aggregate(
439        representation_id: RepresentationId,
440        structure: &ContentStructure,
441        resources: Vec<ResourceResolution>,
442    ) -> Result<Self> {
443        let ordered = order_resource_resolutions(structure, resources)?;
444        let (availability, issues) = inspect_availability(structure, &ordered);
445        Ok(Self {
446            representation_id,
447            availability,
448            resources: ordered,
449            issues,
450            required_resources: structure.members().map_or_else(
451                || structure.resource_ids().into_iter().collect(),
452                |members| {
453                    members
454                        .iter()
455                        .filter(|member| member.is_required())
456                        .map(crate::ResourceMember::resource_id)
457                        .collect()
458                },
459            ),
460        })
461    }
462
463    /// Selects complete, uniquely verified content without additional media I/O.
464    ///
465    /// The caller supplies the base from the same coherent read that supplied
466    /// this resolution's storage inputs. Copied locations outlive that view.
467    /// Optional unverified members are omitted; their diagnostics remain here.
468    ///
469    /// # Errors
470    /// Rejects unavailable required content, ambiguity, partial/unverified
471    /// fingerprints and incomplete or failed search. Confidence alone is not
472    /// proof of complete content verification.
473    pub fn select_verified(&self, base: DecisionBase) -> Result<RelinkSelection> {
474        if self.availability != RepresentationAvailability::Online {
475            return Err(Error::new(
476                ErrorKind::Conflict,
477                "required representation content is not completely available",
478            ));
479        }
480        let mut locations = Vec::new();
481        for resource in &self.resources {
482            let blocked = |evidence: &ResolutionEvidence| {
483                matches!(
484                    evidence.kind(),
485                    EvidenceKind::SearchTruncated | EvidenceKind::DiscoveryError
486                )
487            };
488            if resource.evidence().iter().any(blocked)
489                || resource
490                    .candidates()
491                    .iter()
492                    .any(|candidate| candidate.evidence().iter().any(blocked))
493            {
494                return Err(Error::new(
495                    ErrorKind::Conflict,
496                    "resolution search is incomplete",
497                ));
498            }
499            let candidate = match resource.candidates() {
500                [candidate]
501                    if matches!(
502                        resource.state(),
503                        ResourceResolutionState::ResolvedExact
504                            | ResourceResolutionState::OnlineAtKnownLocator
505                    ) && candidate.evidence().iter().any(|item| {
506                        matches!(
507                            item.kind(),
508                            EvidenceKind::FullHashMatch | EvidenceKind::ExactFingerprintMatch
509                        )
510                    }) && !candidate.evidence().iter().any(|item| {
511                        matches!(
512                            item.kind(),
513                            EvidenceKind::PartialFingerprintMatch
514                                | EvidenceKind::FingerprintNotVerified
515                                | EvidenceKind::FingerprintMismatch
516                                | EvidenceKind::ConflictingCandidate
517                        )
518                    }) =>
519                {
520                    Some(candidate)
521                }
522                _ => None,
523            };
524            if let Some(candidate) = candidate {
525                locations.push((resource.resource_id(), candidate.clone()));
526            } else if self.required_resources.contains(&resource.resource_id()) {
527                return Err(Error::new(
528                    ErrorKind::Conflict,
529                    "required resource has no unique fully verified candidate",
530                ));
531            }
532        }
533        Ok(RelinkSelection {
534            base,
535            representation_id: self.representation_id,
536            locations,
537        })
538    }
539
540    /// Returns the representation whose availability was aggregated.
541    #[must_use]
542    pub const fn representation_id(&self) -> RepresentationId {
543        self.representation_id
544    }
545
546    /// Returns aggregate representation availability.
547    #[must_use]
548    pub const fn availability(&self) -> RepresentationAvailability {
549        self.availability
550    }
551
552    /// Returns results in content-structure resource order.
553    #[must_use]
554    pub fn resources(&self) -> &[ResourceResolution] {
555        &self.resources
556    }
557
558    /// Returns resource- and frame-specific diagnostics.
559    #[must_use]
560    pub fn issues(&self) -> &[AvailabilityIssue] {
561        &self.issues
562    }
563}
564
565#[derive(Default)]
566struct AvailabilityCounts {
567    online_required: usize,
568    offline_required: usize,
569    ambiguous_required: bool,
570    error_required: bool,
571    missing_frames: bool,
572}
573
574impl AvailabilityCounts {
575    const fn availability(&self) -> RepresentationAvailability {
576        if self.error_required {
577            RepresentationAvailability::Error
578        } else if self.ambiguous_required {
579            RepresentationAvailability::Ambiguous
580        } else if self.online_required == 0 {
581            RepresentationAvailability::Offline
582        } else if self.offline_required > 0 || self.missing_frames {
583            RepresentationAvailability::Partial
584        } else {
585            RepresentationAvailability::Online
586        }
587    }
588}
589
590fn order_resource_resolutions(
591    structure: &ContentStructure,
592    resources: Vec<ResourceResolution>,
593) -> Result<Vec<ResourceResolution>> {
594    let expected = structure.resource_ids();
595    if resources.len() != expected.len() {
596        return Err(resource_set_error());
597    }
598    let mut by_id = std::collections::BTreeMap::new();
599    for resource in resources {
600        if by_id.insert(resource.resource_id(), resource).is_some() {
601            return Err(Error::new(
602                ErrorKind::InvalidArgument,
603                "resource resolution is duplicated",
604            ));
605        }
606    }
607    expected
608        .into_iter()
609        .map(|resource_id| by_id.remove(&resource_id).ok_or_else(resource_set_error))
610        .collect()
611}
612
613fn resource_set_error() -> Error {
614    Error::new(
615        ErrorKind::InvalidArgument,
616        "resource resolutions do not match the content structure",
617    )
618}
619
620fn inspect_availability(
621    structure: &ContentStructure,
622    resources: &[ResourceResolution],
623) -> (RepresentationAvailability, Vec<AvailabilityIssue>) {
624    let mut counts = AvailabilityCounts::default();
625    let mut issues = Vec::new();
626    for resource in resources {
627        inspect_resource(structure, resource, &mut counts, &mut issues);
628    }
629    if let Some(descriptor) = structure.image_sequence_descriptor() {
630        let mut missing_frames = descriptor.known_missing_frames().to_vec();
631        if let Some(resource) = resources
632            .iter()
633            .find(|resource| resource.resource_id() == descriptor.resource_id())
634        {
635            missing_frames.extend_from_slice(resource.missing_frames());
636        }
637        missing_frames.sort_unstable();
638        missing_frames.dedup();
639        if !missing_frames.is_empty() {
640            counts.missing_frames = true;
641            issues.push(AvailabilityIssue {
642                resource_id: descriptor.resource_id(),
643                required: true,
644                kind: AvailabilityIssueKind::MissingFrames,
645                frames: missing_frames,
646            });
647        }
648    }
649    (counts.availability(), issues)
650}
651
652fn inspect_resource(
653    structure: &ContentStructure,
654    resource: &ResourceResolution,
655    counts: &mut AvailabilityCounts,
656    issues: &mut Vec<AvailabilityIssue>,
657) {
658    let resource_id = resource.resource_id();
659    let required = resource_is_required(structure, resource_id);
660    let issue_kind = match resource.state() {
661        ResourceResolutionState::OnlineAtKnownLocator
662        | ResourceResolutionState::ResolvedExact
663        | ResourceResolutionState::ResolvedProbable => {
664            counts.online_required += usize::from(required);
665            None
666        }
667        ResourceResolutionState::Offline => {
668            counts.offline_required += usize::from(required);
669            Some(AvailabilityIssueKind::OfflineResource)
670        }
671        ResourceResolutionState::Ambiguous => {
672            counts.ambiguous_required |= required;
673            Some(AvailabilityIssueKind::AmbiguousResource)
674        }
675        ResourceResolutionState::Error => {
676            counts.error_required |= required;
677            Some(AvailabilityIssueKind::ResourceError)
678        }
679    };
680    if let Some(kind) = issue_kind {
681        issues.push(AvailabilityIssue {
682            resource_id,
683            required,
684            kind,
685            frames: Vec::new(),
686        });
687    }
688}
689
690fn resource_is_required(structure: &ContentStructure, resource_id: ResourceId) -> bool {
691    structure.members().is_none_or(|members| {
692        members
693            .iter()
694            .find(|member| member.resource_id() == resource_id)
695            .is_some_and(crate::ResourceMember::is_required)
696    })
697}
698
699#[cfg(test)]
700#[path = "resolution_selection_tests.rs"]
701mod selection_tests;
702
703#[cfg(test)]
704mod tests {
705    use crate::{FrameRange, ImageSequenceDescriptor, RationalRate, ResourceMember, ResourceRole};
706    use proptest::prelude::*;
707
708    use super::*;
709
710    fn candidate(uri: &str, confidence: u16) -> ResolutionCandidate {
711        ResolutionCandidate::new(
712            uri,
713            Confidence::from_basis_points(confidence).expect("test confidence is valid"),
714            vec![ResolutionEvidence::new(EvidenceKind::FileSizeMatch, None)],
715        )
716        .expect("test candidate is valid")
717    }
718
719    fn resource_result(
720        resource_id: ResourceId,
721        state: ResourceResolutionState,
722    ) -> ResourceResolution {
723        let candidates = match state {
724            ResourceResolutionState::OnlineAtKnownLocator
725            | ResourceResolutionState::ResolvedExact
726            | ResourceResolutionState::ResolvedProbable => {
727                vec![candidate(&format!("file:///{resource_id}"), 10_000)]
728            }
729            ResourceResolutionState::Ambiguous => vec![
730                candidate(&format!("file:///a/{resource_id}"), 9_000),
731                candidate(&format!("file:///b/{resource_id}"), 9_000),
732            ],
733            ResourceResolutionState::Offline | ResourceResolutionState::Error => Vec::new(),
734        };
735        ResourceResolution::new(resource_id, state, candidates, Vec::new())
736            .expect("test resource resolution is valid")
737    }
738
739    #[test]
740    fn candidates_are_sorted_deterministically() {
741        let resolution = ResourceResolution::new(
742            ResourceId::new(),
743            ResourceResolutionState::Ambiguous,
744            vec![
745                candidate("file:///z", 8_000),
746                candidate("file:///b", 9_000),
747                candidate("file:///a", 9_000),
748            ],
749            Vec::new(),
750        )
751        .expect("ambiguous result has enough candidates");
752
753        let uris: Vec<_> = resolution
754            .candidates()
755            .iter()
756            .map(ResolutionCandidate::uri)
757            .collect();
758        assert_eq!(uris, ["file:///a", "file:///b", "file:///z"]);
759    }
760
761    #[test]
762    fn ambiguity_cannot_silently_select_one_candidate() {
763        let error = ResourceResolution::new(
764            ResourceId::new(),
765            ResourceResolutionState::Ambiguous,
766            vec![candidate("file:///only", 10_000)],
767            Vec::new(),
768        )
769        .expect_err("one candidate cannot be ambiguous");
770        assert_eq!(error.kind(), ErrorKind::InvalidArgument);
771    }
772
773    #[test]
774    fn optional_package_members_do_not_reduce_availability() {
775        let essence = ResourceId::new();
776        let thumbnail = ResourceId::new();
777        let structure = ContentStructure::package(vec![
778            ResourceMember::new(
779                essence,
780                ResourceRole::new("org.postproject:essence").expect("valid role"),
781                true,
782            ),
783            ResourceMember::new(
784                thumbnail,
785                ResourceRole::new("org.postproject:thumbnail").expect("valid role"),
786                false,
787            ),
788        ])
789        .expect("valid package");
790
791        let resolution = RepresentationResolution::aggregate(
792            RepresentationId::new(),
793            &structure,
794            vec![
795                resource_result(thumbnail, ResourceResolutionState::Offline),
796                resource_result(essence, ResourceResolutionState::OnlineAtKnownLocator),
797            ],
798        )
799        .expect("matching results aggregate");
800
801        assert_eq!(
802            resolution.availability(),
803            RepresentationAvailability::Online
804        );
805        assert_eq!(resolution.resources()[0].resource_id(), essence);
806        assert_eq!(resolution.issues().len(), 1);
807        assert!(!resolution.issues()[0].is_required());
808    }
809
810    #[test]
811    fn some_missing_required_members_make_a_representation_partial() {
812        let first = ResourceId::new();
813        let second = ResourceId::new();
814        let role = ResourceRole::new("org.postproject:essence").expect("valid role");
815        let structure = ContentStructure::ordered_parts(vec![
816            ResourceMember::new(first, role.clone(), true),
817            ResourceMember::new(second, role, true),
818        ])
819        .expect("valid ordered parts");
820
821        let resolution = RepresentationResolution::aggregate(
822            RepresentationId::new(),
823            &structure,
824            vec![
825                resource_result(first, ResourceResolutionState::ResolvedExact),
826                resource_result(second, ResourceResolutionState::Offline),
827            ],
828        )
829        .expect("matching results aggregate");
830
831        assert_eq!(
832            resolution.availability(),
833            RepresentationAvailability::Partial
834        );
835        assert_eq!(
836            resolution.issues()[0].kind(),
837            AvailabilityIssueKind::OfflineResource
838        );
839        assert!(resolution.issues()[0].is_required());
840    }
841
842    #[test]
843    fn known_sequence_gaps_are_partial_with_frame_diagnostics() {
844        let resource_id = ResourceId::new();
845        let descriptor = ImageSequenceDescriptor::new(
846            resource_id,
847            FrameRange::new(1001, 1004, 1).expect("valid frame range"),
848            RationalRate::new(24, 1).expect("valid rate"),
849            vec![1002, 1003],
850        )
851        .expect("valid sequence");
852        let structure = ContentStructure::image_sequence(descriptor);
853
854        let resolution = RepresentationResolution::aggregate(
855            RepresentationId::new(),
856            &structure,
857            vec![resource_result(
858                resource_id,
859                ResourceResolutionState::OnlineAtKnownLocator,
860            )],
861        )
862        .expect("matching results aggregate");
863
864        assert_eq!(
865            resolution.availability(),
866            RepresentationAvailability::Partial
867        );
868        assert_eq!(
869            resolution.issues()[0].kind(),
870            AvailabilityIssueKind::MissingFrames
871        );
872        assert_eq!(resolution.issues()[0].frames(), [1002, 1003]);
873    }
874
875    #[test]
876    fn observed_sequence_gaps_merge_with_recorded_exceptions() {
877        let resource_id = ResourceId::new();
878        let descriptor = ImageSequenceDescriptor::new(
879            resource_id,
880            FrameRange::new(1001, 1004, 1).expect("valid frame range"),
881            RationalRate::new(24, 1).expect("valid rate"),
882            vec![1002],
883        )
884        .expect("valid sequence");
885        let structure = ContentStructure::image_sequence(descriptor);
886        let resource = resource_result(resource_id, ResourceResolutionState::OnlineAtKnownLocator)
887            .with_missing_frames(vec![1004, 1003, 1002])
888            .expect("bounded frame diagnostics");
889
890        let resolution = RepresentationResolution::aggregate(
891            RepresentationId::new(),
892            &structure,
893            vec![resource],
894        )
895        .expect("matching results aggregate");
896
897        assert_eq!(
898            resolution.availability(),
899            RepresentationAvailability::Partial
900        );
901        assert_eq!(resolution.issues()[0].frames(), [1002, 1003, 1004]);
902    }
903
904    #[test]
905    fn aggregate_rejects_the_wrong_resource_set() {
906        let expected = ResourceId::new();
907        let unexpected = ResourceId::new();
908        let error = RepresentationResolution::aggregate(
909            RepresentationId::new(),
910            &ContentStructure::single_resource(expected),
911            vec![resource_result(
912                unexpected,
913                ResourceResolutionState::Offline,
914            )],
915        )
916        .expect_err("unrelated resource must be rejected");
917
918        assert_eq!(error.kind(), ErrorKind::InvalidArgument);
919    }
920
921    proptest! {
922        #[test]
923        fn ordering_is_invariant_under_input_reversal(
924            left_score in 0_u16..=10_000,
925            right_score in 0_u16..=10_000,
926        ) {
927            let id = ResourceId::from_bytes([4; 16]);
928            let forward = ResourceResolution::new(
929                id,
930                ResourceResolutionState::Ambiguous,
931                vec![candidate("file:///a", left_score), candidate("file:///b", right_score)],
932                Vec::new(),
933            ).expect("valid resolution");
934            let reverse = ResourceResolution::new(
935                id,
936                ResourceResolutionState::Ambiguous,
937                vec![candidate("file:///b", right_score), candidate("file:///a", left_score)],
938                Vec::new(),
939            ).expect("valid resolution");
940
941            prop_assert_eq!(forward, reverse);
942        }
943    }
944}