logit-loom-diffusion 0.2.0

Backend-neutral diffusion step contracts and transactional interventions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Versioned whole-plan image graph, routing, and cleanup contracts.

use std::collections::HashSet;

use logit_loom_core::{CoreError, Digest};
use logit_loom_executor::BufferSpec;
use serde::{Deserialize, Serialize};

use crate::{
    ImageBufferLayout, ImageBufferRole, ImageExecutionPlan, ImageOutputFormat, ImageTerminal,
};

/// Maximum deterministic compositing stages in one image plan.
pub const MAX_IMAGE_COMPOSITE_STAGES: usize = 32;
/// Maximum aggregate primary-plus-composite scratch bytes in one image graph.
pub const MAX_IMAGE_GRAPH_SCRATCH_BYTES: u64 = 512 * 1024 * 1024;

/// One image value available to a deterministic postprocess stage or output
/// route.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum ImageValueSource {
    /// Output of the primary diffusion or VAE-decode operation.
    Primary,
    /// Exact image input bound to the primary plan.
    Input {
        /// Caller-defined image input slot.
        slot: u16,
    },
    /// Output of an earlier compositing stage.
    Composite {
        /// Zero-based stage index.
        stage: u16,
    },
}

/// One deterministic postprocess operation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum ImageCompositeOperation {
    /// Per-channel linear interpolation between two RGB8 images using one
    /// Gray8 mask.
    ///
    /// A mask byte of zero selects `base`; 255 selects `overlay`. Intermediate
    /// values use integer round-to-nearest:
    /// `(base * (255 - mask) + overlay * mask + 127) / 255`.
    MaskBlend {
        /// First RGB8 value.
        base: ImageValueSource,
        /// Second RGB8 value.
        overlay: ImageValueSource,
        /// Gray8 input slot.
        mask_slot: u16,
    },
}

/// One ordered deterministic compositing stage.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageCompositeStage {
    /// Zero-based stage index. Stages must be contiguous and declared in
    /// execution order.
    pub stage: u16,
    /// Exact compositing operation.
    pub operation: ImageCompositeOperation,
}

/// Transactional checkpoint mechanics around the primary diffusion
/// operation.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageCheckpointPlan {
    /// Opaque checkpoint input slot restored before installed interventions at
    /// its bound post-step boundary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restore_from: Option<u16>,
    /// Post-step boundary captured before installed interventions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_after_step: Option<u32>,
}

/// Value routed into one caller-owned output allocation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum ImageOutputSource {
    /// Exact image value.
    Image {
        /// Primary, input, or prior composite output.
        source: ImageValueSource,
    },
    /// Captured opaque checkpoint envelope.
    Checkpoint,
}

/// One ordered output route.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageOutputRoute {
    /// Value written to this route.
    pub source: ImageOutputSource,
    /// Exact caller-owned allocation metadata.
    pub buffer: BufferSpec,
    /// Exact output byte interpretation.
    pub layout: ImageBufferLayout,
}

/// Request-scope native cleanup behavior.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ImageCleanupPolicy {
    /// Retain the known resident session for an explicit later cleanup.
    RetainSession,
    /// Confirm request-local cleanup and advance the session epoch before
    /// returning.
    ClearSession,
}

/// Version-two whole-image execution contract.
///
/// The version-one primary plan and its identity are preserved unchanged.
/// This successor adds checkpoint routing, deterministic compositing, explicit
/// output routes, and request-scope cleanup without reinterpreting the
/// `image-execution-plan-v1` domain.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageExecutionPlanV2 {
    /// Exact primary diffusion or VAE operation.
    pub primary: ImageExecutionPlan,
    /// Optional transactional checkpoint mechanics.
    pub checkpoint: ImageCheckpointPlan,
    /// Ordered deterministic compositing graph.
    pub composites: Vec<ImageCompositeStage>,
    /// Ordered caller-owned output routes.
    pub outputs: Vec<ImageOutputRoute>,
    /// Request-scope cleanup behavior.
    pub cleanup: ImageCleanupPolicy,
}

impl ImageExecutionPlanV2 {
    /// Validates the primary plan, checkpoint references, ordered graph,
    /// output routes, and cleanup contract.
    ///
    /// # Errors
    ///
    /// Returns the first invalid or unsupported graph relationship.
    pub fn validate(&self) -> Result<(), CoreError> {
        self.primary.validate()?;
        if self.primary.output_format != ImageOutputFormat::Rgb8 || self.primary.schedule.is_none()
        {
            return Err(CoreError::invalid(
                "image execution v2 primary",
                "must be a diffusion operation producing RGB8 bytes",
            ));
        }
        if self.composites.len() > MAX_IMAGE_COMPOSITE_STAGES
            || self.outputs.is_empty()
            || self.outputs.len() > crate::MAX_IMAGE_BUFFERS
        {
            return Err(CoreError::invalid(
                "image execution v2 collections",
                "composite or output route count is outside its public bound",
            ));
        }
        let canvas_bytes = u64::from(self.primary.width)
            .checked_mul(u64::from(self.primary.height))
            .and_then(|pixels| pixels.checked_mul(3))
            .ok_or_else(|| CoreError::invalid("image graph scratch", "canvas overflowed"))?;
        let retained_images = u64::try_from(self.composites.len())
            .ok()
            .and_then(|stages| stages.checked_add(1))
            .ok_or_else(|| CoreError::invalid("image graph scratch", "stage count overflowed"))?;
        if canvas_bytes
            .checked_mul(retained_images)
            .is_none_or(|bytes| bytes > MAX_IMAGE_GRAPH_SCRATCH_BYTES)
        {
            return Err(CoreError::invalid(
                "image graph scratch",
                format!("exceeds {MAX_IMAGE_GRAPH_SCRATCH_BYTES} bytes"),
            ));
        }
        self.validate_checkpoint()?;
        for (index, stage) in self.composites.iter().enumerate() {
            if usize::from(stage.stage) != index {
                return Err(CoreError::invalid(
                    "image composite stages",
                    "stage indices must be contiguous and declared in order",
                ));
            }
            match stage.operation {
                ImageCompositeOperation::MaskBlend {
                    base,
                    overlay,
                    mask_slot,
                } => {
                    self.validate_rgb_source(base, index)?;
                    self.validate_rgb_source(overlay, index)?;
                    self.require_input_layout(mask_slot, ImageLayoutKind::Gray8)?;
                }
            }
        }
        self.validate_outputs()
    }

    fn validate_checkpoint(&self) -> Result<(), CoreError> {
        let Some(schedule) = self.primary.schedule.as_ref() else {
            if self.checkpoint != ImageCheckpointPlan::default() {
                return Err(CoreError::invalid(
                    "image checkpoint plan",
                    "direct VAE operations cannot restore or capture a diffusion checkpoint",
                ));
            }
            return Ok(());
        };
        if let Some(slot) = self.checkpoint.restore_from {
            let input = self
                .primary
                .inputs
                .iter()
                .find(|input| input.slot == slot)
                .ok_or_else(|| {
                    CoreError::invalid("image checkpoint restore", "does not name an input binding")
                })?;
            if input.role != ImageBufferRole::Checkpoint {
                return Err(CoreError::invalid(
                    "image checkpoint restore",
                    "does not name a checkpoint input",
                ));
            }
        }
        let checkpoint_inputs = self
            .primary
            .inputs
            .iter()
            .filter(|input| input.role == ImageBufferRole::Checkpoint)
            .count();
        if checkpoint_inputs != usize::from(self.checkpoint.restore_from.is_some()) {
            return Err(CoreError::invalid(
                "image checkpoint restore",
                "checkpoint inputs must be consumed exactly once",
            ));
        }
        if self
            .checkpoint
            .capture_after_step
            .is_some_and(|step| usize::try_from(step).map_or(true, |step| step >= schedule.steps()))
        {
            return Err(CoreError::invalid(
                "image checkpoint capture",
                "step is outside the primary schedule",
            ));
        }
        Ok(())
    }

    fn validate_outputs(&self) -> Result<(), CoreError> {
        let mut allocations = HashSet::new();
        let mut checkpoint_routes = 0_usize;
        for (index, route) in self.outputs.iter().enumerate() {
            route.buffer.validate()?;
            if !allocations.insert(route.buffer.identity.clone()) {
                return Err(CoreError::invalid(
                    "image output routes",
                    "allocation identities must be unique",
                ));
            }
            match route.source {
                ImageOutputSource::Image { source } => {
                    self.validate_rgb_source(source, self.composites.len())?;
                    validate_tight_rgb_output(
                        &route.layout,
                        &route.buffer,
                        self.primary.width,
                        self.primary.height,
                    )?;
                }
                ImageOutputSource::Checkpoint => {
                    checkpoint_routes += 1;
                    if !matches!(route.layout, ImageBufferLayout::Opaque)
                        || index + 1 != self.outputs.len()
                    {
                        return Err(CoreError::invalid(
                            "image checkpoint output",
                            "must be the final route and use an opaque buffer layout",
                        ));
                    }
                }
            }
        }
        let expected_checkpoint_routes = usize::from(self.checkpoint.capture_after_step.is_some());
        if checkpoint_routes != expected_checkpoint_routes {
            return Err(CoreError::invalid(
                "image checkpoint output",
                "must be routed exactly once when checkpoint capture is requested",
            ));
        }
        Ok(())
    }

    fn validate_rgb_source(
        &self,
        source: ImageValueSource,
        current_stage: usize,
    ) -> Result<(), CoreError> {
        match source {
            ImageValueSource::Primary if self.primary.output_format == ImageOutputFormat::Rgb8 => {
                Ok(())
            }
            ImageValueSource::Primary => Err(CoreError::invalid(
                "image graph primary source",
                "must produce RGB8 bytes",
            )),
            ImageValueSource::Input { slot } => {
                self.require_input_layout(slot, ImageLayoutKind::Rgb8)
            }
            ImageValueSource::Composite { stage }
                if usize::from(stage) < current_stage
                    && usize::from(stage) < self.composites.len() =>
            {
                Ok(())
            }
            ImageValueSource::Composite { .. } => Err(CoreError::invalid(
                "image graph composite source",
                "must name an earlier stage",
            )),
        }
    }

    fn require_input_layout(&self, slot: u16, kind: ImageLayoutKind) -> Result<(), CoreError> {
        let input = self
            .primary
            .inputs
            .iter()
            .find(|input| input.slot == slot)
            .ok_or_else(|| CoreError::invalid("image graph input", "slot is not bound"))?;
        let (width, height, row_stride, actual) = match input.layout {
            ImageBufferLayout::Rgb8 {
                width,
                height,
                row_stride,
            } => (width, height, row_stride, ImageLayoutKind::Rgb8),
            ImageBufferLayout::Gray8 {
                width,
                height,
                row_stride,
            } => (width, height, row_stride, ImageLayoutKind::Gray8),
            _ => {
                return Err(CoreError::invalid(
                    "image graph input",
                    "must use the required byte layout",
                ));
            }
        };
        let channels = match kind {
            ImageLayoutKind::Rgb8 => 3_u64,
            ImageLayoutKind::Gray8 => 1_u64,
        };
        let expected_stride = u64::from(self.primary.width)
            .checked_mul(channels)
            .ok_or_else(|| CoreError::invalid("image graph stride", "overflowed"))?;
        if actual != kind
            || width != self.primary.width
            || height != self.primary.height
            || row_stride != expected_stride
        {
            return Err(CoreError::invalid(
                "image graph input",
                "must be tightly packed at the primary canvas geometry",
            ));
        }
        Ok(())
    }

    /// Returns the identity of the complete version-two plan.
    ///
    /// # Errors
    ///
    /// Returns a validation or deterministic serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("image-execution-plan-v2", self)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ImageLayoutKind {
    Rgb8,
    Gray8,
}

/// Exact output write accounting.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageOutputReceiptV2 {
    /// Zero-based route index.
    pub route: u16,
    /// Caller-owned allocation identity.
    pub allocation: Digest,
    /// Exact initialized output bytes.
    pub content: Digest,
    /// Initialized prefix length.
    pub bytes_written: u64,
}

/// Deterministic composite lineage.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageCompositeReceipt {
    /// Zero-based stage index.
    pub stage: u16,
    /// Exact first input bytes.
    pub base: Digest,
    /// Exact second input bytes.
    pub overlay: Digest,
    /// Exact mask bytes.
    pub mask: Digest,
    /// Exact RGB8 output bytes.
    pub output: Digest,
}

/// Observed request-scope cleanup outcome.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum ImageCleanupDisposition {
    /// The plan explicitly retained a known resident session.
    Retained,
    /// Cleanup was confirmed for the reported prior epoch.
    Confirmed {
        /// Session epoch invalidated by cleanup.
        cleared_epoch: u64,
    },
    /// Cancellation was observed before native or request-local state existed.
    NotRequired,
}

/// Deterministic whole-plan receipt for [`ImageExecutionPlanV2`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ImageExecutionReceiptV2 {
    /// Exact version-two plan identity.
    pub plan: Digest,
    /// Exact backend build/runtime identity.
    pub backend: Digest,
    /// Exact primary profile identity.
    pub profile: Digest,
    /// Session epoch used by the primary operation.
    pub session_epoch: u64,
    /// Completed diffusion transitions.
    pub completed_steps: u32,
    /// Terminal execution boundary.
    pub terminal: ImageTerminal,
    /// Adapter-specific primary receipt identity, absent for pre-start
    /// cancellation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub primary: Option<Digest>,
    /// Checkpoint lineage in deterministic order: restored receipt, captured
    /// receipt, then captured envelope bytes, omitting absent mechanics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub checkpoints: Vec<Digest>,
    /// Completed deterministic composites in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub composites: Vec<ImageCompositeReceipt>,
    /// Completed output writes in route order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub outputs: Vec<ImageOutputReceiptV2>,
    /// Observation result identities in request order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub observations: Vec<Digest>,
    /// Request-scope cleanup outcome.
    pub cleanup: ImageCleanupDisposition,
}

impl ImageExecutionReceiptV2 {
    /// Validates plan lineage, terminal position, graph prefix, output writes,
    /// and cleanup disposition.
    ///
    /// # Errors
    ///
    /// Returns the first inconsistent receipt field.
    pub fn validate_for(&self, plan: &ImageExecutionPlanV2) -> Result<(), CoreError> {
        plan.validate()?;
        if self.plan != plan.digest()? || self.profile != plan.primary.profile {
            return Err(CoreError::invalid(
                "image execution receipt v2",
                "plan or profile identity differs",
            ));
        }
        let step_count = plan
            .primary
            .schedule
            .as_ref()
            .map_or(0, crate::DiffusionSchedule::steps);
        let completed = usize::try_from(self.completed_steps).map_err(|_| {
            CoreError::invalid("image execution receipt v2", "step count exceeds usize")
        })?;
        self.validate_collections(plan, completed, step_count)?;
        self.validate_terminal(plan, completed, step_count)?;
        self.validate_cleanup(plan)
    }

    fn validate_collections(
        &self,
        plan: &ImageExecutionPlanV2,
        completed: usize,
        step_count: usize,
    ) -> Result<(), CoreError> {
        if completed > step_count
            || self.checkpoints.len() > maximum_checkpoint_lineage(plan)
            || self.composites.len() > plan.composites.len()
            || self.outputs.len() > plan.outputs.len()
            || self.observations.len() > plan.primary.observations.len()
        {
            return Err(CoreError::invalid(
                "image execution receipt v2",
                "a completed collection or step count exceeds the plan",
            ));
        }
        for (index, composite) in self.composites.iter().enumerate() {
            if usize::from(composite.stage) != index {
                return Err(CoreError::invalid(
                    "image composite receipt",
                    "stages must form an ordered completed prefix",
                ));
            }
        }
        for (index, output) in self.outputs.iter().enumerate() {
            let route = plan.outputs.get(index).ok_or_else(|| {
                CoreError::invalid("image output receipt", "route is outside the plan")
            })?;
            if usize::from(output.route) != index
                || output.allocation != route.buffer.identity
                || output.bytes_written == 0
                || output.bytes_written > route.buffer.byte_length
                || (matches!(route.source, ImageOutputSource::Image { .. })
                    && output.bytes_written != route.buffer.byte_length)
            {
                return Err(CoreError::invalid(
                    "image output receipt",
                    "route, allocation, or initialized length is inconsistent",
                ));
            }
        }
        Ok(())
    }

    fn validate_terminal(
        &self,
        plan: &ImageExecutionPlanV2,
        completed: usize,
        step_count: usize,
    ) -> Result<(), CoreError> {
        match self.terminal {
            ImageTerminal::Completed
                if completed != step_count
                    || self.primary.is_none()
                    || self.checkpoints.len() != maximum_checkpoint_lineage(plan)
                    || self.composites.len() != plan.composites.len()
                    || self.outputs.len() != plan.outputs.len()
                    || self.observations.len() != plan.primary.observations.len() =>
            {
                return Err(CoreError::invalid(
                    "image execution receipt v2",
                    "completed terminal requires the whole graph and every route",
                ));
            }
            ImageTerminal::CancelledBeforeStart
                if completed != 0
                    || self.primary.is_some()
                    || !self.checkpoints.is_empty()
                    || !self.composites.is_empty()
                    || !self.outputs.is_empty()
                    || !self.observations.is_empty()
                    || self.cleanup != ImageCleanupDisposition::NotRequired =>
            {
                return Err(CoreError::invalid(
                    "image execution receipt v2",
                    "pre-start cancellation contains execution side effects",
                ));
            }
            ImageTerminal::CancelledAfterStep { step }
                if usize::try_from(step)
                    .ok()
                    .and_then(|step| step.checked_add(1))
                    != Some(completed)
                    || self.primary.is_none()
                    || self.observations.len() != plan.primary.observations.len() =>
            {
                return Err(CoreError::invalid(
                    "image execution receipt v2",
                    "cancelled boundary does not match completed steps",
                ));
            }
            _ => {}
        }
        if let ImageTerminal::CancelledAfterStep { step } = self.terminal {
            let capture_reached = plan
                .checkpoint
                .capture_after_step
                .is_some_and(|capture| capture <= step);
            let minimum = usize::from(capture_reached) * 2;
            let maximum = minimum + usize::from(plan.checkpoint.restore_from.is_some());
            if self.checkpoints.len() < minimum || self.checkpoints.len() > maximum {
                return Err(CoreError::invalid(
                    "image checkpoint receipt",
                    "lineage does not match the reached cancellation boundary",
                ));
            }
        }
        Ok(())
    }

    fn validate_cleanup(&self, plan: &ImageExecutionPlanV2) -> Result<(), CoreError> {
        if self.terminal != ImageTerminal::CancelledBeforeStart {
            match (plan.cleanup, &self.cleanup) {
                (ImageCleanupPolicy::RetainSession, ImageCleanupDisposition::Retained)
                | (ImageCleanupPolicy::ClearSession, ImageCleanupDisposition::Confirmed { .. }) => {
                }
                _ => {
                    return Err(CoreError::invalid(
                        "image execution receipt v2",
                        "cleanup disposition differs from the plan",
                    ));
                }
            }
        }
        Ok(())
    }

    /// Returns the identity of this exact whole-plan receipt.
    ///
    /// # Errors
    ///
    /// Returns a validation or deterministic serialization error.
    pub fn digest_for(&self, plan: &ImageExecutionPlanV2) -> Result<Digest, CoreError> {
        self.validate_for(plan)?;
        Digest::of_serializable("image-execution-receipt-v2", self)
    }
}

fn maximum_checkpoint_lineage(plan: &ImageExecutionPlanV2) -> usize {
    usize::from(plan.checkpoint.restore_from.is_some())
        + usize::from(plan.checkpoint.capture_after_step.is_some()) * 2
}

/// Applies the version-two RGB8 mask-blend contract into caller-owned output.
///
/// Every length is validated before the first output byte is modified.
///
/// # Errors
///
/// Returns an error unless `base`, `overlay`, and `output` have equal RGB8
/// lengths and the mask contains one byte per pixel.
pub fn mask_blend_rgb8(
    base: &[u8],
    overlay: &[u8],
    mask: &[u8],
    output: &mut [u8],
) -> Result<ImageCompositeReceipt, CoreError> {
    if base.is_empty()
        || base.len() != overlay.len()
        || base.len() != output.len()
        || !base.len().is_multiple_of(3)
        || mask.len() != base.len() / 3
    {
        return Err(CoreError::invalid(
            "RGB8 mask blend",
            "image or mask lengths are inconsistent",
        ));
    }
    let base_digest = Digest::of_bytes("image-composite-rgb8-input-v1", base);
    let overlay_digest = Digest::of_bytes("image-composite-rgb8-input-v1", overlay);
    let mask_digest = Digest::of_bytes("image-composite-gray8-input-v1", mask);
    for (pixel_index, (pixel, mask)) in output
        .chunks_exact_mut(3)
        .zip(mask.iter().copied())
        .enumerate()
    {
        let offset = pixel_index * 3;
        let mask = u16::from(mask);
        for channel in 0..3 {
            let base = u16::from(base[offset + channel]);
            let overlay = u16::from(overlay[offset + channel]);
            let value = base * (255 - mask) + overlay * mask + 127;
            pixel[channel] = u8::try_from(value / 255).map_err(|_| {
                CoreError::invalid("RGB8 mask blend", "channel arithmetic overflowed")
            })?;
        }
    }
    let output_digest = Digest::of_bytes("image-composite-rgb8-output-v1", output);
    Ok(ImageCompositeReceipt {
        stage: 0,
        base: base_digest,
        overlay: overlay_digest,
        mask: mask_digest,
        output: output_digest,
    })
}

fn validate_tight_rgb_output(
    layout: &ImageBufferLayout,
    buffer: &BufferSpec,
    width: u32,
    height: u32,
) -> Result<(), CoreError> {
    let expected_stride = u64::from(width)
        .checked_mul(3)
        .ok_or_else(|| CoreError::invalid("image output stride", "overflowed"))?;
    match layout {
        ImageBufferLayout::Rgb8 {
            width: output_width,
            height: output_height,
            row_stride,
        } if *output_width == width
            && *output_height == height
            && *row_stride == expected_stride =>
        {
            let expected = expected_stride
                .checked_mul(u64::from(height))
                .ok_or_else(|| CoreError::invalid("image output length", "overflowed"))?;
            if buffer.byte_length != expected {
                return Err(CoreError::invalid(
                    "image output allocation",
                    "length differs from the tightly packed RGB8 canvas",
                ));
            }
            Ok(())
        }
        _ => Err(CoreError::invalid(
            "image output route",
            "must be tightly packed RGB8 at the primary canvas geometry",
        )),
    }
}

#[cfg(test)]
mod tests {
    use logit_loom_executor::BufferSpec;

    use super::*;
    use crate::{
        DiffusionSchedule, ImageBufferBinding, ImageOperation, ObservationRequest, SeedSelection,
    };

    fn buffer(domain: &str, bytes: u64, media_type: &str) -> BufferSpec {
        BufferSpec::new(
            Digest::of_bytes(domain, domain.as_bytes()),
            bytes,
            media_type,
        )
        .unwrap()
    }

    fn primary() -> ImageExecutionPlan {
        let width = 2;
        let height = 1;
        let prompt = ImageBufferBinding {
            slot: 0,
            role: ImageBufferRole::PositiveConditioning,
            buffer: buffer("prompt", 4, "text/plain"),
            layout: ImageBufferLayout::Utf8,
        };
        let overlay = ImageBufferBinding {
            slot: 1,
            role: ImageBufferRole::ReferenceImage,
            buffer: buffer("overlay", 6, "image/rgb"),
            layout: ImageBufferLayout::Rgb8 {
                width,
                height,
                row_stride: 6,
            },
        };
        let mask = ImageBufferBinding {
            slot: 2,
            role: ImageBufferRole::Mask,
            buffer: buffer("mask", 2, "image/gray"),
            layout: ImageBufferLayout::Gray8 {
                width,
                height,
                row_stride: 2,
            },
        };
        ImageExecutionPlan {
            profile: Digest::of_bytes("profile", b"one"),
            load: Digest::of_bytes("load", b"one"),
            operation: ImageOperation::TextToImage,
            width,
            height,
            output_format: ImageOutputFormat::Rgb8,
            seed: SeedSelection::Fixed { seed: 7 },
            rng: Digest::of_bytes("rng", b"one"),
            placement: Digest::of_bytes("placement", b"one"),
            schedule: Some(
                DiffusionSchedule::new(Digest::of_bytes("schedule", b"one"), vec![1.0, 0.0])
                    .unwrap(),
            ),
            guidance_scale_bits: 1.0_f32.to_bits(),
            strength_bits: 1.0_f32.to_bits(),
            inputs: vec![prompt, overlay, mask],
            loras: Vec::new(),
            operators: Vec::new(),
            observations: Vec::<ObservationRequest>::new(),
        }
    }

    fn graph() -> ImageExecutionPlanV2 {
        let primary = primary();
        ImageExecutionPlanV2 {
            primary,
            checkpoint: ImageCheckpointPlan::default(),
            composites: vec![ImageCompositeStage {
                stage: 0,
                operation: ImageCompositeOperation::MaskBlend {
                    base: ImageValueSource::Primary,
                    overlay: ImageValueSource::Input { slot: 1 },
                    mask_slot: 2,
                },
            }],
            outputs: vec![ImageOutputRoute {
                source: ImageOutputSource::Image {
                    source: ImageValueSource::Composite { stage: 0 },
                },
                buffer: buffer("output", 6, "image/rgb"),
                layout: ImageBufferLayout::Rgb8 {
                    width: 2,
                    height: 1,
                    row_stride: 6,
                },
            }],
            cleanup: ImageCleanupPolicy::RetainSession,
        }
    }

    #[test]
    fn graph_requires_earlier_composites_and_exact_routes() {
        assert!(graph().validate().is_ok());
        let mut invalid = graph();
        invalid.composites[0].operation = ImageCompositeOperation::MaskBlend {
            base: ImageValueSource::Composite { stage: 0 },
            overlay: ImageValueSource::Input { slot: 1 },
            mask_slot: 2,
        };
        assert!(invalid.validate().is_err());

        let mut missing_checkpoint = graph();
        missing_checkpoint.checkpoint.capture_after_step = Some(0);
        assert!(missing_checkpoint.validate().is_err());
    }

    #[test]
    fn version_two_round_trip_preserves_new_identity_domain() {
        let plan = graph();
        let encoded = serde_json::to_vec(&plan).unwrap();
        let decoded: ImageExecutionPlanV2 = serde_json::from_slice(&encoded).unwrap();
        assert_eq!(decoded, plan);
        assert_ne!(plan.digest().unwrap(), plan.primary.digest().unwrap());

        let mut value = serde_json::to_value(&plan).unwrap();
        value
            .as_object_mut()
            .unwrap()
            .insert("future-field".to_owned(), serde_json::Value::Bool(true));
        assert!(serde_json::from_value::<ImageExecutionPlanV2>(value).is_err());
    }

    #[test]
    fn checkpoint_capture_uses_one_final_output_route() {
        let mut plan = graph();
        plan.checkpoint.capture_after_step = Some(0);
        plan.outputs.push(ImageOutputRoute {
            source: ImageOutputSource::Checkpoint,
            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
            layout: ImageBufferLayout::Opaque,
        });
        assert!(plan.validate().is_ok());
        plan.outputs.swap(0, 1);
        assert!(plan.validate().is_err());
    }

    #[test]
    fn mask_blend_is_exact_at_endpoints_and_midpoint() {
        let base = [0, 10, 20, 100, 110, 120, 20, 40, 60];
        let overlay = [200, 210, 220, 50, 60, 70, 120, 140, 160];
        let mask = [0, 255, 128];
        let mut output = [9_u8; 9];
        let receipt = mask_blend_rgb8(&base, &overlay, &mask, &mut output).unwrap();
        assert_eq!(&output[..3], &base[..3]);
        assert_eq!(&output[3..6], &overlay[3..6]);
        assert_eq!(&output[6..], &[70, 90, 110]);
        assert_eq!(
            receipt.output,
            Digest::of_bytes("image-composite-rgb8-output-v1", &output)
        );
    }

    #[test]
    fn mask_blend_rejects_before_write() {
        let mut output = [9_u8; 3];
        assert!(mask_blend_rgb8(&[0, 0, 0], &[1, 1], &[255], &mut output).is_err());
        assert_eq!(output, [9; 3]);
    }

    #[test]
    fn prestart_cancellation_receipt_has_no_side_effects() {
        let plan = graph();
        let mut receipt = ImageExecutionReceiptV2 {
            plan: plan.digest().unwrap(),
            backend: Digest::of_bytes("backend", b"one"),
            profile: plan.primary.profile.clone(),
            session_epoch: 4,
            completed_steps: 0,
            terminal: ImageTerminal::CancelledBeforeStart,
            primary: None,
            checkpoints: Vec::new(),
            composites: Vec::new(),
            outputs: Vec::new(),
            observations: Vec::new(),
            cleanup: ImageCleanupDisposition::NotRequired,
        };
        assert!(receipt.digest_for(&plan).is_ok());
        receipt
            .checkpoints
            .push(Digest::of_bytes("checkpoint", b"unexpected"));
        assert!(receipt.digest_for(&plan).is_err());
    }

    #[test]
    fn reached_checkpoint_capture_requires_receipt_and_envelope_lineage() {
        let mut plan = graph();
        plan.checkpoint.capture_after_step = Some(0);
        plan.outputs.push(ImageOutputRoute {
            source: ImageOutputSource::Checkpoint,
            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
            layout: ImageBufferLayout::Opaque,
        });
        plan.validate().unwrap();
        let receipt = ImageExecutionReceiptV2 {
            plan: plan.digest().unwrap(),
            backend: Digest::of_bytes("backend", b"one"),
            profile: plan.primary.profile.clone(),
            session_epoch: 4,
            completed_steps: 1,
            terminal: ImageTerminal::CancelledAfterStep { step: 0 },
            primary: Some(Digest::of_bytes("primary", b"one")),
            checkpoints: vec![Digest::of_bytes("checkpoint", b"receipt-only")],
            composites: Vec::new(),
            outputs: Vec::new(),
            observations: Vec::new(),
            cleanup: ImageCleanupDisposition::Retained,
        };
        assert!(receipt.validate_for(&plan).is_err());
    }

    #[test]
    fn cancellation_before_capture_can_leave_final_route_uninitialized() {
        let mut plan = graph();
        plan.primary.schedule = Some(
            DiffusionSchedule::new(
                Digest::of_bytes("schedule", b"two-steps"),
                vec![1.0, 0.5, 0.0],
            )
            .unwrap(),
        );
        plan.checkpoint.capture_after_step = Some(1);
        plan.outputs.push(ImageOutputRoute {
            source: ImageOutputSource::Checkpoint,
            buffer: buffer("checkpoint-output", 1_024, "application/octet-stream"),
            layout: ImageBufferLayout::Opaque,
        });
        let receipt = ImageExecutionReceiptV2 {
            plan: plan.digest().unwrap(),
            backend: Digest::of_bytes("backend", b"one"),
            profile: plan.primary.profile.clone(),
            session_epoch: 4,
            completed_steps: 1,
            terminal: ImageTerminal::CancelledAfterStep { step: 0 },
            primary: Some(Digest::of_bytes("primary", b"one")),
            checkpoints: Vec::new(),
            composites: vec![ImageCompositeReceipt {
                stage: 0,
                base: Digest::of_bytes("base", b"one"),
                overlay: Digest::of_bytes("overlay", b"one"),
                mask: Digest::of_bytes("mask", b"one"),
                output: Digest::of_bytes("composite", b"one"),
            }],
            outputs: vec![ImageOutputReceiptV2 {
                route: 0,
                allocation: plan.outputs[0].buffer.identity.clone(),
                content: Digest::of_bytes("content", b"image"),
                bytes_written: 6,
            }],
            observations: Vec::new(),
            cleanup: ImageCleanupDisposition::Retained,
        };
        assert!(receipt.validate_for(&plan).is_ok());
    }

    #[test]
    fn image_routes_require_the_exact_initialized_length() {
        let plan = graph();
        let receipt = ImageExecutionReceiptV2 {
            plan: plan.digest().unwrap(),
            backend: Digest::of_bytes("backend", b"one"),
            profile: plan.primary.profile.clone(),
            session_epoch: 4,
            completed_steps: 1,
            terminal: ImageTerminal::Completed,
            primary: Some(Digest::of_bytes("primary", b"one")),
            checkpoints: Vec::new(),
            composites: vec![ImageCompositeReceipt {
                stage: 0,
                base: Digest::of_bytes("base", b"one"),
                overlay: Digest::of_bytes("overlay", b"one"),
                mask: Digest::of_bytes("mask", b"one"),
                output: Digest::of_bytes("composite", b"one"),
            }],
            outputs: vec![ImageOutputReceiptV2 {
                route: 0,
                allocation: plan.outputs[0].buffer.identity.clone(),
                content: Digest::of_bytes("content", b"short"),
                bytes_written: 5,
            }],
            observations: Vec::new(),
            cleanup: ImageCleanupDisposition::Retained,
        };
        assert!(receipt.validate_for(&plan).is_err());
    }
}