Skip to main content

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