1use 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
13pub const MAX_IMAGE_DIMENSION: u32 = 4_096;
15pub const MAX_IMAGE_BUFFERS: usize = 64;
17pub const MAX_IMAGE_LORAS: usize = 32;
19pub const MAX_IMAGE_OPERATORS: usize = 64;
21pub const MAX_IMAGE_OBSERVATIONS: usize = 64;
23pub const MAX_SELECTOR_LABEL_BYTES: usize = 128;
25pub const MAX_OPERATOR_CONTROL_BYTES: usize = 4_096;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum ImageOperation {
32 TextToImage,
34 ImageToImage,
36 Inpaint,
38 Outpaint,
40 VaeEncode,
42 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "kebab-case")]
58pub enum ImageOutputFormat {
59 Rgb8,
61 Rgba8,
63 Png,
65 Tensor,
67}
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
71#[serde(rename_all = "kebab-case")]
72pub enum ImageBufferRole {
73 PositiveConditioning,
75 NegativeConditioning,
77 SourceImage,
79 ReferenceImage,
81 Mask,
83 Lora,
85 Checkpoint,
87 TensorSnapshot,
89}
90
91#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "kebab-case", tag = "kind")]
94pub enum ImageBufferLayout {
95 Opaque,
97 Utf8,
99 Rgb8 {
101 width: u32,
103 height: u32,
105 row_stride: u64,
107 },
108 Rgba8 {
110 width: u32,
112 height: u32,
114 row_stride: u64,
116 },
117 Gray8 {
119 width: u32,
121 height: u32,
123 row_stride: u64,
125 },
126 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(deny_unknown_fields)]
176pub struct ImageBufferBinding {
177 pub slot: u16,
179 pub role: ImageBufferRole,
181 pub buffer: BufferSpec,
183 pub layout: ImageBufferLayout,
185}
186
187impl ImageBufferBinding {
188 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
251#[serde(rename_all = "kebab-case", tag = "kind")]
252pub enum SeedSelection {
253 Fixed {
255 seed: u64,
257 },
258 WorkerSelected {
260 policy: Digest,
262 },
263}
264
265#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "kebab-case", tag = "kind")]
268pub enum StepSelector {
269 All,
271 Exact {
273 steps: Vec<u32>,
275 },
276}
277
278impl StepSelector {
279 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
316#[serde(deny_unknown_fields)]
317pub struct ScalePoint {
318 pub step: u32,
320 pub scale_bits: u32,
322}
323
324impl ScalePoint {
325 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 pub fn scale(self) -> f32 {
342 f32::from_bits(self.scale_bits)
343 }
344}
345
346#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
348#[serde(deny_unknown_fields)]
349pub struct ScaleSchedule {
350 pub points: Vec<ScalePoint>,
352}
353
354impl ScaleSchedule {
355 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
385#[serde(deny_unknown_fields)]
386pub struct LoraStackEntry {
387 pub input_slot: u16,
389 pub target: Digest,
391 pub scales: ScaleSchedule,
393}
394
395#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
397#[serde(rename_all = "kebab-case", tag = "kind")]
398pub enum TensorSelector {
399 SchedulerState,
401 Conditioning {
403 label: String,
405 },
406 ModelBlock {
408 component: String,
410 block: u32,
412 site: String,
414 },
415}
416
417impl TensorSelector {
418 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
445#[serde(deny_unknown_fields)]
446pub struct OperatorInvocation {
447 pub schema: Digest,
449 pub implementation: Digest,
451 pub selector: TensorSelector,
453 pub steps: StepSelector,
455 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(rename_all = "kebab-case")]
476pub enum ObservationKind {
477 Digest,
479 Statistics,
481 Snapshot,
483}
484
485#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(deny_unknown_fields)]
488pub struct ObservationRequest {
489 pub selector: TensorSelector,
491 pub steps: StepSelector,
493 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
515#[serde(deny_unknown_fields)]
516pub struct ImageExecutionPlan {
517 pub profile: Digest,
519 pub load: Digest,
521 pub operation: ImageOperation,
523 pub width: u32,
525 pub height: u32,
527 pub output_format: ImageOutputFormat,
529 pub seed: SeedSelection,
531 pub rng: Digest,
533 pub placement: Digest,
535 pub schedule: Option<DiffusionSchedule>,
537 pub guidance_scale_bits: u32,
539 pub strength_bits: u32,
541 pub inputs: Vec<ImageBufferBinding>,
543 pub loras: Vec<LoraStackEntry>,
545 pub operators: Vec<OperatorInvocation>,
547 pub observations: Vec<ObservationRequest>,
549}
550
551impl ImageExecutionPlan {
552 pub fn guidance_scale(&self) -> f32 {
554 f32::from_bits(self.guidance_scale_bits)
555 }
556
557 pub fn strength(&self) -> f32 {
559 f32::from_bits(self.strength_bits)
560 }
561
562 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 pub fn digest(&self) -> Result<Digest, CoreError> {
750 self.validate()?;
751 Digest::of_serializable("image-execution-plan-v1", self)
752 }
753}
754
755#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
757#[serde(rename_all = "kebab-case", tag = "kind")]
758pub enum ImageTerminal {
759 Completed,
761 CancelledBeforeStart,
763 CancelledAfterStep {
765 step: u32,
767 },
768}
769
770#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
772#[serde(deny_unknown_fields)]
773pub struct ImageExecutionReceipt {
774 pub plan: Digest,
776 pub backend: Digest,
778 pub profile: Digest,
780 pub session_epoch: u64,
782 pub completed_steps: u32,
784 pub terminal: ImageTerminal,
786 pub outputs: Vec<BufferSpec>,
788 pub checkpoints: Vec<Digest>,
790 pub observations: Vec<Digest>,
792}
793
794impl ImageExecutionReceipt {
795 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 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}