Skip to main content

logit_loom_diffusion/
execution.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Serializable whole-image execution plans over exact buffer identities.
4
5use std::collections::HashSet;
6
7use logit_loom_core::{CoreError, Digest};
8use logit_loom_executor::BufferSpec;
9use serde::{Deserialize, Serialize};
10
11use crate::{DiffusionSchedule, TensorDType, TensorSpec};
12
13/// Maximum image dimension accepted by the generic execution contract.
14pub const MAX_IMAGE_DIMENSION: u32 = 4_096;
15/// Maximum input or output buffer bindings in one image execution.
16pub const MAX_IMAGE_BUFFERS: usize = 64;
17/// Maximum ordered `LoRA` entries in one image execution.
18pub const MAX_IMAGE_LORAS: usize = 32;
19/// Maximum installed operator invocations in one image execution.
20pub const MAX_IMAGE_OPERATORS: usize = 64;
21/// Maximum observation requests in one image execution.
22pub const MAX_IMAGE_OBSERVATIONS: usize = 64;
23/// Maximum bytes in one selector label.
24pub const MAX_SELECTOR_LABEL_BYTES: usize = 128;
25/// Maximum schema-specific bytes in one installed operator invocation.
26pub const MAX_OPERATOR_CONTROL_BYTES: usize = 4_096;
27
28/// Whole-image operation selected by an exact execution plan.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum ImageOperation {
32    /// Text conditioning to a new image.
33    TextToImage,
34    /// Source image plus conditioning to a new image.
35    ImageToImage,
36    /// Masked replacement inside a source image.
37    Inpaint,
38    /// Expanded canvas plus mask completion.
39    Outpaint,
40    /// Image bytes to an exact backend latent representation.
41    VaeEncode,
42    /// Exact backend latent representation to image bytes.
43    VaeDecode,
44}
45
46impl ImageOperation {
47    pub(crate) const fn uses_diffusion(self) -> bool {
48        matches!(
49            self,
50            Self::TextToImage | Self::ImageToImage | Self::Inpaint | Self::Outpaint
51        )
52    }
53}
54
55/// Requested final image representation.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum ImageOutputFormat {
59    /// Interleaved red, green, and blue bytes.
60    Rgb8,
61    /// Interleaved red, green, blue, and alpha bytes.
62    Rgba8,
63    /// Lossless PNG bytes.
64    Png,
65    /// Backend-native tensor bytes for VAE encode.
66    Tensor,
67}
68
69/// Logical role of an exact execution buffer.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "kebab-case")]
72pub enum ImageBufferRole {
73    /// Positive prompt bytes or encoded conditioning.
74    PositiveConditioning,
75    /// Negative prompt bytes or encoded conditioning.
76    NegativeConditioning,
77    /// Image-to-image, inpaint, outpaint, or VAE source image.
78    SourceImage,
79    /// Additional independently sized reference image.
80    ReferenceImage,
81    /// Spatial mask.
82    Mask,
83    /// Compatible `LoRA` artifact bytes.
84    Lora,
85    /// Opaque authenticated checkpoint bytes.
86    Checkpoint,
87    /// Explicit typed tensor bytes.
88    TensorSnapshot,
89}
90
91/// Exact interpretation of bytes at the public execution boundary.
92#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "kebab-case", tag = "kind")]
94pub enum ImageBufferLayout {
95    /// Opaque backend bytes whose structure is identified by the media type.
96    Opaque,
97    /// Exact UTF-8 bytes validated when storage is bound.
98    Utf8,
99    /// Interleaved RGB bytes with an explicit row stride.
100    Rgb8 {
101        /// Pixel width.
102        width: u32,
103        /// Pixel height.
104        height: u32,
105        /// Bytes between adjacent rows.
106        row_stride: u64,
107    },
108    /// Interleaved RGBA bytes with an explicit row stride.
109    Rgba8 {
110        /// Pixel width.
111        width: u32,
112        /// Pixel height.
113        height: u32,
114        /// Bytes between adjacent rows.
115        row_stride: u64,
116    },
117    /// Single-channel mask bytes with an explicit row stride.
118    Gray8 {
119        /// Pixel width.
120        width: u32,
121        /// Pixel height.
122        height: u32,
123        /// Bytes between adjacent rows.
124        row_stride: u64,
125    },
126    /// Exact typed tensor bytes.
127    Tensor(TensorSpec),
128}
129
130impl ImageBufferLayout {
131    fn validate(&self, byte_length: u64) -> Result<(), CoreError> {
132        match self {
133            Self::Opaque | Self::Utf8 => Ok(()),
134            Self::Rgb8 {
135                width,
136                height,
137                row_stride,
138            } => validate_image_bytes(*width, *height, *row_stride, 3, byte_length),
139            Self::Rgba8 {
140                width,
141                height,
142                row_stride,
143            } => validate_image_bytes(*width, *height, *row_stride, 4, byte_length),
144            Self::Gray8 {
145                width,
146                height,
147                row_stride,
148            } => validate_image_bytes(*width, *height, *row_stride, 1, byte_length),
149            Self::Tensor(tensor) => {
150                tensor.validate()?;
151                let scalar_bytes = match tensor.dtype {
152                    TensorDType::F32 => 4,
153                    TensorDType::F16 | TensorDType::Bf16 => 2,
154                };
155                let expected = tensor
156                    .elements()?
157                    .checked_mul(scalar_bytes)
158                    .ok_or_else(|| {
159                        CoreError::invalid("image tensor buffer", "byte length overflowed")
160                    })?;
161                if byte_length != expected {
162                    return Err(CoreError::invalid(
163                        "image tensor buffer",
164                        "byte length does not match the tensor contract",
165                    ));
166                }
167                Ok(())
168            }
169        }
170    }
171}
172
173/// One exact input-slot binding in an image execution plan.
174#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(deny_unknown_fields)]
176pub struct ImageBufferBinding {
177    /// Caller-defined slot used by `LoRA` and operator plans.
178    pub slot: u16,
179    /// Logical mechanics role.
180    pub role: ImageBufferRole,
181    /// Exact content/allocation metadata.
182    pub buffer: BufferSpec,
183    /// Exact byte interpretation.
184    pub layout: ImageBufferLayout,
185}
186
187impl ImageBufferBinding {
188    /// Validates metadata, layout, and role compatibility.
189    ///
190    /// # Errors
191    ///
192    /// Returns the first invalid field.
193    pub fn validate(&self) -> Result<(), CoreError> {
194        self.buffer.validate()?;
195        self.layout.validate(self.buffer.byte_length)?;
196        let valid_layout = match self.role {
197            ImageBufferRole::PositiveConditioning | ImageBufferRole::NegativeConditioning => {
198                matches!(
199                    self.layout,
200                    ImageBufferLayout::Utf8 | ImageBufferLayout::Tensor(_)
201                )
202            }
203            ImageBufferRole::SourceImage | ImageBufferRole::ReferenceImage => matches!(
204                self.layout,
205                ImageBufferLayout::Rgb8 { .. } | ImageBufferLayout::Rgba8 { .. }
206            ),
207            ImageBufferRole::Mask => matches!(self.layout, ImageBufferLayout::Gray8 { .. }),
208            ImageBufferRole::Lora | ImageBufferRole::Checkpoint => {
209                matches!(self.layout, ImageBufferLayout::Opaque)
210            }
211            ImageBufferRole::TensorSnapshot => {
212                matches!(self.layout, ImageBufferLayout::Tensor(_))
213            }
214        };
215        if !valid_layout {
216            return Err(CoreError::invalid(
217                "image buffer layout",
218                "is incompatible with the selected role",
219            ));
220        }
221        Ok(())
222    }
223
224    /// Validates bytes that cannot be checked from serialized metadata alone.
225    ///
226    /// # Errors
227    ///
228    /// Returns an error when the exact length differs or UTF-8 is malformed.
229    pub fn validate_bytes(&self, bytes: &[u8]) -> Result<(), CoreError> {
230        self.validate()?;
231        let actual = u64::try_from(bytes.len())
232            .map_err(|_| CoreError::invalid("image buffer bytes", "length exceeds u64"))?;
233        if actual != self.buffer.byte_length {
234            return Err(CoreError::invalid(
235                "image buffer bytes",
236                "length does not match the binding",
237            ));
238        }
239        if matches!(self.layout, ImageBufferLayout::Utf8) && std::str::from_utf8(bytes).is_err() {
240            return Err(CoreError::invalid(
241                "image conditioning bytes",
242                "must be valid UTF-8",
243            ));
244        }
245        Ok(())
246    }
247}
248
249/// Resolution policy for the exact execution seed.
250#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "kebab-case", tag = "kind")]
252pub enum SeedSelection {
253    /// Caller supplied the exact native seed.
254    Fixed {
255        /// Exact native seed.
256        seed: u64,
257    },
258    /// The installed worker policy selects and receipts a seed.
259    WorkerSelected {
260        /// Exact seed-policy implementation.
261        policy: Digest,
262    },
263}
264
265/// Exact schedule boundaries selected for one mechanic.
266#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "kebab-case", tag = "kind")]
268pub enum StepSelector {
269    /// Every completed state transition.
270    All,
271    /// A canonical sorted set of zero-based completed transitions.
272    Exact {
273        /// Strictly increasing step indices.
274        steps: Vec<u32>,
275    },
276}
277
278impl StepSelector {
279    /// Validates selection against an exact step count.
280    ///
281    /// # Errors
282    ///
283    /// Returns an error for an empty, non-canonical, or out-of-range set.
284    pub fn validate_for(&self, step_count: usize) -> Result<(), CoreError> {
285        match self {
286            Self::All if step_count == 0 => Err(CoreError::invalid(
287                "image step selector",
288                "cannot select every step of a non-diffusion operation",
289            )),
290            Self::All => Ok(()),
291            Self::Exact { steps } => {
292                if steps.is_empty() || steps.len() > step_count {
293                    return Err(CoreError::invalid(
294                        "image step selector",
295                        "must contain a bounded non-empty set",
296                    ));
297                }
298                if steps.windows(2).any(|pair| pair[0] >= pair[1])
299                    || steps
300                        .iter()
301                        .any(|step| usize::try_from(*step).map_or(true, |step| step >= step_count))
302                {
303                    return Err(CoreError::invalid(
304                        "image step selector",
305                        "steps must be unique, increasing, and in range",
306                    ));
307                }
308                Ok(())
309            }
310        }
311    }
312}
313
314/// One exact `LoRA` scale beginning at a completed-step boundary.
315#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
316#[serde(deny_unknown_fields)]
317pub struct ScalePoint {
318    /// Zero-based step at which this scale becomes active.
319    pub step: u32,
320    /// Exact IEEE-754 scale bits.
321    pub scale_bits: u32,
322}
323
324impl ScalePoint {
325    /// Constructs a finite scale point.
326    ///
327    /// # Errors
328    ///
329    /// Returns an error when the scale is not finite.
330    pub fn new(step: u32, scale: f32) -> Result<Self, CoreError> {
331        if !scale.is_finite() {
332            return Err(CoreError::invalid("LoRA scale", "must be finite"));
333        }
334        Ok(Self {
335            step,
336            scale_bits: scale.to_bits(),
337        })
338    }
339
340    /// Returns the exact scale.
341    pub fn scale(self) -> f32 {
342        f32::from_bits(self.scale_bits)
343    }
344}
345
346/// Canonical piecewise-constant `LoRA` scale schedule.
347#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(deny_unknown_fields)]
349pub struct ScaleSchedule {
350    /// Strictly increasing scale-change points, beginning at step zero.
351    pub points: Vec<ScalePoint>,
352}
353
354impl ScaleSchedule {
355    /// Validates finite scale points against an execution schedule.
356    ///
357    /// # Errors
358    ///
359    /// Returns an error for a missing zero point, duplicate, or out-of-range
360    /// step.
361    pub fn validate_for(&self, step_count: usize) -> Result<(), CoreError> {
362        if self.points.is_empty()
363            || self.points.len() > step_count
364            || self.points[0].step != 0
365            || self.points.iter().any(|point| {
366                !point.scale().is_finite()
367                    || usize::try_from(point.step).map_or(true, |step| step >= step_count)
368            })
369            || self
370                .points
371                .windows(2)
372                .any(|pair| pair[0].step >= pair[1].step)
373        {
374            return Err(CoreError::invalid(
375                "LoRA scale schedule",
376                "must begin at zero with finite, increasing, in-range points",
377            ));
378        }
379        Ok(())
380    }
381}
382
383/// One entry in the exact ordered `LoRA` stack.
384#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
385#[serde(deny_unknown_fields)]
386pub struct LoraStackEntry {
387    /// Slot of the bound `LoRA` artifact.
388    pub input_slot: u16,
389    /// Exact native target-resolution implementation.
390    pub target: Digest,
391    /// Per-step multiplier schedule.
392    pub scales: ScaleSchedule,
393}
394
395/// Exact tensor site selected by an installed mechanic.
396#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(rename_all = "kebab-case", tag = "kind")]
398pub enum TensorSelector {
399    /// Scheduler state immediately after one state transition.
400    SchedulerState,
401    /// Named conditioning tensor.
402    Conditioning {
403        /// Exact adapter label.
404        label: String,
405    },
406    /// Exact named site inside a model block.
407    ModelBlock {
408        /// Exact component identifier.
409        component: String,
410        /// Zero-based block index.
411        block: u32,
412        /// Exact site label inside the block.
413        site: String,
414    },
415}
416
417impl TensorSelector {
418    /// Validates bounded labels.
419    ///
420    /// # Errors
421    ///
422    /// Returns an error for an empty, oversized, or NUL-containing label.
423    pub fn validate(&self) -> Result<(), CoreError> {
424        let valid = |label: &str| {
425            !label.is_empty() && label.len() <= MAX_SELECTOR_LABEL_BYTES && !label.contains('\0')
426        };
427        match self {
428            Self::SchedulerState => Ok(()),
429            Self::Conditioning { label } if valid(label) => Ok(()),
430            Self::ModelBlock {
431                component, site, ..
432            } if valid(component) && valid(site) => Ok(()),
433            _ => Err(CoreError::invalid(
434                "image tensor selector",
435                format!(
436                    "labels must be non-empty, NUL-free, and at most {MAX_SELECTOR_LABEL_BYTES} bytes"
437                ),
438            )),
439        }
440    }
441}
442
443/// One exact installed operator invocation.
444#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
445#[serde(deny_unknown_fields)]
446pub struct OperatorInvocation {
447    /// Public control schema identity.
448    pub schema: Digest,
449    /// Exact installed implementation identity.
450    pub implementation: Digest,
451    /// Exact native tensor site.
452    pub selector: TensorSelector,
453    /// Boundaries at which the operator runs.
454    pub steps: StepSelector,
455    /// Bounded schema-specific control bytes.
456    pub controls: Vec<u8>,
457}
458
459impl OperatorInvocation {
460    pub(crate) fn validate_for(&self, step_count: usize) -> Result<(), CoreError> {
461        self.selector.validate()?;
462        self.steps.validate_for(step_count)?;
463        if self.controls.len() > MAX_OPERATOR_CONTROL_BYTES {
464            return Err(CoreError::invalid(
465                "image operator controls",
466                format!("exceed {MAX_OPERATOR_CONTROL_BYTES} bytes"),
467            ));
468        }
469        Ok(())
470    }
471}
472
473/// Data retained at selected execution boundaries.
474#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(rename_all = "kebab-case")]
476pub enum ObservationKind {
477    /// Content identity only.
478    Digest,
479    /// Bounded numerical summary.
480    Statistics,
481    /// Exact tensor snapshot in an output buffer.
482    Snapshot,
483}
484
485/// One exact batched observation request.
486#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(deny_unknown_fields)]
488pub struct ObservationRequest {
489    /// Exact native tensor site.
490    pub selector: TensorSelector,
491    /// Boundaries to retain.
492    pub steps: StepSelector,
493    /// Retained representation.
494    pub kind: ObservationKind,
495}
496
497impl ObservationRequest {
498    pub(crate) fn validate_for(&self, step_count: usize) -> Result<(), CoreError> {
499        self.selector.validate()?;
500        self.steps.validate_for(step_count)?;
501        if self.kind == ObservationKind::Snapshot
502            && !matches!(&self.steps, StepSelector::Exact { steps } if steps.len() == 1)
503        {
504            return Err(CoreError::invalid(
505                "image snapshot observation",
506                "must select exactly one post-transition boundary",
507            ));
508        }
509        Ok(())
510    }
511}
512
513/// Complete exact image execution mechanics and input identities.
514#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
515#[serde(deny_unknown_fields)]
516pub struct ImageExecutionPlan {
517    /// Exact compatible profile descriptor.
518    pub profile: Digest,
519    /// Exact resident load identity.
520    pub load: Digest,
521    /// Whole-image operation.
522    pub operation: ImageOperation,
523    /// Output width.
524    pub width: u32,
525    /// Output height.
526    pub height: u32,
527    /// Requested output representation.
528    pub output_format: ImageOutputFormat,
529    /// Exact seed policy.
530    pub seed: SeedSelection,
531    /// Exact RNG implementation.
532    pub rng: Digest,
533    /// Exact placement selected at load.
534    pub placement: Digest,
535    /// Diffusion schedule, absent for direct VAE operations.
536    pub schedule: Option<DiffusionSchedule>,
537    /// Exact IEEE-754 guidance scale bits.
538    pub guidance_scale_bits: u32,
539    /// Exact IEEE-754 source-image strength bits.
540    pub strength_bits: u32,
541    /// Exact input identities and layouts.
542    pub inputs: Vec<ImageBufferBinding>,
543    /// Ordered `LoRA` stack.
544    pub loras: Vec<LoraStackEntry>,
545    /// Ordered installed operators.
546    pub operators: Vec<OperatorInvocation>,
547    /// Batched observation requests.
548    pub observations: Vec<ObservationRequest>,
549}
550
551impl ImageExecutionPlan {
552    /// Returns the exact guidance scale.
553    pub fn guidance_scale(&self) -> f32 {
554        f32::from_bits(self.guidance_scale_bits)
555    }
556
557    /// Returns the exact source-image strength.
558    pub fn strength(&self) -> f32 {
559        f32::from_bits(self.strength_bits)
560    }
561
562    /// Validates bounds, operation requirements, references, and schedules.
563    ///
564    /// # Errors
565    ///
566    /// Returns the first mechanically invalid field.
567    pub fn validate(&self) -> Result<(), CoreError> {
568        self.validate_scalars()?;
569        self.validate_collection_bounds()?;
570        self.validate_inputs()?;
571        let step_count = self.validate_operation()?;
572        self.validate_step_mechanics(step_count)
573    }
574
575    fn validate_scalars(&self) -> Result<(), CoreError> {
576        if self.width == 0
577            || self.height == 0
578            || self.width > MAX_IMAGE_DIMENSION
579            || self.height > MAX_IMAGE_DIMENSION
580        {
581            return Err(CoreError::invalid(
582                "image execution dimensions",
583                format!("must be within 1..={MAX_IMAGE_DIMENSION}"),
584            ));
585        }
586        if !self.guidance_scale().is_finite()
587            || !self.strength().is_finite()
588            || !(0.0..=1.0).contains(&self.strength())
589        {
590            return Err(CoreError::invalid(
591                "image execution scalar",
592                "guidance must be finite and strength must be finite within 0..=1",
593            ));
594        }
595        let output_compatible = match self.operation {
596            ImageOperation::VaeEncode => self.output_format == ImageOutputFormat::Tensor,
597            _ => self.output_format != ImageOutputFormat::Tensor,
598        };
599        if !output_compatible {
600            return Err(CoreError::invalid(
601                "image execution output format",
602                "is incompatible with the selected operation",
603            ));
604        }
605        let strength_compatible = match self.operation {
606            ImageOperation::TextToImage | ImageOperation::VaeEncode | ImageOperation::VaeDecode => {
607                self.strength_bits == 1.0_f32.to_bits()
608            }
609            ImageOperation::ImageToImage | ImageOperation::Inpaint | ImageOperation::Outpaint => {
610                self.strength() > 0.0
611            }
612        };
613        if !strength_compatible {
614            return Err(CoreError::invalid(
615                "image execution strength",
616                "is not canonical for the selected operation",
617            ));
618        }
619        Ok(())
620    }
621
622    fn validate_collection_bounds(&self) -> Result<(), CoreError> {
623        if self.inputs.len() > MAX_IMAGE_BUFFERS
624            || self.loras.len() > MAX_IMAGE_LORAS
625            || self.operators.len() > MAX_IMAGE_OPERATORS
626            || self.observations.len() > MAX_IMAGE_OBSERVATIONS
627        {
628            return Err(CoreError::invalid(
629                "image execution collection",
630                "a public collection bound was exceeded",
631            ));
632        }
633        Ok(())
634    }
635
636    fn validate_inputs(&self) -> Result<(), CoreError> {
637        let mut slots = HashSet::new();
638        for input in &self.inputs {
639            input.validate()?;
640            if !slots.insert(input.slot) {
641                return Err(CoreError::invalid("image input slots", "must be unique"));
642            }
643        }
644        require_single_roles(&self.inputs)?;
645        Ok(())
646    }
647
648    fn validate_operation(&self) -> Result<usize, CoreError> {
649        let has = |role| self.inputs.iter().any(|input| input.role == role);
650        let needs_positive = self.operation.uses_diffusion();
651        let needs_source = matches!(
652            self.operation,
653            ImageOperation::ImageToImage
654                | ImageOperation::Inpaint
655                | ImageOperation::Outpaint
656                | ImageOperation::VaeEncode
657        );
658        let needs_mask = matches!(
659            self.operation,
660            ImageOperation::Inpaint | ImageOperation::Outpaint
661        );
662        let needs_tensor = self.operation == ImageOperation::VaeDecode;
663        if (needs_positive && !has(ImageBufferRole::PositiveConditioning))
664            || (needs_source && !has(ImageBufferRole::SourceImage))
665            || (needs_mask && !has(ImageBufferRole::Mask))
666            || (needs_tensor && !has(ImageBufferRole::TensorSnapshot))
667        {
668            return Err(CoreError::invalid(
669                "image execution inputs",
670                "required operation input is missing",
671            ));
672        }
673        for input in self.inputs.iter().filter(|input| {
674            matches!(
675                input.role,
676                ImageBufferRole::SourceImage | ImageBufferRole::Mask
677            )
678        }) {
679            let geometry = match input.layout {
680                ImageBufferLayout::Rgb8 { width, height, .. }
681                | ImageBufferLayout::Rgba8 { width, height, .. }
682                | ImageBufferLayout::Gray8 { width, height, .. } => Some((width, height)),
683                _ => None,
684            };
685            if geometry != Some((self.width, self.height)) {
686                return Err(CoreError::invalid(
687                    "image execution canvas",
688                    "source and mask geometry must match the requested output",
689                ));
690            }
691        }
692        if self.operation.uses_diffusion() != self.schedule.is_some() {
693            return Err(CoreError::invalid(
694                "image execution schedule",
695                "must be present exactly for diffusion operations",
696            ));
697        }
698        let step_count = self.schedule.as_ref().map_or(0, DiffusionSchedule::steps);
699        if let Some(schedule) = &self.schedule {
700            schedule.validate()?;
701        }
702        Ok(step_count)
703    }
704
705    fn validate_step_mechanics(&self, step_count: usize) -> Result<(), CoreError> {
706        for lora in &self.loras {
707            let Some(input) = self
708                .inputs
709                .iter()
710                .find(|input| input.slot == lora.input_slot)
711            else {
712                return Err(CoreError::invalid(
713                    "image LoRA slot",
714                    "does not name an input binding",
715                ));
716            };
717            if input.role != ImageBufferRole::Lora {
718                return Err(CoreError::invalid(
719                    "image LoRA slot",
720                    "does not name a LoRA input",
721                ));
722            }
723            lora.scales.validate_for(step_count)?;
724        }
725        if !self.operation.uses_diffusion()
726            && (!self.loras.is_empty()
727                || !self.operators.is_empty()
728                || !self.observations.is_empty())
729        {
730            return Err(CoreError::invalid(
731                "image VAE operation",
732                "cannot carry step-scoped LoRAs, operators, or observations",
733            ));
734        }
735        for operator in &self.operators {
736            operator.validate_for(step_count)?;
737        }
738        for observation in &self.observations {
739            observation.validate_for(step_count)?;
740        }
741        Ok(())
742    }
743
744    /// Returns the identity of this exact execution plan.
745    ///
746    /// # Errors
747    ///
748    /// Returns a validation or serialization error.
749    pub fn digest(&self) -> Result<Digest, CoreError> {
750        self.validate()?;
751        Digest::of_serializable("image-execution-plan-v1", self)
752    }
753}
754
755/// Terminal boundary reached by an image execution.
756#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
757#[serde(rename_all = "kebab-case", tag = "kind")]
758pub enum ImageTerminal {
759    /// Every requested operation completed.
760    Completed,
761    /// Cancellation was observed before native execution.
762    CancelledBeforeStart,
763    /// Cancellation was observed after an exact completed diffusion step.
764    CancelledAfterStep {
765        /// Zero-based completed transition.
766        step: u32,
767    },
768}
769
770/// Deterministic mechanical receipt for one image execution.
771#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
772#[serde(deny_unknown_fields)]
773pub struct ImageExecutionReceipt {
774    /// Exact execution-plan identity.
775    pub plan: Digest,
776    /// Exact backend build/runtime identity.
777    pub backend: Digest,
778    /// Exact profile descriptor identity.
779    pub profile: Digest,
780    /// Session epoch used by native handles.
781    pub session_epoch: u64,
782    /// Completed diffusion transitions.
783    pub completed_steps: u32,
784    /// Terminal execution boundary.
785    pub terminal: ImageTerminal,
786    /// Exact produced output metadata.
787    pub outputs: Vec<BufferSpec>,
788    /// Produced checkpoint identities.
789    pub checkpoints: Vec<Digest>,
790    /// Batched observation identities.
791    pub observations: Vec<Digest>,
792}
793
794impl ImageExecutionReceipt {
795    /// Validates position, terminal state, output bounds, and plan identity.
796    ///
797    /// # Errors
798    ///
799    /// Returns the first inconsistent field.
800    pub fn validate_for(&self, plan: &ImageExecutionPlan) -> Result<(), CoreError> {
801        plan.validate()?;
802        if self.plan != plan.digest()? || self.profile != plan.profile {
803            return Err(CoreError::invalid(
804                "image execution receipt",
805                "plan or profile identity differs",
806            ));
807        }
808        if self.outputs.len() > MAX_IMAGE_BUFFERS
809            || self.checkpoints.len() > MAX_IMAGE_BUFFERS
810            || self.observations.len() > MAX_IMAGE_OBSERVATIONS
811        {
812            return Err(CoreError::invalid(
813                "image execution receipt",
814                "a receipt collection bound was exceeded",
815            ));
816        }
817        for output in &self.outputs {
818            output.validate()?;
819        }
820        let step_count = plan.schedule.as_ref().map_or(0, DiffusionSchedule::steps);
821        let completed = usize::try_from(self.completed_steps)
822            .map_err(|_| CoreError::invalid("image execution receipt", "steps exceed usize"))?;
823        if completed > step_count {
824            return Err(CoreError::invalid(
825                "image execution receipt",
826                "completed steps exceed the plan",
827            ));
828        }
829        match self.terminal {
830            ImageTerminal::Completed if completed != step_count => Err(CoreError::invalid(
831                "image execution receipt",
832                "completed terminal requires every planned step",
833            )),
834            ImageTerminal::CancelledBeforeStart if completed != 0 => Err(CoreError::invalid(
835                "image execution receipt",
836                "pre-start cancellation cannot complete steps",
837            )),
838            ImageTerminal::CancelledAfterStep { step }
839                if usize::try_from(step)
840                    .ok()
841                    .and_then(|step| step.checked_add(1))
842                    != Some(completed) =>
843            {
844                Err(CoreError::invalid(
845                    "image execution receipt",
846                    "cancelled boundary does not match completed steps",
847                ))
848            }
849            _ => Ok(()),
850        }
851    }
852
853    /// Returns the identity of this exact mechanical receipt.
854    ///
855    /// # Errors
856    ///
857    /// Returns a validation or serialization error.
858    pub fn digest_for(&self, plan: &ImageExecutionPlan) -> Result<Digest, CoreError> {
859        self.validate_for(plan)?;
860        Digest::of_serializable("image-execution-receipt-v1", self)
861    }
862}
863
864fn validate_image_bytes(
865    width: u32,
866    height: u32,
867    row_stride: u64,
868    channels: u64,
869    byte_length: u64,
870) -> Result<(), CoreError> {
871    if width == 0 || height == 0 || width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION {
872        return Err(CoreError::invalid(
873            "image buffer dimensions",
874            format!("must be within 1..={MAX_IMAGE_DIMENSION}"),
875        ));
876    }
877    let minimum_stride = u64::from(width)
878        .checked_mul(channels)
879        .ok_or_else(|| CoreError::invalid("image buffer stride", "overflowed"))?;
880    let expected = row_stride
881        .checked_mul(u64::from(height))
882        .ok_or_else(|| CoreError::invalid("image buffer length", "overflowed"))?;
883    if row_stride < minimum_stride || byte_length != expected {
884        return Err(CoreError::invalid(
885            "image buffer layout",
886            "stride or byte length is inconsistent",
887        ));
888    }
889    Ok(())
890}
891
892fn require_single_roles(inputs: &[ImageBufferBinding]) -> Result<(), CoreError> {
893    for role in [
894        ImageBufferRole::PositiveConditioning,
895        ImageBufferRole::NegativeConditioning,
896        ImageBufferRole::SourceImage,
897        ImageBufferRole::Mask,
898        ImageBufferRole::Checkpoint,
899        ImageBufferRole::TensorSnapshot,
900    ] {
901        if inputs.iter().filter(|input| input.role == role).count() > 1 {
902            return Err(CoreError::invalid(
903                "image input roles",
904                "a singleton role was repeated",
905            ));
906        }
907    }
908    Ok(())
909}
910
911#[cfg(test)]
912mod tests {
913    use super::*;
914    use crate::{TensorLayout, TensorSpec};
915
916    fn text(slot: u16, role: ImageBufferRole) -> ImageBufferBinding {
917        ImageBufferBinding {
918            slot,
919            role,
920            buffer: BufferSpec::new(
921                Digest::of_bytes("test-input", &slot.to_le_bytes()),
922                5,
923                "text/plain; charset=utf-8",
924            )
925            .unwrap(),
926            layout: ImageBufferLayout::Utf8,
927        }
928    }
929
930    fn schedule() -> DiffusionSchedule {
931        DiffusionSchedule::new(
932            Digest::of_bytes("test-scheduler", b"v1"),
933            vec![1.0, 0.5, 0.0],
934        )
935        .unwrap()
936    }
937
938    fn plan() -> ImageExecutionPlan {
939        ImageExecutionPlan {
940            profile: Digest::of_bytes("profile", b"krea"),
941            load: Digest::of_bytes("load", b"resident"),
942            operation: ImageOperation::TextToImage,
943            width: 512,
944            height: 512,
945            output_format: ImageOutputFormat::Rgb8,
946            seed: SeedSelection::Fixed { seed: 7 },
947            rng: Digest::of_bytes("rng", b"cpu"),
948            placement: Digest::of_bytes("placement", b"vulkan0"),
949            schedule: Some(schedule()),
950            guidance_scale_bits: 1.0_f32.to_bits(),
951            strength_bits: 1.0_f32.to_bits(),
952            inputs: vec![text(0, ImageBufferRole::PositiveConditioning)],
953            loras: Vec::new(),
954            operators: Vec::new(),
955            observations: Vec::new(),
956        }
957    }
958
959    #[test]
960    fn text_to_image_plan_round_trips_with_exact_float_bits() {
961        let plan = plan();
962        plan.validate().unwrap();
963        let encoded = serde_json::to_vec(&plan).unwrap();
964        let decoded: ImageExecutionPlan = serde_json::from_slice(&encoded).unwrap();
965        assert_eq!(decoded, plan);
966        assert_eq!(decoded.digest().unwrap(), plan.digest().unwrap());
967    }
968
969    #[test]
970    fn operation_requirements_and_duplicate_slots_fail_closed() {
971        let mut value = plan();
972        value.operation = ImageOperation::Inpaint;
973        assert!(value.validate().is_err());
974
975        let mut value = plan();
976        value
977            .inputs
978            .push(text(0, ImageBufferRole::NegativeConditioning));
979        assert!(value.validate().is_err());
980    }
981
982    #[test]
983    fn operation_output_strength_and_canvas_are_canonical() {
984        let mut value = plan();
985        value.output_format = ImageOutputFormat::Tensor;
986        assert!(value.validate().is_err());
987
988        let mut value = plan();
989        value.strength_bits = 0.5_f32.to_bits();
990        assert!(value.validate().is_err());
991
992        let mut value = plan();
993        value.operation = ImageOperation::ImageToImage;
994        value.strength_bits = 0.5_f32.to_bits();
995        value.inputs.push(ImageBufferBinding {
996            slot: 1,
997            role: ImageBufferRole::SourceImage,
998            buffer: BufferSpec::new(
999                Digest::of_bytes("test-source", b"wrong-canvas"),
1000                u64::from(256_u32 * 256 * 3),
1001                "image/rgb8",
1002            )
1003            .unwrap(),
1004            layout: ImageBufferLayout::Rgb8 {
1005                width: 256,
1006                height: 256,
1007                row_stride: 256 * 3,
1008            },
1009        });
1010        assert!(value.validate().is_err());
1011    }
1012
1013    #[test]
1014    fn lora_schedule_is_ordered_and_bound_to_a_lora_slot() {
1015        let mut value = plan();
1016        value.inputs.push(ImageBufferBinding {
1017            slot: 3,
1018            role: ImageBufferRole::Lora,
1019            buffer: BufferSpec::new(
1020                Digest::of_bytes("test-lora", b"adapter"),
1021                7,
1022                "application/x-safetensors",
1023            )
1024            .unwrap(),
1025            layout: ImageBufferLayout::Opaque,
1026        });
1027        value.loras.push(LoraStackEntry {
1028            input_slot: 3,
1029            target: Digest::of_bytes("lora-target", b"all"),
1030            scales: ScaleSchedule {
1031                points: vec![
1032                    ScalePoint::new(0, 0.5).unwrap(),
1033                    ScalePoint::new(1, -0.25).unwrap(),
1034                ],
1035            },
1036        });
1037        value.validate().unwrap();
1038        value.loras[0].scales.points.swap(0, 1);
1039        assert!(value.validate().is_err());
1040    }
1041
1042    #[test]
1043    fn snapshot_observation_names_one_exact_boundary() {
1044        let mut value = plan();
1045        value.observations.push(ObservationRequest {
1046            selector: TensorSelector::SchedulerState,
1047            steps: StepSelector::Exact { steps: vec![1] },
1048            kind: ObservationKind::Snapshot,
1049        });
1050        value.validate().unwrap();
1051
1052        value.observations[0].steps = StepSelector::All;
1053        assert!(value.validate().is_err());
1054        value.observations[0].steps = StepSelector::Exact { steps: vec![0, 1] };
1055        assert!(value.validate().is_err());
1056    }
1057
1058    #[test]
1059    fn buffer_layout_checks_exact_bytes_and_utf8() {
1060        let binding = text(0, ImageBufferRole::PositiveConditioning);
1061        assert!(binding.validate_bytes(b"hello").is_ok());
1062        assert!(
1063            binding
1064                .validate_bytes(&[0xff, 0xff, 0xff, 0xff, 0xff])
1065                .is_err()
1066        );
1067
1068        let tensor = TensorSpec::new(
1069            vec![2, 2],
1070            TensorDType::F32,
1071            TensorLayout::DimensionZeroFastest,
1072            "host",
1073        )
1074        .unwrap();
1075        let binding = ImageBufferBinding {
1076            slot: 1,
1077            role: ImageBufferRole::TensorSnapshot,
1078            buffer: BufferSpec::new(
1079                Digest::of_bytes("test-tensor", b"bytes"),
1080                15,
1081                "application/octet-stream",
1082            )
1083            .unwrap(),
1084            layout: ImageBufferLayout::Tensor(tensor),
1085        };
1086        assert!(binding.validate().is_err());
1087    }
1088
1089    #[test]
1090    fn receipt_binds_exact_terminal_boundary() {
1091        let plan = plan();
1092        let receipt = ImageExecutionReceipt {
1093            plan: plan.digest().unwrap(),
1094            backend: Digest::of_bytes("backend", b"test"),
1095            profile: plan.profile.clone(),
1096            session_epoch: 4,
1097            completed_steps: 2,
1098            terminal: ImageTerminal::Completed,
1099            outputs: vec![
1100                BufferSpec::new(
1101                    Digest::of_bytes("output", b"rgb"),
1102                    u64::from(512_u32 * 512 * 3),
1103                    "image/rgb8",
1104                )
1105                .unwrap(),
1106            ],
1107            checkpoints: Vec::new(),
1108            observations: Vec::new(),
1109        };
1110        receipt.validate_for(&plan).unwrap();
1111        let mut cancelled = receipt.clone();
1112        cancelled.terminal = ImageTerminal::CancelledAfterStep { step: 0 };
1113        assert!(cancelled.validate_for(&plan).is_err());
1114    }
1115}