Skip to main content

temporal_vision/
provenance.rs

1use std::{collections::BTreeMap, fmt, str::FromStr};
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::{
6    BinaryMask, ComparisonOutcome, DeclaredGap, ErrorCode, FrameRegion, FrameSequence, Marker,
7    PixelDimensions, PresentationTile, Result, SelectionReason, StoryboardSelection, TimeRange,
8    VisionError,
9    sequence::{NonEmptyText, validate_gaps, validate_markers},
10};
11
12stable_registry! {
13    /// Stable visual artifact family.
14    pub enum ArtifactKind {
15        BeforeDuringAfter => "before_during_after",
16        Storyboard => "storyboard",
17        DifferenceMap => "difference_map",
18        RegionFilmstrip => "region_filmstrip",
19        MotionHistory => "motion_history",
20    }
21}
22
23/// Authoritative name/version descriptor for one generated artifact family.
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25pub struct GeneratorDescriptor {
26    pub name: &'static str,
27    pub version: &'static str,
28}
29
30/// One registry drives both generated manifests and callers' pre-generation cache keys.
31pub const fn generator_descriptor(kind: ArtifactKind) -> GeneratorDescriptor {
32    match kind {
33        ArtifactKind::Storyboard | ArtifactKind::BeforeDuringAfter => GeneratorDescriptor {
34            name: "temporal-storyboard",
35            version: "1.1.0",
36        },
37        ArtifactKind::DifferenceMap => GeneratorDescriptor {
38            name: "temporal-difference-map",
39            version: "v1",
40        },
41        ArtifactKind::RegionFilmstrip => GeneratorDescriptor {
42            name: "region-filmstrip",
43            version: "1.0.0",
44        },
45        ArtifactKind::MotionHistory => GeneratorDescriptor {
46            name: "motion-history",
47            version: "1.0.0",
48        },
49    }
50}
51
52stable_registry! {
53    /// Relationship between an output and source observations.
54    pub enum EvidenceClass {
55        SourceFrame => "source_frame",
56        SourceDerived => "source_derived",
57        Inferred => "inferred",
58    }
59}
60
61stable_registry! {
62    /// Stable source-derived normalization operation.
63    pub enum NormalizationKind {
64        ColorSpaceConversion => "color_space_conversion",
65        AlphaCompositing => "alpha_compositing",
66        IntegerScaling => "integer_scaling",
67        FixedCrop => "fixed_crop",
68        Denoising => "denoising",
69        Thresholding => "thresholding",
70    }
71}
72
73/// Named and versioned artifact algorithm.
74#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
75pub struct AlgorithmDescriptor {
76    name: NonEmptyText,
77    version: NonEmptyText,
78}
79
80impl AlgorithmDescriptor {
81    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Result<Self> {
82        Ok(Self {
83            name: NonEmptyText::new(
84                name,
85                ErrorCode::InvalidParameter,
86                "algorithm name must not be empty",
87            )?,
88            version: NonEmptyText::new(
89                version,
90                ErrorCode::InvalidParameter,
91                "algorithm version must not be empty",
92            )?,
93        })
94    }
95
96    pub fn name(&self) -> &str {
97        self.name.as_str()
98    }
99
100    pub fn version(&self) -> &str {
101        self.version.as_str()
102    }
103}
104
105impl<'de> Deserialize<'de> for AlgorithmDescriptor {
106    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
107    where
108        D: Deserializer<'de>,
109    {
110        #[derive(Deserialize)]
111        struct Wire {
112            name: String,
113            version: String,
114        }
115        let wire = Wire::deserialize(deserializer)?;
116        Self::new(wire.name, wire.version).map_err(serde::de::Error::custom)
117    }
118}
119
120/// A finite deterministic floating-point parameter.
121#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
122#[serde(transparent)]
123pub struct FiniteNumber(f64);
124
125impl FiniteNumber {
126    pub fn new(value: f64) -> Result<Self> {
127        if !value.is_finite() {
128            return Err(VisionError::new(
129                ErrorCode::InvalidParameter,
130                "numeric parameters must be finite",
131            ));
132        }
133        Ok(Self(if value == 0.0 { 0.0 } else { value }))
134    }
135
136    pub const fn get(self) -> f64 {
137        self.0
138    }
139}
140
141impl<'de> Deserialize<'de> for FiniteNumber {
142    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
143    where
144        D: Deserializer<'de>,
145    {
146        Self::new(f64::deserialize(deserializer)?).map_err(serde::de::Error::custom)
147    }
148}
149
150/// Recursive, tagged parameter value with deterministic object ordering.
151#[derive(Clone, Debug, PartialEq, Serialize)]
152#[serde(tag = "type", content = "value", rename_all = "snake_case")]
153pub enum ParameterValue {
154    Bool(bool),
155    Signed(i64),
156    Unsigned(u64),
157    Number(FiniteNumber),
158    Text(Box<str>),
159    List(Vec<ParameterValue>),
160    Object(BTreeMap<Box<str>, ParameterValue>),
161}
162
163impl ParameterValue {
164    fn validate(&self) -> Result<()> {
165        match self {
166            Self::List(values) => values.iter().try_for_each(Self::validate),
167            Self::Object(values) => {
168                for (key, value) in values {
169                    if key.is_empty() {
170                        return Err(VisionError::new(
171                            ErrorCode::InvalidParameter,
172                            "parameter object keys must not be empty",
173                        ));
174                    }
175                    value.validate()?;
176                }
177                Ok(())
178            }
179            _ => Ok(()),
180        }
181    }
182}
183
184impl<'de> Deserialize<'de> for ParameterValue {
185    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
186    where
187        D: Deserializer<'de>,
188    {
189        #[derive(Deserialize)]
190        #[serde(tag = "type", content = "value", rename_all = "snake_case")]
191        enum Wire {
192            Bool(bool),
193            Signed(i64),
194            Unsigned(u64),
195            Number(FiniteNumber),
196            Text(Box<str>),
197            List(Vec<Wire>),
198            Object(BTreeMap<Box<str>, Wire>),
199        }
200
201        fn convert(value: Wire) -> ParameterValue {
202            match value {
203                Wire::Bool(value) => ParameterValue::Bool(value),
204                Wire::Signed(value) => ParameterValue::Signed(value),
205                Wire::Unsigned(value) => ParameterValue::Unsigned(value),
206                Wire::Number(value) => ParameterValue::Number(value),
207                Wire::Text(value) => ParameterValue::Text(value),
208                Wire::List(values) => {
209                    ParameterValue::List(values.into_iter().map(convert).collect())
210                }
211                Wire::Object(values) => ParameterValue::Object(
212                    values
213                        .into_iter()
214                        .map(|(key, value)| (key, convert(value)))
215                        .collect(),
216                ),
217            }
218        }
219
220        let value = convert(Wire::deserialize(deserializer)?);
221        value.validate().map_err(serde::de::Error::custom)?;
222        Ok(value)
223    }
224}
225
226/// Artifact parameters with deterministic lexicographic object ordering.
227#[derive(Clone, Debug, Default, PartialEq, Serialize)]
228#[serde(transparent)]
229pub struct Parameters(BTreeMap<Box<str>, ParameterValue>);
230
231impl Parameters {
232    pub fn new(values: BTreeMap<Box<str>, ParameterValue>) -> Result<Self> {
233        for (key, value) in &values {
234            if key.is_empty() {
235                return Err(VisionError::new(
236                    ErrorCode::InvalidParameter,
237                    "parameter names must not be empty",
238                ));
239            }
240            value.validate()?;
241        }
242        Ok(Self(values))
243    }
244
245    pub fn empty() -> Self {
246        Self::default()
247    }
248
249    pub fn get(&self, name: &str) -> Option<&ParameterValue> {
250        self.0.get(name)
251    }
252
253    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&str, &ParameterValue)> {
254        self.0.iter().map(|(name, value)| (name.as_ref(), value))
255    }
256
257    pub(crate) fn insert(&mut self, name: &'static str, value: ParameterValue) -> Result<()> {
258        if name.is_empty() {
259            return Err(VisionError::new(
260                ErrorCode::InvalidParameter,
261                "parameter names must not be empty",
262            ));
263        }
264        value.validate()?;
265        self.0.insert(name.into(), value);
266        Ok(())
267    }
268}
269
270/// The only sampling scheme this crate produces. A disclosure naming anything
271/// else is not describing an artifact these generators made.
272pub(crate) const ANALYSIS_SAMPLING_MODE: &str = "uniform_bounded";
273pub(crate) const ANALYSIS_SAMPLING_SPACING: &str = "uniform";
274/// The complete field set of a sampling disclosure, so an extra member is
275/// rejected rather than silently carried as an unvalidated claim.
276const ANALYSIS_SAMPLING_FIELDS: [&str; 5] = [
277    "analyzed_frame_count",
278    "analyzed_source_indices",
279    "mode",
280    "source_frame_count",
281    "spacing",
282];
283
284pub(crate) fn analysis_sampling_parameters<F, M, G, P>(
285    source: &FrameSequence<F, M, G, P>,
286) -> Result<Option<ParameterValue>>
287where
288    F: Eq,
289    M: Eq,
290    G: Eq,
291    P: AsRef<[u8]>,
292{
293    let Some(indices) = source.source_indices() else {
294        return Ok(None);
295    };
296    // Only a genuinely decimated analysis may claim a sampling mode. An exhaustive
297    // run carries source provenance too, and describing it as `uniform_bounded`
298    // would be a false claim about how the evidence was produced.
299    if indices.len() >= source.source_frame_count() {
300        return Ok(None);
301    }
302    let source_frame_count = u64::try_from(source.source_frame_count()).map_err(|_| {
303        VisionError::new(
304            ErrorCode::InvalidManifest,
305            "analysis sampling source frame count exceeds the manifest format",
306        )
307    })?;
308    let analyzed_frame_count = u64::try_from(indices.len()).map_err(|_| {
309        VisionError::new(
310            ErrorCode::InvalidManifest,
311            "analysis sampling frame count exceeds the manifest format",
312        )
313    })?;
314    let analyzed_source_indices = indices
315        .iter()
316        .map(|index| {
317            u64::try_from(*index)
318                .map(ParameterValue::Unsigned)
319                .map_err(|_| {
320                    VisionError::new(
321                        ErrorCode::InvalidManifest,
322                        "analysis sampling source index exceeds the manifest format",
323                    )
324                })
325        })
326        .collect::<Result<Vec<_>>>()?;
327    Ok(Some(ParameterValue::Object(
328        [
329            (
330                "source_frame_count".into(),
331                ParameterValue::Unsigned(source_frame_count),
332            ),
333            (
334                "analyzed_frame_count".into(),
335                ParameterValue::Unsigned(analyzed_frame_count),
336            ),
337            (
338                "analyzed_source_indices".into(),
339                ParameterValue::List(analyzed_source_indices),
340            ),
341            (
342                "mode".into(),
343                ParameterValue::Text(ANALYSIS_SAMPLING_MODE.into()),
344            ),
345            (
346                "spacing".into(),
347                ParameterValue::Text(ANALYSIS_SAMPLING_SPACING.into()),
348            ),
349        ]
350        .into_iter()
351        .collect(),
352    )))
353}
354
355impl<'de> Deserialize<'de> for Parameters {
356    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
357    where
358        D: Deserializer<'de>,
359    {
360        Self::new(BTreeMap::deserialize(deserializer)?).map_err(serde::de::Error::custom)
361    }
362}
363
364/// One ordered normalization operation included in provenance.
365#[derive(Clone, Debug, PartialEq, Serialize)]
366pub struct NormalizationStep {
367    kind: NormalizationKind,
368    algorithm_version: NonEmptyText,
369    parameters: Parameters,
370}
371
372impl NormalizationStep {
373    pub fn new(
374        kind: NormalizationKind,
375        algorithm_version: impl Into<String>,
376        parameters: Parameters,
377    ) -> Result<Self> {
378        Ok(Self {
379            kind,
380            algorithm_version: NonEmptyText::new(
381                algorithm_version,
382                ErrorCode::InvalidParameter,
383                "normalization algorithm version must not be empty",
384            )?,
385            parameters,
386        })
387    }
388
389    pub const fn kind(&self) -> NormalizationKind {
390        self.kind
391    }
392
393    pub fn algorithm_version(&self) -> &str {
394        self.algorithm_version.as_str()
395    }
396
397    pub const fn parameters(&self) -> &Parameters {
398        &self.parameters
399    }
400}
401
402impl<'de> Deserialize<'de> for NormalizationStep {
403    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
404    where
405        D: Deserializer<'de>,
406    {
407        #[derive(Deserialize)]
408        struct Wire {
409            kind: NormalizationKind,
410            algorithm_version: String,
411            parameters: Parameters,
412        }
413        let wire = Wire::deserialize(deserializer)?;
414        Self::new(wire.kind, wire.algorithm_version, wire.parameters)
415            .map_err(serde::de::Error::custom)
416    }
417}
418
419/// SHA-256 of the exact encoded bytes returned for an artifact.
420#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
421pub struct OutputHash([u8; 32]);
422
423impl OutputHash {
424    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
425        Self(bytes)
426    }
427
428    pub const fn as_bytes(&self) -> &[u8; 32] {
429        &self.0
430    }
431}
432
433impl fmt::Display for OutputHash {
434    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
435        for byte in self.0 {
436            write!(formatter, "{byte:02x}")?;
437        }
438        Ok(())
439    }
440}
441
442impl FromStr for OutputHash {
443    type Err = VisionError;
444
445    fn from_str(value: &str) -> Result<Self> {
446        if value.len() != 64
447            || value
448                .bytes()
449                .any(|byte| !byte.is_ascii_digit() && !(b'a'..=b'f').contains(&byte))
450        {
451            return Err(VisionError::new(
452                ErrorCode::InvalidOutputHash,
453                "output hash must be exactly 64 lowercase hexadecimal characters",
454            ));
455        }
456        let mut bytes = [0_u8; 32];
457        for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
458            bytes[index] = (hex_nibble(pair[0]) << 4) | hex_nibble(pair[1]);
459        }
460        Ok(Self(bytes))
461    }
462}
463
464const fn hex_nibble(value: u8) -> u8 {
465    match value {
466        b'0'..=b'9' => value - b'0',
467        b'a'..=b'f' => value - b'a' + 10,
468        _ => 0,
469    }
470}
471
472impl Serialize for OutputHash {
473    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
474    where
475        S: Serializer,
476    {
477        serializer.collect_str(self)
478    }
479}
480
481impl<'de> Deserialize<'de> for OutputHash {
482    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
483    where
484        D: Deserializer<'de>,
485    {
486        <&str>::deserialize(deserializer)?
487            .parse()
488            .map_err(serde::de::Error::custom)
489    }
490}
491
492/// How a generator consumes the sequence it was handed.
493///
494/// This is the one thing a generator must declare that the manifest cannot work
495/// out for itself, and it is deliberately a two-value choice rather than a
496/// per-generator hook: the declaration says *which shape* the generator has, and
497/// the manifest derives every frame population from it. A generator cannot get
498/// the counts wrong, only the shape — and the shape is checked, because
499/// `SelectedFramesOnly` must name frames the sequence actually contains.
500///
501/// Getting this wrong in the permissive direction is what makes a filmstrip
502/// claim it analyzed five frames when three tiles were rendered and the other
503/// two were never looked at.
504#[derive(Clone, Copy, Debug, Eq, PartialEq)]
505pub enum SequenceConsumption {
506    /// Every decoded frame contributed to the result.
507    ///
508    /// True of difference maps and motion history, which measure across the whole
509    /// decoded sequence, and of storyboards, whose selection is derived by reading
510    /// every frame.
511    EveryDecodedFrame,
512    /// Only the frames the output renders or references contributed.
513    ///
514    /// True of a filmstrip: its tiles are chosen by position in the sequence, and
515    /// a frame that backs no tile is decoded but never examined.
516    SelectedFramesOnly,
517}
518
519/// Reproducible machine-readable provenance for one generated artifact.
520///
521/// Three frame populations are distinguished, narrowest last:
522///
523/// - `source_frame_ids` — every retained frame in the artifact's visual epoch.
524/// - `analyzed_frame_ids` — the frames that actually contributed to the artifact.
525///   Sampling and bounded selection drop source frames here.
526/// - `selected_frame_ids` — the analyzed frames rendered or referenced in the
527///   output. An analysis artifact examines many frames but references only one.
528///
529/// `omitted_frame_count` is `source - analyzed`: frames that contributed nothing.
530/// Frames that were analyzed but not rendered are `analyzed - selected`.
531#[derive(Clone, Debug, PartialEq, Serialize)]
532pub struct ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId> {
533    artifact_id: ArtifactId,
534    artifact_kind: ArtifactKind,
535    evidence_class: EvidenceClass,
536    algorithm: Box<AlgorithmDescriptor>,
537    source_frame_ids: Box<[FrameId]>,
538    analyzed_frame_ids: Box<[FrameId]>,
539    selected_frame_ids: Box<[FrameId]>,
540    storyboard_selection: Option<Box<StoryboardSelection<FrameId>>>,
541    #[serde(skip_serializing_if = "Option::is_none")]
542    presentation_tiles: Option<Box<[PresentationTile<FrameId>]>>,
543    source_frame_count: u64,
544    analyzed_frame_count: u64,
545    omitted_frame_count: u64,
546    range: TimeRange,
547    markers: Box<[Marker<MarkerId>]>,
548    gaps: Box<[DeclaredGap<GapId>]>,
549    region: Option<FrameRegion>,
550    /// Boxed like the other rarely populated members: only region filmstrips carry
551    /// a mask, and an inline one widens every manifest-bearing value.
552    mask: Option<Box<BinaryMask>>,
553    normalization: Box<[NormalizationStep]>,
554    parameters: Parameters,
555    output_dimensions: PixelDimensions,
556    output_hash: OutputHash,
557}
558
559impl<A, F: Clone + Eq, M: Clone + Eq, G: Clone + Eq> ArtifactManifest<A, F, M, G> {
560    #[allow(clippy::too_many_arguments)]
561    pub fn from_sequence<P: AsRef<[u8]>>(
562        artifact_id: A,
563        artifact_kind: ArtifactKind,
564        evidence_class: EvidenceClass,
565        algorithm: AlgorithmDescriptor,
566        sequence: &FrameSequence<F, M, G, P>,
567        selected_frame_ids: Vec<F>,
568        normalization: Vec<NormalizationStep>,
569        parameters: Parameters,
570        output_dimensions: PixelDimensions,
571        output_hash: OutputHash,
572    ) -> Result<Self> {
573        Self::from_sequence_with_trace_and_domain(
574            artifact_id,
575            artifact_kind,
576            evidence_class,
577            algorithm,
578            sequence,
579            sequence.region(),
580            sequence.mask().cloned(),
581            selected_frame_ids,
582            None,
583            SequenceConsumption::EveryDecodedFrame,
584            normalization,
585            parameters,
586            output_dimensions,
587            output_hash,
588        )
589    }
590
591    #[allow(clippy::too_many_arguments)]
592    pub fn from_storyboard_sequence<P: AsRef<[u8]>>(
593        artifact_id: A,
594        artifact_kind: ArtifactKind,
595        evidence_class: EvidenceClass,
596        algorithm: AlgorithmDescriptor,
597        sequence: &FrameSequence<F, M, G, P>,
598        selected_frame_ids: Vec<F>,
599        storyboard_selection: StoryboardSelection<F>,
600        normalization: Vec<NormalizationStep>,
601        parameters: Parameters,
602        output_dimensions: PixelDimensions,
603        output_hash: OutputHash,
604    ) -> Result<Self> {
605        Self::from_sequence_with_trace_and_domain(
606            artifact_id,
607            artifact_kind,
608            evidence_class,
609            algorithm,
610            sequence,
611            sequence.region(),
612            sequence.mask().cloned(),
613            selected_frame_ids,
614            Some(Box::new(storyboard_selection)),
615            SequenceConsumption::EveryDecodedFrame,
616            normalization,
617            parameters,
618            output_dimensions,
619            output_hash,
620        )
621    }
622
623    #[allow(clippy::too_many_arguments)]
624    pub(crate) fn from_sequence_with_domain<P: AsRef<[u8]>>(
625        artifact_id: A,
626        artifact_kind: ArtifactKind,
627        evidence_class: EvidenceClass,
628        algorithm: AlgorithmDescriptor,
629        sequence: &FrameSequence<F, M, G, P>,
630        region: Option<FrameRegion>,
631        mask: Option<BinaryMask>,
632        selected_frame_ids: Vec<F>,
633        consumption: SequenceConsumption,
634        normalization: Vec<NormalizationStep>,
635        parameters: Parameters,
636        output_dimensions: PixelDimensions,
637        output_hash: OutputHash,
638    ) -> Result<Self> {
639        Self::from_sequence_with_trace_and_domain(
640            artifact_id,
641            artifact_kind,
642            evidence_class,
643            algorithm,
644            sequence,
645            region,
646            mask,
647            selected_frame_ids,
648            None,
649            consumption,
650            normalization,
651            parameters,
652            output_dimensions,
653            output_hash,
654        )
655    }
656
657    #[allow(clippy::too_many_arguments)]
658    fn from_sequence_with_trace_and_domain<P: AsRef<[u8]>>(
659        artifact_id: A,
660        artifact_kind: ArtifactKind,
661        evidence_class: EvidenceClass,
662        algorithm: AlgorithmDescriptor,
663        sequence: &FrameSequence<F, M, G, P>,
664        region: Option<FrameRegion>,
665        mask: Option<BinaryMask>,
666        selected_frame_ids: Vec<F>,
667        storyboard_selection: Option<Box<StoryboardSelection<F>>>,
668        consumption: SequenceConsumption,
669        normalization: Vec<NormalizationStep>,
670        parameters: Parameters,
671        output_dimensions: PixelDimensions,
672        output_hash: OutputHash,
673    ) -> Result<Self> {
674        let source_frame_ids: Box<[F]> = sequence.source_frame_ids().to_vec().into_boxed_slice();
675        // Decoding a frame is not the same as consuming it. Which of the two the
676        // generator did is the declaration it makes; the population itself is
677        // derived here, in one place, so that the manifest counts and any sampling
678        // disclosure they carry cannot describe different evidence.
679        let analyzed_frame_ids: Box<[F]> = sequence
680            .frames()
681            .iter()
682            .map(|frame| frame.id().clone())
683            .filter(|id| match consumption {
684                SequenceConsumption::EveryDecodedFrame => true,
685                SequenceConsumption::SelectedFramesOnly => selected_frame_ids.contains(id),
686            })
687            .collect::<Vec<_>>()
688            .into_boxed_slice();
689        if analyzed_frame_ids.len() < selected_frame_ids.len() {
690            return Err(VisionError::new(
691                ErrorCode::InvalidManifest,
692                "manifest selected frames are not all present in the decoded sequence",
693            ));
694        }
695        let source_frame_count = u64::try_from(source_frame_ids.len()).map_err(|_| {
696            VisionError::new(
697                ErrorCode::InvalidManifest,
698                "source frame count exceeds the manifest representation",
699            )
700        })?;
701        let analyzed_frame_count = u64::try_from(analyzed_frame_ids.len()).map_err(|_| {
702            VisionError::new(
703                ErrorCode::InvalidManifest,
704                "analyzed frame count exceeds the manifest representation",
705            )
706        })?;
707        let omitted_frame_count = source_frame_count
708            .checked_sub(analyzed_frame_count)
709            .ok_or_else(|| {
710                VisionError::new(
711                    ErrorCode::InvalidManifest,
712                    "analyzed frame count exceeds source frame count",
713                )
714            })?;
715
716        let storyboard_selection = storyboard_selection
717            .map(|selection| {
718                let selection = *selection;
719                sequence
720                    .source_indices()
721                    .map_or(Ok(Box::new(selection.clone())), |indices| {
722                        selection.remap_source_indices(indices).map(Box::new)
723                    })
724            })
725            .transpose()?;
726        let manifest = Self {
727            artifact_id,
728            artifact_kind,
729            evidence_class,
730            algorithm: Box::new(algorithm),
731            source_frame_ids,
732            analyzed_frame_ids,
733            selected_frame_ids: selected_frame_ids.into_boxed_slice(),
734            storyboard_selection,
735            presentation_tiles: None,
736            source_frame_count,
737            analyzed_frame_count,
738            omitted_frame_count,
739            range: sequence.range(),
740            markers: sequence.markers().to_vec().into_boxed_slice(),
741            gaps: sequence.gaps().to_vec().into_boxed_slice(),
742            region,
743            mask: mask.map(Box::new),
744            normalization: normalization.into_boxed_slice(),
745            parameters,
746            output_dimensions,
747            output_hash,
748        };
749        manifest.validate()?;
750        Ok(manifest)
751    }
752
753    fn validate(&self) -> Result<()> {
754        if self.source_frame_ids.is_empty() {
755            return Err(VisionError::new(
756                ErrorCode::InvalidManifest,
757                "manifest source frames must not be empty",
758            ));
759        }
760        validate_unique(
761            &self.source_frame_ids,
762            "source frame identifiers must be unique",
763        )?;
764        if self.analyzed_frame_ids.is_empty() {
765            return Err(VisionError::new(
766                ErrorCode::InvalidManifest,
767                "manifest analyzed frames must not be empty",
768            ));
769        }
770        validate_ordered_subsequence(
771            &self.source_frame_ids,
772            &self.analyzed_frame_ids,
773            "analyzed frame identifiers must be unique",
774            "analyzed frames must be an ordered subsequence of source frames",
775        )?;
776        validate_ordered_subsequence(
777            &self.analyzed_frame_ids,
778            &self.selected_frame_ids,
779            "selected frame identifiers must be unique",
780            "selected frames must be an ordered subsequence of analyzed frames",
781        )?;
782        self.validate_storyboard_trace()?;
783        self.validate_presentation_tiles()?;
784        let source_count = u64::try_from(self.source_frame_ids.len()).map_err(|_| {
785            VisionError::new(
786                ErrorCode::InvalidManifest,
787                "source frame count is too large",
788            )
789        })?;
790        let analyzed_count = u64::try_from(self.analyzed_frame_ids.len()).map_err(|_| {
791            VisionError::new(
792                ErrorCode::InvalidManifest,
793                "analyzed frame count is too large",
794            )
795        })?;
796        if self.source_frame_count != source_count
797            || self.analyzed_frame_count != analyzed_count
798            || self.omitted_frame_count != source_count - analyzed_count
799        {
800            return Err(VisionError::new(
801                ErrorCode::InvalidManifest,
802                "manifest frame counts contradict its identifiers",
803            ));
804        }
805        self.validate_analysis_sampling_disclosure()?;
806        validate_markers(&self.markers, self.range).map_err(as_manifest_error)?;
807        validate_gaps(&self.gaps, self.range).map_err(as_manifest_error)?;
808        if let (Some(region), Some(mask)) = (self.region, self.mask.as_ref())
809            && !region.rect().fits_within(mask.dimensions())
810        {
811            return Err(VisionError::new(
812                ErrorCode::InvalidManifest,
813                "manifest region does not fit its source mask dimensions",
814            ));
815        }
816        Ok(())
817    }
818
819    pub(crate) fn with_presentation_tiles(
820        mut self,
821        tiles: Vec<PresentationTile<F>>,
822    ) -> Result<Self> {
823        self.presentation_tiles = Some(tiles.into_boxed_slice());
824        self.validate_presentation_tiles()?;
825        Ok(self)
826    }
827
828    fn validate_presentation_tiles(&self) -> Result<()> {
829        let Some(tiles) = self.presentation_tiles.as_deref() else {
830            return Ok(());
831        };
832        if self.artifact_kind != ArtifactKind::Storyboard
833            || tiles.len() != self.selected_frame_ids.len()
834            || tiles.is_empty()
835        {
836            return Err(VisionError::new(
837                ErrorCode::InvalidManifest,
838                "presentation tiles require one rectangle per selected storyboard frame",
839            ));
840        }
841        for (index, (tile, id)) in tiles.iter().zip(self.selected_frame_ids.iter()).enumerate() {
842            let rect = tile.rect();
843            if tile.frame_id() != id || !rect.fits_within(self.output_dimensions) {
844                return Err(VisionError::at(
845                    ErrorCode::InvalidManifest,
846                    "presentation tile identity or bounds contradict the manifest",
847                    index,
848                ));
849            }
850            for prior in &tiles[..index] {
851                let prior = prior.rect();
852                if rect.x() < prior.right_exclusive()?
853                    && prior.x() < rect.right_exclusive()?
854                    && rect.y() < prior.bottom_exclusive()?
855                    && prior.y() < rect.bottom_exclusive()?
856                {
857                    return Err(VisionError::at(
858                        ErrorCode::InvalidManifest,
859                        "presentation tile rectangles must not overlap",
860                        index,
861                    ));
862                }
863            }
864        }
865        Ok(())
866    }
867
868    /// The `analysis_sampling` parameter block is what agent-facing surfaces read to
869    /// warn that an analysis was decimated. It must therefore describe the same
870    /// evidence as the manifest counts, and it must exist whenever an analysis
871    /// artifact actually dropped source frames.
872    fn validate_analysis_sampling_disclosure(&self) -> Result<()> {
873        let decimated = self.analyzed_frame_count < self.source_frame_count;
874        let Some(value) = self.parameters.get("analysis_sampling") else {
875            if decimated
876                && matches!(
877                    self.artifact_kind,
878                    ArtifactKind::DifferenceMap | ArtifactKind::MotionHistory
879                )
880            {
881                return Err(VisionError::new(
882                    ErrorCode::InvalidManifest,
883                    "a decimated analysis manifest must disclose its analysis sampling",
884                ));
885            }
886            return Ok(());
887        };
888        let ParameterValue::Object(values) = value else {
889            return Err(VisionError::new(
890                ErrorCode::InvalidManifest,
891                "analysis sampling disclosure must be an object",
892            ));
893        };
894        for (name, expected) in [
895            ("source_frame_count", self.source_frame_count),
896            ("analyzed_frame_count", self.analyzed_frame_count),
897        ] {
898            if values.get(name) != Some(&ParameterValue::Unsigned(expected)) {
899                return Err(VisionError::new(
900                    ErrorCode::InvalidManifest,
901                    "analysis sampling disclosure contradicts the manifest frame counts",
902                ));
903            }
904        }
905        if !decimated {
906            return Err(VisionError::new(
907                ErrorCode::InvalidManifest,
908                "an undecimated manifest must not claim an analysis sampling mode",
909            ));
910        }
911        // The counts are the smallest part of the claim. `mode` and `spacing` say
912        // *how* frames were chosen, and `analyzed_source_indices` says *which* —
913        // that is the part a reader would use to re-derive the analysis. Checking
914        // only the counts would let a disclosure agree about how many frames were
915        // examined while lying about every one of them.
916        for (name, expected) in [
917            ("mode", ANALYSIS_SAMPLING_MODE),
918            ("spacing", ANALYSIS_SAMPLING_SPACING),
919        ] {
920            let ParameterValue::Text(text) = values.get(name).ok_or_else(|| {
921                VisionError::new(
922                    ErrorCode::InvalidManifest,
923                    "analysis sampling disclosure is missing a required field",
924                )
925            })?
926            else {
927                return Err(VisionError::new(
928                    ErrorCode::InvalidManifest,
929                    "analysis sampling mode and spacing must be text",
930                ));
931            };
932            if text.as_ref() != expected {
933                return Err(VisionError::new(
934                    ErrorCode::InvalidManifest,
935                    "analysis sampling disclosure names a sampling scheme this crate does not produce",
936                ));
937            }
938        }
939        let Some(ParameterValue::List(indices)) = values.get("analyzed_source_indices") else {
940            return Err(VisionError::new(
941                ErrorCode::InvalidManifest,
942                "analysis sampling disclosure must list its analyzed source indices",
943            ));
944        };
945        if indices.len() as u64 != self.analyzed_frame_count {
946            return Err(VisionError::new(
947                ErrorCode::InvalidManifest,
948                "analysis sampling disclosure contradicts the manifest frame counts",
949            ));
950        }
951        let mut previous: Option<u64> = None;
952        for (position, index) in indices.iter().enumerate() {
953            let ParameterValue::Unsigned(index) = index else {
954                return Err(VisionError::new(
955                    ErrorCode::InvalidManifest,
956                    "analysis sampling source indices must be unsigned",
957                ));
958            };
959            if *index >= self.source_frame_count {
960                return Err(VisionError::new(
961                    ErrorCode::InvalidManifest,
962                    "analysis sampling source index lies outside the manifest source frames",
963                ));
964            }
965            // Strictly increasing: sampling selects a subset of the source order,
966            // so a repeat or a reversal describes a selection that cannot have
967            // happened.
968            if previous.is_some_and(|previous| previous >= *index) {
969                return Err(VisionError::new(
970                    ErrorCode::InvalidManifest,
971                    "analysis sampling source indices must be strictly increasing",
972                ));
973            }
974            previous = Some(*index);
975            // Shape alone is not identity. A well-formed, in-range, strictly
976            // increasing index list can still name frames the analysis never
977            // examined — source [f0,f1,f2,f3] analyzed [f0,f2] disclosed as
978            // [0,1] passes every check above while naming f0 and f1. Each index
979            // must therefore resolve, through the manifest's own source order,
980            // to exactly the analyzed frame it claims to identify.
981            let resolved = usize::try_from(*index)
982                .ok()
983                .and_then(|index| self.source_frame_ids.get(index));
984            if resolved != self.analyzed_frame_ids.get(position) {
985                return Err(VisionError::new(
986                    ErrorCode::InvalidManifest,
987                    "analysis sampling source index does not identify the analyzed frame",
988                ));
989            }
990        }
991        // An unrecognised member would be an undocumented claim about the
992        // analysis riding along inside the block agents trust for exactly this.
993        for name in values.keys() {
994            if !ANALYSIS_SAMPLING_FIELDS.contains(&name.as_ref()) {
995                return Err(VisionError::new(
996                    ErrorCode::InvalidManifest,
997                    "analysis sampling disclosure carries an unrecognised field",
998                ));
999            }
1000        }
1001        Ok(())
1002    }
1003
1004    fn validate_storyboard_trace(&self) -> Result<()> {
1005        let storyboard_kind = matches!(
1006            self.artifact_kind,
1007            ArtifactKind::Storyboard | ArtifactKind::BeforeDuringAfter
1008        );
1009        let Some(selection) = self.storyboard_selection.as_ref() else {
1010            if storyboard_kind {
1011                return Err(VisionError::new(
1012                    ErrorCode::InvalidManifest,
1013                    "storyboard manifests require their selection trace",
1014                ));
1015            }
1016            return Ok(());
1017        };
1018        if !storyboard_kind {
1019            return Err(VisionError::new(
1020                ErrorCode::InvalidManifest,
1021                "only storyboard artifacts may carry a storyboard selection trace",
1022            ));
1023        }
1024        selection.validate_local().map_err(as_manifest_error)?;
1025        let source_len = self.source_frame_ids.len();
1026        if selection.after_index() >= source_len
1027            || selection.continuity_segment_count() > source_len
1028        {
1029            return Err(VisionError::new(
1030                ErrorCode::InvalidManifest,
1031                "storyboard selection roles exceed the manifest source frames",
1032            ));
1033        }
1034        for selected in selection.selected_frames() {
1035            if selected.frame_index() >= source_len
1036                || self.source_frame_ids[selected.frame_index()] != *selected.frame_id()
1037                || !self.range.contains(selected.timestamp())
1038            {
1039                return Err(VisionError::new(
1040                    ErrorCode::InvalidManifest,
1041                    "storyboard selected trace disagrees with manifest source identity or time",
1042                ));
1043            }
1044        }
1045        if selection
1046            .omitted_anchors()
1047            .iter()
1048            .any(|anchor| anchor.frame_index() >= source_len)
1049        {
1050            return Err(VisionError::new(
1051                ErrorCode::InvalidManifest,
1052                "storyboard omitted anchors exceed the manifest source frames",
1053            ));
1054        }
1055        let expected_selected: Vec<&F> = match self.artifact_kind {
1056            ArtifactKind::Storyboard => selection
1057                .selected_frames()
1058                .iter()
1059                .map(|frame| frame.frame_id())
1060                .collect(),
1061            ArtifactKind::BeforeDuringAfter => {
1062                let mut indices = vec![
1063                    selection.before_index(),
1064                    selection.during_index(),
1065                    selection.after_index(),
1066                ];
1067                indices.sort_unstable();
1068                indices.dedup();
1069                indices
1070                    .into_iter()
1071                    .map(|index| &self.source_frame_ids[index])
1072                    .collect()
1073            }
1074            _ => unreachable!("non-storyboard traces were rejected"),
1075        };
1076        if expected_selected
1077            .iter()
1078            .copied()
1079            .ne(self.selected_frame_ids.iter())
1080        {
1081            return Err(VisionError::new(
1082                ErrorCode::InvalidManifest,
1083                "storyboard trace does not match manifest selected frame roles",
1084            ));
1085        }
1086
1087        let validate_moment = |moment: &crate::VisualChangeMoment<F>| -> Result<()> {
1088            let comparison = moment.comparison();
1089            if comparison.earlier_frame_index() >= source_len
1090                || comparison.later_frame_index() >= source_len
1091                || self.source_frame_ids[moment.frame_index()] != *moment.frame_id()
1092                || !self.range.contains(moment.timestamp())
1093            {
1094                return Err(VisionError::new(
1095                    ErrorCode::InvalidManifest,
1096                    "storyboard visual moment disagrees with manifest source identity or time",
1097                ));
1098            }
1099            let earlier_nanos = moment
1100                .timestamp()
1101                .as_nanos()
1102                .checked_sub(comparison.elapsed_nanos())
1103                .ok_or_else(|| {
1104                    VisionError::new(
1105                        ErrorCode::InvalidManifest,
1106                        "storyboard visual moment elapsed time precedes the manifest range",
1107                    )
1108                })?;
1109            let comparison_range = TimeRange::new(
1110                crate::Timestamp::from_nanos(earlier_nanos),
1111                moment.timestamp(),
1112            )?;
1113            if !self.range.contains(comparison_range.start())
1114                || self.gaps.iter().any(|gap| {
1115                    gap.range().start() <= comparison_range.end()
1116                        && gap.range().end() >= comparison_range.start()
1117                })
1118                || !matches!(comparison.outcome(), ComparisonOutcome::Measured(_))
1119            {
1120                return Err(VisionError::new(
1121                    ErrorCode::InvalidManifest,
1122                    "storyboard visual moments must not cross declared gaps",
1123                ));
1124            }
1125            if let Some(selected) = selection
1126                .selected_frames()
1127                .iter()
1128                .find(|selected| selected.frame_index() == moment.frame_index())
1129                && selected.timestamp() != moment.timestamp()
1130            {
1131                return Err(VisionError::new(
1132                    ErrorCode::InvalidManifest,
1133                    "storyboard visual moment timestamp disagrees with its selected frame",
1134                ));
1135            }
1136            Ok(())
1137        };
1138        let summary = selection.visual_summary();
1139        for moment in [
1140            summary.first_change(),
1141            summary.peak_baseline_change(),
1142            summary.peak_adjacent_changed_area(),
1143        ]
1144        .into_iter()
1145        .flatten()
1146        {
1147            validate_moment(moment)?;
1148        }
1149        for (moment, reason) in [
1150            (summary.first_change(), SelectionReason::FirstChange),
1151            (
1152                summary.peak_baseline_change(),
1153                SelectionReason::PeakBaselineChange,
1154            ),
1155        ] {
1156            if let Some(moment) = moment {
1157                let represented = selection.selected_frames().iter().any(|frame| {
1158                    frame.frame_index() == moment.frame_index() && frame.reasons().contains(&reason)
1159                }) || selection.omitted_anchors().iter().any(|anchor| {
1160                    anchor.frame_index() == moment.frame_index() && anchor.reason() == reason
1161                });
1162                if !represented {
1163                    return Err(VisionError::new(
1164                        ErrorCode::InvalidManifest,
1165                        "storyboard visual moment is missing its selection reason",
1166                    ));
1167                }
1168            }
1169        }
1170        Ok(())
1171    }
1172
1173    pub const fn artifact_id(&self) -> &A {
1174        &self.artifact_id
1175    }
1176    pub const fn artifact_kind(&self) -> ArtifactKind {
1177        self.artifact_kind
1178    }
1179    pub const fn evidence_class(&self) -> EvidenceClass {
1180        self.evidence_class
1181    }
1182    pub const fn algorithm(&self) -> &AlgorithmDescriptor {
1183        &self.algorithm
1184    }
1185    pub fn source_frame_ids(&self) -> &[F] {
1186        &self.source_frame_ids
1187    }
1188    /// The frames that contributed to this artifact, before render selection.
1189    pub fn analyzed_frame_ids(&self) -> &[F] {
1190        &self.analyzed_frame_ids
1191    }
1192    pub fn selected_frame_ids(&self) -> &[F] {
1193        &self.selected_frame_ids
1194    }
1195    pub fn storyboard_selection(&self) -> Option<&StoryboardSelection<F>> {
1196        self.storyboard_selection.as_deref()
1197    }
1198    /// Exact original-image rectangles when a storyboard uses a separate presentation.
1199    pub fn presentation_tiles(&self) -> Option<&[PresentationTile<F>]> {
1200        self.presentation_tiles.as_deref()
1201    }
1202    pub const fn source_frame_count(&self) -> u64 {
1203        self.source_frame_count
1204    }
1205    pub const fn analyzed_frame_count(&self) -> u64 {
1206        self.analyzed_frame_count
1207    }
1208    /// Source frames that contributed nothing to this artifact.
1209    pub const fn omitted_frame_count(&self) -> u64 {
1210        self.omitted_frame_count
1211    }
1212    pub const fn range(&self) -> TimeRange {
1213        self.range
1214    }
1215    pub fn markers(&self) -> &[Marker<M>] {
1216        &self.markers
1217    }
1218    pub fn gaps(&self) -> &[DeclaredGap<G>] {
1219        &self.gaps
1220    }
1221    pub const fn region(&self) -> Option<FrameRegion> {
1222        self.region
1223    }
1224    pub fn mask(&self) -> Option<&BinaryMask> {
1225        self.mask.as_deref()
1226    }
1227    pub fn normalization(&self) -> &[NormalizationStep] {
1228        &self.normalization
1229    }
1230    pub const fn parameters(&self) -> &Parameters {
1231        &self.parameters
1232    }
1233    pub const fn output_dimensions(&self) -> PixelDimensions {
1234        self.output_dimensions
1235    }
1236    pub const fn output_hash(&self) -> OutputHash {
1237        self.output_hash
1238    }
1239}
1240
1241impl<'de, A, F, M, G> Deserialize<'de> for ArtifactManifest<A, F, M, G>
1242where
1243    A: Deserialize<'de>,
1244    F: Deserialize<'de> + Clone + Eq,
1245    M: Deserialize<'de> + Clone + Eq,
1246    G: Deserialize<'de> + Clone + Eq,
1247{
1248    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1249    where
1250        D: Deserializer<'de>,
1251    {
1252        #[derive(Deserialize)]
1253        #[serde(
1254            bound(
1255                deserialize = "A: Deserialize<'de>, F: Deserialize<'de> + Eq, M: Deserialize<'de>, G: Deserialize<'de>"
1256            ),
1257            deny_unknown_fields
1258        )]
1259        struct Wire<A, F, M, G> {
1260            artifact_id: A,
1261            artifact_kind: ArtifactKind,
1262            evidence_class: EvidenceClass,
1263            algorithm: AlgorithmDescriptor,
1264            source_frame_ids: Box<[F]>,
1265            analyzed_frame_ids: Box<[F]>,
1266            selected_frame_ids: Box<[F]>,
1267            storyboard_selection: Option<Box<StoryboardSelection<F>>>,
1268            presentation_tiles: Option<Box<[PresentationTile<F>]>>,
1269            source_frame_count: u64,
1270            analyzed_frame_count: u64,
1271            omitted_frame_count: u64,
1272            range: TimeRange,
1273            markers: Box<[Marker<M>]>,
1274            gaps: Box<[DeclaredGap<G>]>,
1275            region: Option<FrameRegion>,
1276            mask: Option<Box<BinaryMask>>,
1277            normalization: Box<[NormalizationStep]>,
1278            parameters: Parameters,
1279            output_dimensions: PixelDimensions,
1280            output_hash: OutputHash,
1281        }
1282        let wire = Wire::deserialize(deserializer)?;
1283        let manifest = Self {
1284            artifact_id: wire.artifact_id,
1285            artifact_kind: wire.artifact_kind,
1286            evidence_class: wire.evidence_class,
1287            algorithm: Box::new(wire.algorithm),
1288            source_frame_ids: wire.source_frame_ids,
1289            analyzed_frame_ids: wire.analyzed_frame_ids,
1290            selected_frame_ids: wire.selected_frame_ids,
1291            storyboard_selection: wire.storyboard_selection,
1292            presentation_tiles: wire.presentation_tiles,
1293            source_frame_count: wire.source_frame_count,
1294            analyzed_frame_count: wire.analyzed_frame_count,
1295            omitted_frame_count: wire.omitted_frame_count,
1296            range: wire.range,
1297            markers: wire.markers,
1298            gaps: wire.gaps,
1299            region: wire.region,
1300            mask: wire.mask,
1301            normalization: wire.normalization,
1302            parameters: wire.parameters,
1303            output_dimensions: wire.output_dimensions,
1304            output_hash: wire.output_hash,
1305        };
1306        manifest.validate().map_err(serde::de::Error::custom)?;
1307        Ok(manifest)
1308    }
1309}
1310
1311fn validate_unique<T: Eq>(values: &[T], message: &'static str) -> Result<()> {
1312    for (index, value) in values.iter().enumerate() {
1313        if values[..index].contains(value) {
1314            return Err(VisionError::at(ErrorCode::InvalidManifest, message, index));
1315        }
1316    }
1317    Ok(())
1318}
1319
1320fn validate_ordered_subsequence<F: Eq>(
1321    source: &[F],
1322    subset: &[F],
1323    unique_message: &'static str,
1324    subsequence_message: &'static str,
1325) -> Result<()> {
1326    validate_unique(subset, unique_message)?;
1327    let mut source_index = 0;
1328    for (index, subset_id) in subset.iter().enumerate() {
1329        let Some(offset) = source[source_index..]
1330            .iter()
1331            .position(|source_id| source_id == subset_id)
1332        else {
1333            return Err(VisionError::at(
1334                ErrorCode::InvalidManifest,
1335                subsequence_message,
1336                index,
1337            ));
1338        };
1339        source_index += offset + 1;
1340    }
1341    Ok(())
1342}
1343
1344fn as_manifest_error(error: VisionError) -> VisionError {
1345    VisionError {
1346        code: ErrorCode::InvalidManifest,
1347        message: error.message,
1348        index: error.index,
1349    }
1350}
1351
1352#[cfg(test)]
1353mod tests {
1354    use super::*;
1355
1356    #[test]
1357    fn registries_have_one_stable_wire_table() {
1358        fn check<T>(values: &[T], name: impl Fn(T) -> &'static str)
1359        where
1360            T: Copy + fmt::Display + Serialize + for<'de> Deserialize<'de> + Eq + fmt::Debug,
1361        {
1362            for value in values {
1363                let json = serde_json::to_string(value).unwrap();
1364                assert_eq!(json, format!("\"{}\"", name(*value)));
1365                assert_eq!(serde_json::from_str::<T>(&json).unwrap(), *value);
1366                assert_eq!(value.to_string(), name(*value));
1367            }
1368        }
1369        check(ArtifactKind::ALL, ArtifactKind::as_str);
1370        check(EvidenceClass::ALL, EvidenceClass::as_str);
1371        check(NormalizationKind::ALL, NormalizationKind::as_str);
1372    }
1373
1374    #[test]
1375    fn parameters_are_finite_canonical_and_recursive() {
1376        assert!(FiniteNumber::new(f64::NAN).is_err());
1377        assert_eq!(
1378            FiniteNumber::new(-0.0).unwrap().get().to_bits(),
1379            0.0_f64.to_bits()
1380        );
1381        assert!(
1382            serde_json::from_str::<ParameterValue>(
1383                r#"{"type":"object","value":{"":{"type":"bool","value":true}}}"#
1384            )
1385            .is_err()
1386        );
1387    }
1388
1389    #[test]
1390    fn output_hash_requires_canonical_sha256_hex() {
1391        let hash = OutputHash::from_bytes([0xab; 32]);
1392        let encoded = hash.to_string();
1393        assert_eq!(encoded.len(), 64);
1394        assert_eq!(encoded.parse::<OutputHash>().unwrap(), hash);
1395        assert!(encoded.to_uppercase().parse::<OutputHash>().is_err());
1396        assert!("ab".parse::<OutputHash>().is_err());
1397    }
1398}