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