Skip to main content

logit_loom_diffusion/
execution_v3.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Versioned whole-plan image graph, routing, and cleanup contracts.
4
5use std::collections::HashSet;
6
7use logit_loom_core::{CoreError, Digest};
8use logit_loom_executor::BufferSpec;
9use serde::{Deserialize, Serialize};
10
11use crate::{
12    ImageBufferLayout, ImageBufferRole, ImageCheckpointPlan, ImageCleanupDisposition,
13    ImageCleanupPolicy, ImageCompositeOperation, ImageCompositeReceipt, ImageCompositeStage,
14    ImageExecutionPlan, ImageOutputFormat, ImageOutputRoute, ImageOutputSource, ImageTerminal,
15    ImageValueSource, MAX_IMAGE_COMPOSITE_STAGES, MAX_IMAGE_GRAPH_SCRATCH_BYTES,
16};
17
18/// Version-three whole-image execution contract.
19///
20/// The version-one primary plan and its identity are preserved unchanged.
21/// This successor adds checkpoint routing, deterministic compositing, explicit
22/// output routes, and request-scope cleanup without reinterpreting the
23/// `image-execution-plan-v1` domain.
24#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct ImageExecutionPlanV3 {
27    /// Exact primary diffusion or VAE operation.
28    pub primary: ImageExecutionPlan,
29    /// Optional transactional checkpoint mechanics.
30    pub checkpoint: ImageCheckpointPlan,
31    /// Ordered deterministic compositing graph.
32    pub composites: Vec<ImageCompositeStage>,
33    /// Ordered caller-owned output routes.
34    pub outputs: Vec<ImageOutputRoute>,
35    /// Request-scope cleanup behavior.
36    pub cleanup: ImageCleanupPolicy,
37}
38
39impl ImageExecutionPlanV3 {
40    /// Validates the primary plan, checkpoint references, ordered graph,
41    /// output routes, and cleanup contract.
42    ///
43    /// # Errors
44    ///
45    /// Returns the first invalid or unsupported graph relationship.
46    pub fn validate(&self) -> Result<(), CoreError> {
47        self.primary.validate()?;
48        if self.primary.output_format != ImageOutputFormat::Rgb8 || self.primary.schedule.is_none()
49        {
50            return Err(CoreError::invalid(
51                "image execution v2 primary",
52                "must be a diffusion operation producing RGB8 bytes",
53            ));
54        }
55        if self.composites.len() > MAX_IMAGE_COMPOSITE_STAGES
56            || self.outputs.is_empty()
57            || self.outputs.len() > crate::MAX_IMAGE_BUFFERS
58        {
59            return Err(CoreError::invalid(
60                "image execution v2 collections",
61                "composite or output route count is outside its public bound",
62            ));
63        }
64        let canvas_bytes = u64::from(self.primary.width)
65            .checked_mul(u64::from(self.primary.height))
66            .and_then(|pixels| pixels.checked_mul(3))
67            .ok_or_else(|| CoreError::invalid("image graph scratch", "canvas overflowed"))?;
68        let retained_images = u64::try_from(self.composites.len())
69            .ok()
70            .and_then(|stages| stages.checked_add(1))
71            .ok_or_else(|| CoreError::invalid("image graph scratch", "stage count overflowed"))?;
72        if canvas_bytes
73            .checked_mul(retained_images)
74            .is_none_or(|bytes| bytes > MAX_IMAGE_GRAPH_SCRATCH_BYTES)
75        {
76            return Err(CoreError::invalid(
77                "image graph scratch",
78                format!("exceeds {MAX_IMAGE_GRAPH_SCRATCH_BYTES} bytes"),
79            ));
80        }
81        self.validate_checkpoint()?;
82        for (index, stage) in self.composites.iter().enumerate() {
83            if usize::from(stage.stage) != index {
84                return Err(CoreError::invalid(
85                    "image composite stages",
86                    "stage indices must be contiguous and declared in order",
87                ));
88            }
89            match stage.operation {
90                ImageCompositeOperation::MaskBlend {
91                    base,
92                    overlay,
93                    mask_slot,
94                } => {
95                    self.validate_rgb_source(base, index)?;
96                    self.validate_rgb_source(overlay, index)?;
97                    self.require_input_layout(mask_slot, ImageLayoutKind::Gray8)?;
98                }
99            }
100        }
101        self.validate_outputs()
102    }
103
104    fn validate_checkpoint(&self) -> Result<(), CoreError> {
105        let Some(schedule) = self.primary.schedule.as_ref() else {
106            if self.checkpoint != ImageCheckpointPlan::default() {
107                return Err(CoreError::invalid(
108                    "image checkpoint plan",
109                    "direct VAE operations cannot restore or capture a diffusion checkpoint",
110                ));
111            }
112            return Ok(());
113        };
114        if let Some(slot) = self.checkpoint.restore_from {
115            let input = self
116                .primary
117                .inputs
118                .iter()
119                .find(|input| input.slot == slot)
120                .ok_or_else(|| {
121                    CoreError::invalid("image checkpoint restore", "does not name an input binding")
122                })?;
123            if input.role != ImageBufferRole::Checkpoint {
124                return Err(CoreError::invalid(
125                    "image checkpoint restore",
126                    "does not name a checkpoint input",
127                ));
128            }
129        }
130        let checkpoint_inputs = self
131            .primary
132            .inputs
133            .iter()
134            .filter(|input| input.role == ImageBufferRole::Checkpoint)
135            .count();
136        if checkpoint_inputs != usize::from(self.checkpoint.restore_from.is_some()) {
137            return Err(CoreError::invalid(
138                "image checkpoint restore",
139                "checkpoint inputs must be consumed exactly once",
140            ));
141        }
142        if self
143            .checkpoint
144            .capture_after_step
145            .is_some_and(|step| usize::try_from(step).map_or(true, |step| step >= schedule.steps()))
146        {
147            return Err(CoreError::invalid(
148                "image checkpoint capture",
149                "step is outside the primary schedule",
150            ));
151        }
152        Ok(())
153    }
154
155    fn validate_outputs(&self) -> Result<(), CoreError> {
156        let mut allocations = HashSet::new();
157        let mut checkpoint_routes = 0_usize;
158        for (index, route) in self.outputs.iter().enumerate() {
159            route.buffer.validate()?;
160            if !allocations.insert(route.buffer.identity.clone()) {
161                return Err(CoreError::invalid(
162                    "image output routes",
163                    "allocation identities must be unique",
164                ));
165            }
166            match route.source {
167                ImageOutputSource::Image { source } => {
168                    self.validate_rgb_source(source, self.composites.len())?;
169                    validate_tight_rgb_output(
170                        &route.layout,
171                        &route.buffer,
172                        self.primary.width,
173                        self.primary.height,
174                    )?;
175                }
176                ImageOutputSource::Checkpoint => {
177                    checkpoint_routes += 1;
178                    if !matches!(route.layout, ImageBufferLayout::Opaque)
179                        || index + 1 != self.outputs.len()
180                    {
181                        return Err(CoreError::invalid(
182                            "image checkpoint output",
183                            "must be the final route and use an opaque buffer layout",
184                        ));
185                    }
186                }
187            }
188        }
189        let expected_checkpoint_routes = usize::from(self.checkpoint.capture_after_step.is_some());
190        if checkpoint_routes != expected_checkpoint_routes {
191            return Err(CoreError::invalid(
192                "image checkpoint output",
193                "must be routed exactly once when checkpoint capture is requested",
194            ));
195        }
196        Ok(())
197    }
198
199    fn validate_rgb_source(
200        &self,
201        source: ImageValueSource,
202        current_stage: usize,
203    ) -> Result<(), CoreError> {
204        match source {
205            ImageValueSource::Primary if self.primary.output_format == ImageOutputFormat::Rgb8 => {
206                Ok(())
207            }
208            ImageValueSource::Primary => Err(CoreError::invalid(
209                "image graph primary source",
210                "must produce RGB8 bytes",
211            )),
212            ImageValueSource::Input { slot } => {
213                self.require_input_layout(slot, ImageLayoutKind::Rgb8)
214            }
215            ImageValueSource::Composite { stage }
216                if usize::from(stage) < current_stage
217                    && usize::from(stage) < self.composites.len() =>
218            {
219                Ok(())
220            }
221            ImageValueSource::Composite { .. } => Err(CoreError::invalid(
222                "image graph composite source",
223                "must name an earlier stage",
224            )),
225        }
226    }
227
228    fn require_input_layout(&self, slot: u16, kind: ImageLayoutKind) -> Result<(), CoreError> {
229        let input = self
230            .primary
231            .inputs
232            .iter()
233            .find(|input| input.slot == slot)
234            .ok_or_else(|| CoreError::invalid("image graph input", "slot is not bound"))?;
235        let (width, height, row_stride, actual) = match input.layout {
236            ImageBufferLayout::Rgb8 {
237                width,
238                height,
239                row_stride,
240            } => (width, height, row_stride, ImageLayoutKind::Rgb8),
241            ImageBufferLayout::Gray8 {
242                width,
243                height,
244                row_stride,
245            } => (width, height, row_stride, ImageLayoutKind::Gray8),
246            _ => {
247                return Err(CoreError::invalid(
248                    "image graph input",
249                    "must use the required byte layout",
250                ));
251            }
252        };
253        let channels = match kind {
254            ImageLayoutKind::Rgb8 => 3_u64,
255            ImageLayoutKind::Gray8 => 1_u64,
256        };
257        let expected_stride = u64::from(self.primary.width)
258            .checked_mul(channels)
259            .ok_or_else(|| CoreError::invalid("image graph stride", "overflowed"))?;
260        if actual != kind
261            || width != self.primary.width
262            || height != self.primary.height
263            || row_stride != expected_stride
264        {
265            return Err(CoreError::invalid(
266                "image graph input",
267                "must be tightly packed at the primary canvas geometry",
268            ));
269        }
270        Ok(())
271    }
272
273    /// Returns the identity of the complete version-three plan.
274    ///
275    /// # Errors
276    ///
277    /// Returns a validation or deterministic serialization error.
278    pub fn digest(&self) -> Result<Digest, CoreError> {
279        self.validate()?;
280        Digest::of_serializable("image-execution-plan-v3", self)
281    }
282}
283
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285enum ImageLayoutKind {
286    Rgb8,
287    Gray8,
288}
289
290/// Exact output write accounting.
291#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(deny_unknown_fields)]
293pub struct ImageOutputReceiptV3 {
294    /// Zero-based route index.
295    pub route: u16,
296    /// Caller-owned allocation identity.
297    pub allocation: Digest,
298    /// Exact initialized output bytes.
299    pub content: Digest,
300    /// Initialized prefix length.
301    pub bytes_written: u64,
302}
303
304/// Deterministic whole-plan receipt for [`ImageExecutionPlanV3`].
305#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
306#[serde(deny_unknown_fields)]
307pub struct ImageExecutionReceiptV3 {
308    /// Exact version-three plan identity.
309    pub plan: Digest,
310    /// Exact backend build/runtime identity.
311    pub backend: Digest,
312    /// Exact primary profile identity.
313    pub profile: Digest,
314    /// Session epoch used by the primary operation.
315    pub session_epoch: u64,
316    /// Completed diffusion transitions.
317    pub completed_steps: u32,
318    /// Terminal execution boundary.
319    pub terminal: ImageTerminal,
320    /// Adapter-specific primary receipt identity, absent for pre-start
321    /// cancellation.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub primary: Option<Digest>,
324    /// Checkpoint lineage in deterministic order: restored receipt, captured
325    /// receipt, then captured envelope bytes, omitting absent mechanics.
326    #[serde(default, skip_serializing_if = "Vec::is_empty")]
327    pub checkpoints: Vec<Digest>,
328    /// Completed deterministic composites in order.
329    #[serde(default, skip_serializing_if = "Vec::is_empty")]
330    pub composites: Vec<ImageCompositeReceipt>,
331    /// Completed output writes in route order.
332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
333    pub outputs: Vec<ImageOutputReceiptV3>,
334    /// Observation result identities in request order.
335    #[serde(default, skip_serializing_if = "Vec::is_empty")]
336    pub observations: Vec<Digest>,
337    /// Request-scope cleanup outcome.
338    pub cleanup: ImageCleanupDisposition,
339}
340
341impl ImageExecutionReceiptV3 {
342    /// Validates plan lineage, terminal position, graph prefix, output writes,
343    /// and cleanup disposition.
344    ///
345    /// # Errors
346    ///
347    /// Returns the first inconsistent receipt field.
348    pub fn validate_for(&self, plan: &ImageExecutionPlanV3) -> Result<(), CoreError> {
349        plan.validate()?;
350        if self.plan != plan.digest()? || self.profile != plan.primary.profile {
351            return Err(CoreError::invalid(
352                "image execution receipt v2",
353                "plan or profile identity differs",
354            ));
355        }
356        let step_count = plan
357            .primary
358            .schedule
359            .as_ref()
360            .map_or(0, crate::DiffusionSchedule::steps);
361        let completed = usize::try_from(self.completed_steps).map_err(|_| {
362            CoreError::invalid("image execution receipt v2", "step count exceeds usize")
363        })?;
364        self.validate_collections(plan, completed, step_count)?;
365        self.validate_terminal(plan, completed, step_count)?;
366        self.validate_cleanup(plan)
367    }
368
369    fn validate_collections(
370        &self,
371        plan: &ImageExecutionPlanV3,
372        completed: usize,
373        step_count: usize,
374    ) -> Result<(), CoreError> {
375        if completed > step_count
376            || self.checkpoints.len() > maximum_checkpoint_lineage(plan)
377            || self.composites.len() > plan.composites.len()
378            || self.outputs.len() > plan.outputs.len()
379            || self.observations.len() > plan.primary.observations.len()
380        {
381            return Err(CoreError::invalid(
382                "image execution receipt v2",
383                "a completed collection or step count exceeds the plan",
384            ));
385        }
386        for (index, composite) in self.composites.iter().enumerate() {
387            if usize::from(composite.stage) != index {
388                return Err(CoreError::invalid(
389                    "image composite receipt",
390                    "stages must form an ordered completed prefix",
391                ));
392            }
393        }
394        for (index, output) in self.outputs.iter().enumerate() {
395            let route = plan.outputs.get(index).ok_or_else(|| {
396                CoreError::invalid("image output receipt", "route is outside the plan")
397            })?;
398            if usize::from(output.route) != index
399                || output.allocation != route.buffer.identity
400                || output.bytes_written == 0
401                || output.bytes_written > route.buffer.byte_length
402                || (matches!(route.source, ImageOutputSource::Image { .. })
403                    && output.bytes_written != route.buffer.byte_length)
404            {
405                return Err(CoreError::invalid(
406                    "image output receipt",
407                    "route, allocation, or initialized length is inconsistent",
408                ));
409            }
410        }
411        Ok(())
412    }
413
414    fn validate_terminal(
415        &self,
416        plan: &ImageExecutionPlanV3,
417        completed: usize,
418        step_count: usize,
419    ) -> Result<(), CoreError> {
420        match self.terminal {
421            ImageTerminal::Completed
422                if completed != step_count
423                    || self.primary.is_none()
424                    || self.checkpoints.len() != maximum_checkpoint_lineage(plan)
425                    || self.composites.len() != plan.composites.len()
426                    || self.outputs.len() != plan.outputs.len()
427                    || self.observations.len() != plan.primary.observations.len() =>
428            {
429                return Err(CoreError::invalid(
430                    "image execution receipt v2",
431                    "completed terminal requires the whole graph and every route",
432                ));
433            }
434            ImageTerminal::CancelledBeforeStart
435                if completed != 0
436                    || self.primary.is_some()
437                    || !self.checkpoints.is_empty()
438                    || !self.composites.is_empty()
439                    || !self.outputs.is_empty()
440                    || !self.observations.is_empty()
441                    || self.cleanup != ImageCleanupDisposition::NotRequired =>
442            {
443                return Err(CoreError::invalid(
444                    "image execution receipt v2",
445                    "pre-start cancellation contains execution side effects",
446                ));
447            }
448            ImageTerminal::CancelledAfterStep { step }
449                if usize::try_from(step)
450                    .ok()
451                    .and_then(|step| step.checked_add(1))
452                    != Some(completed)
453                    || self.primary.is_none()
454                    || self.observations.len() != plan.primary.observations.len() =>
455            {
456                return Err(CoreError::invalid(
457                    "image execution receipt v2",
458                    "cancelled boundary does not match completed steps",
459                ));
460            }
461            _ => {}
462        }
463        if let ImageTerminal::CancelledAfterStep { step } = self.terminal {
464            let capture_reached = plan
465                .checkpoint
466                .capture_after_step
467                .is_some_and(|capture| capture <= step);
468            let minimum = usize::from(capture_reached) * 2;
469            let maximum = minimum + usize::from(plan.checkpoint.restore_from.is_some());
470            if self.checkpoints.len() < minimum || self.checkpoints.len() > maximum {
471                return Err(CoreError::invalid(
472                    "image checkpoint receipt",
473                    "lineage does not match the reached cancellation boundary",
474                ));
475            }
476        }
477        Ok(())
478    }
479
480    fn validate_cleanup(&self, plan: &ImageExecutionPlanV3) -> Result<(), CoreError> {
481        if self.terminal != ImageTerminal::CancelledBeforeStart {
482            match (plan.cleanup, &self.cleanup) {
483                (ImageCleanupPolicy::RetainSession, ImageCleanupDisposition::Retained)
484                | (ImageCleanupPolicy::ClearSession, ImageCleanupDisposition::Confirmed { .. }) => {
485                }
486                _ => {
487                    return Err(CoreError::invalid(
488                        "image execution receipt v2",
489                        "cleanup disposition differs from the plan",
490                    ));
491                }
492            }
493        }
494        Ok(())
495    }
496
497    /// Returns the identity of this exact whole-plan receipt.
498    ///
499    /// # Errors
500    ///
501    /// Returns a validation or deterministic serialization error.
502    pub fn digest_for(&self, plan: &ImageExecutionPlanV3) -> Result<Digest, CoreError> {
503        self.validate_for(plan)?;
504        Digest::of_serializable("image-execution-receipt-v3", self)
505    }
506}
507
508fn maximum_checkpoint_lineage(plan: &ImageExecutionPlanV3) -> usize {
509    usize::from(plan.checkpoint.restore_from.is_some())
510        + usize::from(plan.checkpoint.capture_after_step.is_some()) * 2
511}
512
513fn validate_tight_rgb_output(
514    layout: &ImageBufferLayout,
515    buffer: &BufferSpec,
516    width: u32,
517    height: u32,
518) -> Result<(), CoreError> {
519    let expected_stride = u64::from(width)
520        .checked_mul(3)
521        .ok_or_else(|| CoreError::invalid("image output stride", "overflowed"))?;
522    match layout {
523        ImageBufferLayout::Rgb8 {
524            width: output_width,
525            height: output_height,
526            row_stride,
527        } if *output_width == width
528            && *output_height == height
529            && *row_stride == expected_stride =>
530        {
531            let expected = expected_stride
532                .checked_mul(u64::from(height))
533                .ok_or_else(|| CoreError::invalid("image output length", "overflowed"))?;
534            if buffer.byte_length != expected {
535                return Err(CoreError::invalid(
536                    "image output allocation",
537                    "length differs from the tightly packed RGB8 canvas",
538                ));
539            }
540            Ok(())
541        }
542        _ => Err(CoreError::invalid(
543            "image output route",
544            "must be tightly packed RGB8 at the primary canvas geometry",
545        )),
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use logit_loom_executor::BufferSpec;
552
553    use super::*;
554    use crate::{
555        DiffusionSchedule, ImageBufferBinding, ImageOperation, ObservationRequest, SeedSelection,
556    };
557
558    fn buffer(domain: &str, bytes: u64, media_type: &str) -> BufferSpec {
559        BufferSpec::new(
560            Digest::of_bytes(domain, domain.as_bytes()),
561            bytes,
562            media_type,
563        )
564        .unwrap()
565    }
566
567    fn primary() -> ImageExecutionPlan {
568        let width = 2;
569        let height = 1;
570        let prompt = ImageBufferBinding {
571            slot: 0,
572            role: ImageBufferRole::PositiveConditioning,
573            buffer: buffer("prompt", 4, "text/plain"),
574            layout: ImageBufferLayout::Utf8,
575        };
576        let overlay = ImageBufferBinding {
577            slot: 1,
578            role: ImageBufferRole::ReferenceImage,
579            buffer: buffer("overlay", 6, "image/rgb"),
580            layout: ImageBufferLayout::Rgb8 {
581                width,
582                height,
583                row_stride: 6,
584            },
585        };
586        let mask = ImageBufferBinding {
587            slot: 2,
588            role: ImageBufferRole::Mask,
589            buffer: buffer("mask", 2, "image/gray"),
590            layout: ImageBufferLayout::Gray8 {
591                width,
592                height,
593                row_stride: 2,
594            },
595        };
596        ImageExecutionPlan {
597            profile: Digest::of_bytes("profile", b"one"),
598            load: Digest::of_bytes("load", b"one"),
599            operation: ImageOperation::TextToImage,
600            width,
601            height,
602            output_format: ImageOutputFormat::Rgb8,
603            seed: SeedSelection::Fixed { seed: 7 },
604            rng: Digest::of_bytes("rng", b"one"),
605            placement: Digest::of_bytes("placement", b"one"),
606            schedule: Some(
607                DiffusionSchedule::new(Digest::of_bytes("schedule", b"one"), vec![1.0, 0.0])
608                    .unwrap(),
609            ),
610            guidance_scale_bits: 1.0_f32.to_bits(),
611            strength_bits: 1.0_f32.to_bits(),
612            inputs: vec![prompt, overlay, mask],
613            loras: Vec::new(),
614            operators: Vec::new(),
615            observations: Vec::<ObservationRequest>::new(),
616        }
617    }
618
619    fn graph() -> ImageExecutionPlanV3 {
620        let primary = primary();
621        ImageExecutionPlanV3 {
622            primary,
623            checkpoint: ImageCheckpointPlan::default(),
624            composites: vec![ImageCompositeStage {
625                stage: 0,
626                operation: ImageCompositeOperation::MaskBlend {
627                    base: ImageValueSource::Primary,
628                    overlay: ImageValueSource::Input { slot: 1 },
629                    mask_slot: 2,
630                },
631            }],
632            outputs: vec![ImageOutputRoute {
633                source: ImageOutputSource::Image {
634                    source: ImageValueSource::Composite { stage: 0 },
635                },
636                buffer: buffer("output", 6, "image/rgb"),
637                layout: ImageBufferLayout::Rgb8 {
638                    width: 2,
639                    height: 1,
640                    row_stride: 6,
641                },
642            }],
643            cleanup: ImageCleanupPolicy::RetainSession,
644        }
645    }
646
647    #[test]
648    fn graph_requires_earlier_composites_and_exact_routes() {
649        assert!(graph().validate().is_ok());
650        let mut invalid = graph();
651        invalid.composites[0].operation = ImageCompositeOperation::MaskBlend {
652            base: ImageValueSource::Composite { stage: 0 },
653            overlay: ImageValueSource::Input { slot: 1 },
654            mask_slot: 2,
655        };
656        assert!(invalid.validate().is_err());
657
658        let mut missing_checkpoint = graph();
659        missing_checkpoint.checkpoint.capture_after_step = Some(0);
660        assert!(missing_checkpoint.validate().is_err());
661    }
662
663    #[test]
664    fn version_two_round_trip_preserves_new_identity_domain() {
665        let plan = graph();
666        let encoded = serde_json::to_vec(&plan).unwrap();
667        let decoded: ImageExecutionPlanV3 = serde_json::from_slice(&encoded).unwrap();
668        assert_eq!(decoded, plan);
669        assert_ne!(plan.digest().unwrap(), plan.primary.digest().unwrap());
670
671        let mut value = serde_json::to_value(&plan).unwrap();
672        value
673            .as_object_mut()
674            .unwrap()
675            .insert("future-field".to_owned(), serde_json::Value::Bool(true));
676        assert!(serde_json::from_value::<ImageExecutionPlanV3>(value).is_err());
677    }
678
679    #[test]
680    fn checkpoint_capture_uses_one_final_output_route() {
681        let mut plan = graph();
682        plan.checkpoint.capture_after_step = Some(0);
683        plan.outputs.push(ImageOutputRoute {
684            source: ImageOutputSource::Checkpoint,
685            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
686            layout: ImageBufferLayout::Opaque,
687        });
688        assert!(plan.validate().is_ok());
689        plan.outputs.swap(0, 1);
690        assert!(plan.validate().is_err());
691    }
692
693    #[test]
694    fn mask_blend_is_exact_at_endpoints_and_midpoint() {
695        let base = [0, 10, 20, 100, 110, 120, 20, 40, 60];
696        let overlay = [200, 210, 220, 50, 60, 70, 120, 140, 160];
697        let mask = [0, 255, 128];
698        let mut output = [9_u8; 9];
699        let receipt = crate::mask_blend_rgb8(&base, &overlay, &mask, &mut output).unwrap();
700        assert_eq!(&output[..3], &base[..3]);
701        assert_eq!(&output[3..6], &overlay[3..6]);
702        assert_eq!(&output[6..], &[70, 90, 110]);
703        assert_eq!(
704            receipt.output,
705            Digest::of_bytes("image-composite-rgb8-output-v1", &output)
706        );
707    }
708
709    #[test]
710    fn mask_blend_rejects_before_write() {
711        let mut output = [9_u8; 3];
712        assert!(crate::mask_blend_rgb8(&[0, 0, 0], &[1, 1], &[255], &mut output).is_err());
713        assert_eq!(output, [9; 3]);
714    }
715
716    #[test]
717    fn prestart_cancellation_receipt_has_no_side_effects() {
718        let plan = graph();
719        let mut receipt = ImageExecutionReceiptV3 {
720            plan: plan.digest().unwrap(),
721            backend: Digest::of_bytes("backend", b"one"),
722            profile: plan.primary.profile.clone(),
723            session_epoch: 4,
724            completed_steps: 0,
725            terminal: ImageTerminal::CancelledBeforeStart,
726            primary: None,
727            checkpoints: Vec::new(),
728            composites: Vec::new(),
729            outputs: Vec::new(),
730            observations: Vec::new(),
731            cleanup: ImageCleanupDisposition::NotRequired,
732        };
733        assert!(receipt.digest_for(&plan).is_ok());
734        receipt
735            .checkpoints
736            .push(Digest::of_bytes("checkpoint", b"unexpected"));
737        assert!(receipt.digest_for(&plan).is_err());
738    }
739
740    #[test]
741    fn reached_checkpoint_capture_requires_receipt_and_envelope_lineage() {
742        let mut plan = graph();
743        plan.checkpoint.capture_after_step = Some(0);
744        plan.outputs.push(ImageOutputRoute {
745            source: ImageOutputSource::Checkpoint,
746            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
747            layout: ImageBufferLayout::Opaque,
748        });
749        plan.validate().unwrap();
750        let receipt = ImageExecutionReceiptV3 {
751            plan: plan.digest().unwrap(),
752            backend: Digest::of_bytes("backend", b"one"),
753            profile: plan.primary.profile.clone(),
754            session_epoch: 4,
755            completed_steps: 1,
756            terminal: ImageTerminal::CancelledAfterStep { step: 0 },
757            primary: Some(Digest::of_bytes("primary", b"one")),
758            checkpoints: vec![Digest::of_bytes("checkpoint", b"receipt-only")],
759            composites: Vec::new(),
760            outputs: Vec::new(),
761            observations: Vec::new(),
762            cleanup: ImageCleanupDisposition::Retained,
763        };
764        assert!(receipt.validate_for(&plan).is_err());
765    }
766
767    #[test]
768    fn cancellation_before_capture_can_leave_final_route_uninitialized() {
769        let mut plan = graph();
770        plan.primary.schedule = Some(
771            DiffusionSchedule::new(
772                Digest::of_bytes("schedule", b"two-steps"),
773                vec![1.0, 0.5, 0.0],
774            )
775            .unwrap(),
776        );
777        plan.checkpoint.capture_after_step = Some(1);
778        plan.outputs.push(ImageOutputRoute {
779            source: ImageOutputSource::Checkpoint,
780            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
781            layout: ImageBufferLayout::Opaque,
782        });
783        let receipt = ImageExecutionReceiptV3 {
784            plan: plan.digest().unwrap(),
785            backend: Digest::of_bytes("backend", b"one"),
786            profile: plan.primary.profile.clone(),
787            session_epoch: 4,
788            completed_steps: 1,
789            terminal: ImageTerminal::CancelledAfterStep { step: 0 },
790            primary: Some(Digest::of_bytes("primary", b"one")),
791            checkpoints: Vec::new(),
792            composites: vec![ImageCompositeReceipt {
793                stage: 0,
794                base: Digest::of_bytes("base", b"one"),
795                overlay: Digest::of_bytes("overlay", b"one"),
796                mask: Digest::of_bytes("mask", b"one"),
797                output: Digest::of_bytes("composite", b"one"),
798            }],
799            outputs: vec![ImageOutputReceiptV3 {
800                route: 0,
801                allocation: plan.outputs[0].buffer.identity.clone(),
802                content: Digest::of_bytes("content", b"image"),
803                bytes_written: 6,
804            }],
805            observations: Vec::new(),
806            cleanup: ImageCleanupDisposition::Retained,
807        };
808        assert!(receipt.validate_for(&plan).is_ok());
809    }
810
811    #[test]
812    fn image_routes_require_the_exact_initialized_length() {
813        let plan = graph();
814        let receipt = ImageExecutionReceiptV3 {
815            plan: plan.digest().unwrap(),
816            backend: Digest::of_bytes("backend", b"one"),
817            profile: plan.primary.profile.clone(),
818            session_epoch: 4,
819            completed_steps: 1,
820            terminal: ImageTerminal::Completed,
821            primary: Some(Digest::of_bytes("primary", b"one")),
822            checkpoints: Vec::new(),
823            composites: vec![ImageCompositeReceipt {
824                stage: 0,
825                base: Digest::of_bytes("base", b"one"),
826                overlay: Digest::of_bytes("overlay", b"one"),
827                mask: Digest::of_bytes("mask", b"one"),
828                output: Digest::of_bytes("composite", b"one"),
829            }],
830            outputs: vec![ImageOutputReceiptV3 {
831                route: 0,
832                allocation: plan.outputs[0].buffer.identity.clone(),
833                content: Digest::of_bytes("content", b"short"),
834                bytes_written: 5,
835            }],
836            observations: Vec::new(),
837            cleanup: ImageCleanupDisposition::Retained,
838        };
839        assert!(receipt.validate_for(&plan).is_err());
840    }
841}