vyre-megakernel 0.7.2

Backend-neutral compiler for canonical Vyre megakernel artifacts
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
use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use crate::{
    failure, Artifact, ArtifactNodeId, ArtifactValueId, CompileError, CompilerFailureKind, Digest,
};

/// Current schema for the artifact envelope that carries neutral data and target payloads.
pub const ARTIFACT_ENVELOPE_SCHEMA_VERSION: u16 = 2;
/// Current schema for one target payload attachment.
pub const TARGET_PAYLOAD_SCHEMA_VERSION: u16 = 3;

const ENVELOPE_MAGIC: &[u8; 4] = b"VME0";
const TARGET_PAYLOAD_MAGIC: &[u8; 4] = b"VTP0";
const FRAME_HEADER_BYTES: usize = 10;
const DIGEST_BYTES: usize = 32;
const ENVELOPE_DIGEST_DOMAIN: &[u8] = b"vyre-megakernel-envelope-v2\0";
const TARGET_PAYLOAD_DIGEST_DOMAIN: &[u8] = b"vyre-megakernel-target-payload-v3\0";

/// Versioned identity of target bytes without assigning concrete target semantics.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetPayloadFormat {
    identity: String,
    version: u16,
}

impl TargetPayloadFormat {
    /// Construct a non-empty, non-zero format identity.
    pub fn new(identity: impl Into<String>, version: u16) -> Result<Self, CompileError> {
        let identity = identity.into();
        if identity.is_empty() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.format.identity",
                "target payload format identity is empty",
                "supply the stable format identity owned by the target materializer",
            ));
        }
        if version == 0 {
            return Err(failure(
                CompilerFailureKind::TargetPayloadVersionSkew,
                "target_payload.format.version",
                "target payload format version zero is reserved",
                "supply a positive target format version",
            ));
        }
        Ok(Self { identity, version })
    }

    /// Stable target-payload format identity.
    #[must_use]
    pub fn identity(&self) -> &str {
        &self.identity
    }

    /// Exact target-payload format version.
    #[must_use]
    pub const fn version(&self) -> u16 {
        self.version
    }
}

/// Immutable capability profile used for pure target compilation.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetProfile {
    identity: String,
    generation: u64,
    max_workgroup_size: [u32; 3],
    max_invocations_per_workgroup: u32,
    max_dynamic_shared_bytes: u32,
    subgroup_size: u32,
}

impl TargetProfile {
    /// Construct one target-owned compilation profile.
    pub fn new(
        identity: impl Into<String>,
        generation: u64,
        max_workgroup_size: [u32; 3],
        max_invocations_per_workgroup: u32,
        max_dynamic_shared_bytes: u32,
        subgroup_size: u32,
    ) -> Result<Self, CompileError> {
        let identity = identity.into();
        if identity.is_empty() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.profile.identity",
                "target profile identity is empty",
                "supply the stable profile identity owned by the target compiler",
            ));
        }
        if generation == 0 {
            return Err(failure(
                CompilerFailureKind::TargetPayloadVersionSkew,
                "target_payload.profile.generation",
                "target profile generation zero is reserved",
                "supply a positive compiler/materializer generation",
            ));
        }
        if let Some(axis) = max_workgroup_size.iter().position(|extent| *extent == 0) {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("target_payload.profile.max_workgroup_size[{axis}]"),
                "target profile workgroup limit is zero",
                "supply positive workgroup limits for every axis",
            ));
        }
        if max_invocations_per_workgroup == 0 {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.profile.max_invocations_per_workgroup",
                "target profile invocation limit is zero",
                "supply a positive invocation limit",
            ));
        }
        if subgroup_size != 0 && !subgroup_size.is_power_of_two() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.profile.subgroup_size",
                "target profile subgroup width is not a power of two",
                "supply zero for no subgroup constraint or a power-of-two subgroup width",
            ));
        }
        Ok(Self {
            identity,
            generation,
            max_workgroup_size,
            max_invocations_per_workgroup,
            max_dynamic_shared_bytes,
            subgroup_size,
        })
    }

    /// Stable target-owned profile identity.
    #[must_use]
    pub fn identity(&self) -> &str {
        &self.identity
    }

    /// Compiler/materializer contract generation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Maximum supported workgroup dimensions.
    #[must_use]
    pub const fn max_workgroup_size(&self) -> [u32; 3] {
        self.max_workgroup_size
    }

    /// Maximum supported invocations in one workgroup.
    #[must_use]
    pub const fn max_invocations_per_workgroup(&self) -> u32 {
        self.max_invocations_per_workgroup
    }

    /// Maximum dynamic shared bytes per entry.
    #[must_use]
    pub const fn max_dynamic_shared_bytes(&self) -> u32 {
        self.max_dynamic_shared_bytes
    }

    /// Required subgroup width, or zero when subgroup width is not constrained.
    #[must_use]
    pub const fn subgroup_size(&self) -> u32 {
        self.subgroup_size
    }
}

/// Neutral memory class required by one target resource binding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetResourceMemory {
    /// Externally allocated storage.
    Global,
    /// Entry-local shared storage.
    Shared,
    /// Read-only constant storage.
    Constant,
}

/// Access required by one target resource binding.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetResourceAccess {
    /// Read-only access.
    ReadOnly,
    /// Write-only access.
    WriteOnly,
    /// Read and write access.
    ReadWrite,
}

/// Target binding metadata associated with one canonical neutral resource.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetResourceBinding {
    /// Canonical resource identity from [`Artifact::resources`].
    pub resource: ArtifactValueId,
    /// Target resource group or descriptor set.
    pub group: u32,
    /// Target entry binding slot within `group`.
    pub slot: u32,
    /// Required memory class.
    pub memory: TargetResourceMemory,
    /// Required access mode.
    pub access: TargetResourceAccess,
}

/// Metadata for one entry in an attached target payload.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetEntryPoint {
    /// Stable entry name in the target payload.
    pub name: String,
    /// Canonical neutral node implemented by this entry.
    pub node: ArtifactNodeId,
    /// Exact target workgroup dimensions.
    pub workgroup_size: [u32; 3],
    /// Exact target grid dimensions.
    pub grid_size: [u32; 3],
    /// Entry-local dynamic shared byte requirement.
    pub dynamic_shared_bytes: u32,
    /// Bindings associated by identity with canonical neutral resources.
    pub resource_bindings: Vec<TargetResourceBinding>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct TargetPayloadBody {
    schema_version: u16,
    neutral_artifact: Digest,
    format: TargetPayloadFormat,
    profile: TargetProfile,
    entries: Vec<TargetEntryPoint>,
    bytes: Vec<u8>,
}

/// Digest-bound target bytes attached to one exact neutral artifact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TargetPayload {
    body: TargetPayloadBody,
    digest: Digest,
}

impl TargetPayload {
    /// Validate and bind target bytes to an exact neutral artifact.
    pub fn new(
        neutral: &Artifact,
        format: TargetPayloadFormat,
        profile: TargetProfile,
        mut entries: Vec<TargetEntryPoint>,
        bytes: Vec<u8>,
    ) -> Result<Self, CompileError> {
        if bytes.is_empty() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.bytes",
                "target payload bytes are empty",
                "attach non-empty bytes emitted for the declared target format",
            ));
        }
        entries.sort_by(|left, right| left.name.cmp(&right.name));
        for entry in &mut entries {
            entry
                .resource_bindings
                .sort_by_key(|binding| (binding.group, binding.slot));
        }
        validate_entries(neutral, &profile, &entries)?;
        let body = TargetPayloadBody {
            schema_version: TARGET_PAYLOAD_SCHEMA_VERSION,
            neutral_artifact: neutral.digest(),
            format,
            profile,
            entries,
            bytes,
        };
        let digest = body_digest(TARGET_PAYLOAD_DIGEST_DOMAIN, &body)?;
        Ok(Self { body, digest })
    }

    /// Target payload attachment schema.
    #[must_use]
    pub const fn schema_version(&self) -> u16 {
        self.body.schema_version
    }

    /// Exact neutral artifact identity this payload implements.
    #[must_use]
    pub const fn neutral_artifact(&self) -> Digest {
        self.body.neutral_artifact
    }

    /// Versioned payload format identity.
    #[must_use]
    pub const fn format(&self) -> &TargetPayloadFormat {
        &self.body.format
    }

    /// Immutable target capability profile used during compilation.
    #[must_use]
    pub const fn profile(&self) -> &TargetProfile {
        &self.body.profile
    }

    /// Canonical entry metadata.
    #[must_use]
    pub fn entries(&self) -> &[TargetEntryPoint] {
        &self.body.entries
    }

    /// Target-owned opaque bytes.
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.body.bytes
    }

    /// Content identity covering association, format, entries, and bytes.
    #[must_use]
    pub const fn digest(&self) -> Digest {
        self.digest
    }

    /// Encode this authenticated target payload.
    pub fn to_bytes(&self) -> Result<Vec<u8>, CompileError> {
        encode_frame(
            TARGET_PAYLOAD_MAGIC,
            self.body.schema_version,
            TARGET_PAYLOAD_DIGEST_DOMAIN,
            &self.body,
        )
    }

    /// Decode and authenticate one target payload attachment.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CompileError> {
        let (version, body, encoded_digest) = decode_frame(
            bytes,
            TARGET_PAYLOAD_MAGIC,
            TARGET_PAYLOAD_SCHEMA_VERSION,
            TARGET_PAYLOAD_DIGEST_DOMAIN,
            "target_payload",
            CompilerFailureKind::TargetPayloadVersionSkew,
            CompilerFailureKind::TargetPayloadDigestMismatch,
        )?;
        let body: TargetPayloadBody = serde_json::from_slice(body).map_err(|error| {
            failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.body",
                error.to_string(),
                "supply canonical target payload bytes emitted by this crate",
            )
        })?;
        if body.schema_version != version {
            return Err(failure(
                CompilerFailureKind::TargetPayloadVersionSkew,
                "target_payload.body.schema_version",
                "target payload body schema disagrees with its framing schema",
                "re-materialize the target payload instead of rewriting its framing",
            ));
        }
        let canonical = serde_json::to_vec(&body).map_err(serialization_failure)?;
        if canonical.as_slice() != &bytes[FRAME_HEADER_BYTES..FRAME_HEADER_BYTES + canonical.len()]
        {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "target_payload.body",
                "target payload body is not canonical JSON",
                "use bytes emitted by TargetPayload::to_bytes",
            ));
        }
        Ok(Self {
            body,
            digest: Digest(encoded_digest),
        })
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct EnvelopeBody {
    schema_version: u16,
    neutral_artifact: Vec<u8>,
    target_payloads: Vec<Vec<u8>>,
}

/// Canonical versioned envelope containing one neutral artifact and target attachments.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ArtifactEnvelope {
    neutral: Artifact,
    target_payloads: Vec<TargetPayload>,
}

impl ArtifactEnvelope {
    /// Start an envelope around one authenticated neutral artifact.
    #[must_use]
    pub fn new(neutral: Artifact) -> Self {
        Self {
            neutral,
            target_payloads: Vec::new(),
        }
    }

    /// Canonical neutral artifact.
    #[must_use]
    pub const fn neutral(&self) -> &Artifact {
        &self.neutral
    }

    /// Canonically ordered target payload attachments.
    #[must_use]
    pub fn target_payloads(&self) -> &[TargetPayload] {
        &self.target_payloads
    }

    /// Attach a validated target payload to its exact neutral artifact.
    pub fn attach_target_payload(&mut self, payload: TargetPayload) -> Result<(), CompileError> {
        validate_target_payload(&self.neutral, &payload)?;
        if self
            .target_payloads
            .iter()
            .any(|existing| existing.format() == payload.format())
        {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                "envelope.target_payloads",
                format!(
                    "duplicate target payload format {} version {}",
                    payload.format().identity(),
                    payload.format().version()
                ),
                "attach at most one payload for each exact format identity and version",
            ));
        }
        self.target_payloads.push(payload);
        self.target_payloads
            .sort_by(|left, right| left.format().cmp(right.format()));
        Ok(())
    }

    /// Return the canonical index of the payload compatible with one exact format.
    pub fn require_target_payload_index(
        &self,
        required: &TargetPayloadFormat,
    ) -> Result<usize, CompileError> {
        if let Some(index) = self
            .target_payloads
            .iter()
            .position(|payload| payload.format() == required)
        {
            return Ok(index);
        }
        if let Some(payload) = self
            .target_payloads
            .iter()
            .find(|payload| payload.format().identity() == required.identity())
        {
            return Err(failure(
                CompilerFailureKind::TargetPayloadVersionSkew,
                "envelope.target_payloads.format.version",
                format!(
                    "format {} version {} is incompatible; required version {}",
                    required.identity(),
                    payload.format().version(),
                    required.version()
                ),
                "materialize the neutral artifact with the exact required target format version",
            ));
        }
        Err(failure(
            CompilerFailureKind::IncompatibleTargetPayload,
            "envelope.target_payloads.format.identity",
            format!(
                "required target payload format {} is absent",
                required.identity()
            ),
            "attach a compatible payload or materialize one from the neutral artifact",
        ))
    }

    /// Return the payload compatible with one exact format identity and version.
    pub fn require_target_payload(
        &self,
        required: &TargetPayloadFormat,
    ) -> Result<&TargetPayload, CompileError> {
        let index = self.require_target_payload_index(required)?;
        self.target_payloads.get(index).ok_or_else(|| {
            failure(
                CompilerFailureKind::MalformedArtifact,
                "envelope.target_payloads",
                "validated target payload index is outside the canonical attachment set",
                "discard the artifact and regenerate its canonical envelope",
            )
        })
    }

    /// Encode the complete authenticated artifact envelope.
    pub fn to_bytes(&self) -> Result<Vec<u8>, CompileError> {
        let body = EnvelopeBody {
            schema_version: ARTIFACT_ENVELOPE_SCHEMA_VERSION,
            neutral_artifact: self.neutral.to_bytes()?,
            target_payloads: self
                .target_payloads
                .iter()
                .map(TargetPayload::to_bytes)
                .collect::<Result<_, _>>()?,
        };
        encode_frame(
            ENVELOPE_MAGIC,
            body.schema_version,
            ENVELOPE_DIGEST_DOMAIN,
            &body,
        )
    }

    /// Decode, authenticate, and validate a complete artifact envelope.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CompileError> {
        let (version, body, _) = decode_frame(
            bytes,
            ENVELOPE_MAGIC,
            ARTIFACT_ENVELOPE_SCHEMA_VERSION,
            ENVELOPE_DIGEST_DOMAIN,
            "envelope",
            CompilerFailureKind::VersionSkew,
            CompilerFailureKind::DigestMismatch,
        )?;
        let body: EnvelopeBody = serde_json::from_slice(body).map_err(|error| {
            failure(
                CompilerFailureKind::MalformedArtifact,
                "envelope.body",
                error.to_string(),
                "supply canonical envelope bytes emitted by this crate",
            )
        })?;
        if body.schema_version != version {
            return Err(failure(
                CompilerFailureKind::VersionSkew,
                "envelope.body.schema_version",
                "envelope body schema disagrees with its framing schema",
                "repackage the artifact instead of rewriting its framing",
            ));
        }
        let canonical = serde_json::to_vec(&body).map_err(serialization_failure)?;
        if canonical.as_slice() != &bytes[FRAME_HEADER_BYTES..FRAME_HEADER_BYTES + canonical.len()]
        {
            return Err(failure(
                CompilerFailureKind::MalformedArtifact,
                "envelope.body",
                "envelope body is not canonical JSON",
                "use bytes emitted by ArtifactEnvelope::to_bytes",
            ));
        }
        let neutral = Artifact::from_bytes(&body.neutral_artifact)?;
        let mut envelope = Self::new(neutral);
        for payload_bytes in body.target_payloads {
            envelope.attach_target_payload(TargetPayload::from_bytes(&payload_bytes)?)?;
        }
        Ok(envelope)
    }
}

fn validate_target_payload(
    neutral: &Artifact,
    payload: &TargetPayload,
) -> Result<(), CompileError> {
    if payload.schema_version() != TARGET_PAYLOAD_SCHEMA_VERSION {
        return Err(failure(
            CompilerFailureKind::TargetPayloadVersionSkew,
            "target_payload.schema_version",
            format!(
                "target payload schema {} is unsupported; expected {}",
                payload.schema_version(),
                TARGET_PAYLOAD_SCHEMA_VERSION
            ),
            "re-materialize the target payload with this envelope version",
        ));
    }
    if payload.neutral_artifact() != neutral.digest() {
        return Err(failure(
            CompilerFailureKind::TargetPayloadAssociationMismatch,
            "target_payload.neutral_artifact",
            "target payload names a different neutral artifact digest",
            "discard the payload and materialize bytes from this exact neutral artifact",
        ));
    }
    validate_entries(neutral, payload.profile(), payload.entries())?;
    let digest = body_digest(TARGET_PAYLOAD_DIGEST_DOMAIN, &payload.body)?;
    if digest != payload.digest() {
        return Err(failure(
            CompilerFailureKind::TargetPayloadDigestMismatch,
            "target_payload.digest",
            "target payload identity does not match its association, metadata, and bytes",
            "discard the corrupted target payload and materialize it again",
        ));
    }
    Ok(())
}

fn validate_entries(
    neutral: &Artifact,
    profile: &TargetProfile,
    entries: &[TargetEntryPoint],
) -> Result<(), CompileError> {
    if entries.is_empty() {
        return Err(failure(
            CompilerFailureKind::MalformedTargetPayload,
            "target_payload.entries",
            "target payload has no entry metadata",
            "associate at least one payload entry with a canonical neutral node",
        ));
    }
    let mut names = BTreeSet::new();
    for (entry_index, entry) in entries.iter().enumerate() {
        let path = format!("target_payload.entries[{entry_index}]");
        if entry.name.is_empty() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("{path}.name"),
                "target entry name is empty",
                "supply the emitted entry symbol name",
            ));
        }
        if !names.insert(entry.name.as_str()) {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("{path}.name"),
                format!("duplicate target entry name {}", entry.name),
                "supply each target entry name exactly once",
            ));
        }
        if !neutral.nodes().iter().any(|node| node.id == entry.node) {
            return Err(failure(
                CompilerFailureKind::TargetPayloadAssociationMismatch,
                format!("{path}.node"),
                format!("neutral artifact has no node {}", entry.node.0),
                "associate the target entry with a canonical neutral node identity",
            ));
        }
        if !neutral
            .geometry()
            .iter()
            .any(|geometry| geometry.node == entry.node)
        {
            return Err(failure(
                CompilerFailureKind::TargetPayloadAssociationMismatch,
                format!("{path}.node"),
                "target entry node has no canonical neutral geometry record",
                "compile a complete neutral artifact before attaching target bytes",
            ));
        }
        for (field, geometry) in [
            ("workgroup_size", entry.workgroup_size),
            ("grid_size", entry.grid_size),
        ] {
            if let Some(axis) = geometry.iter().position(|extent| *extent == 0) {
                return Err(failure(
                    CompilerFailureKind::MalformedTargetPayload,
                    format!("{path}.{field}[{axis}]"),
                    "target entry geometry extent is zero",
                    "materialize explicit positive target geometry",
                ));
            }
        }
        let limits = profile.max_workgroup_size();
        if let Some(axis) = entry
            .workgroup_size
            .iter()
            .zip(limits)
            .position(|(extent, limit)| *extent > limit)
        {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("{path}.workgroup_size[{axis}]"),
                format!(
                    "target workgroup extent {} exceeds profile limit {}",
                    entry.workgroup_size[axis], limits[axis]
                ),
                "emit geometry admitted by the authenticated target profile",
            ));
        }
        let invocations = entry
            .workgroup_size
            .iter()
            .try_fold(1u32, |product, extent| product.checked_mul(*extent))
            .ok_or_else(|| {
                failure(
                    CompilerFailureKind::MalformedTargetPayload,
                    format!("{path}.workgroup_size"),
                    "target workgroup invocation count overflows u32",
                    "emit bounded workgroup geometry",
                )
            })?;
        if invocations > profile.max_invocations_per_workgroup() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("{path}.workgroup_size"),
                format!(
                    "target workgroup has {invocations} invocations, exceeding profile limit {}",
                    profile.max_invocations_per_workgroup()
                ),
                "emit geometry admitted by the authenticated target profile",
            ));
        }
        if entry.dynamic_shared_bytes > profile.max_dynamic_shared_bytes() {
            return Err(failure(
                CompilerFailureKind::MalformedTargetPayload,
                format!("{path}.dynamic_shared_bytes"),
                format!(
                    "target entry requires {} dynamic shared bytes, exceeding profile limit {}",
                    entry.dynamic_shared_bytes,
                    profile.max_dynamic_shared_bytes()
                ),
                "emit shared-memory requirements admitted by the authenticated target profile",
            ));
        }
        let mut slots = BTreeSet::new();
        let mut resources = BTreeSet::new();
        for (binding_index, binding) in entry.resource_bindings.iter().enumerate() {
            let binding_path = format!("{path}.resource_bindings[{binding_index}]");
            if !slots.insert((binding.group, binding.slot)) {
                return Err(failure(
                    CompilerFailureKind::MalformedTargetPayload,
                    format!("{binding_path}.slot"),
                    format!(
                        "duplicate target binding group {} slot {}",
                        binding.group, binding.slot
                    ),
                    "associate each target binding group/slot exactly once",
                ));
            }
            if !resources.insert(binding.resource) {
                return Err(failure(
                    CompilerFailureKind::MalformedTargetPayload,
                    format!("{binding_path}.resource"),
                    format!(
                        "canonical resource {} is bound more than once",
                        binding.resource.0
                    ),
                    "associate each canonical resource with at most one entry binding",
                ));
            }
            if !neutral
                .resources()
                .iter()
                .any(|resource| resource.value == binding.resource)
            {
                return Err(failure(
                    CompilerFailureKind::TargetPayloadAssociationMismatch,
                    format!("{binding_path}.resource"),
                    format!("neutral artifact has no resource {}", binding.resource.0),
                    "bind only canonical resources from the associated neutral artifact",
                ));
            }
        }
    }
    Ok(())
}

fn encode_frame<T: Serialize>(
    magic: &[u8; 4],
    version: u16,
    domain: &[u8],
    body: &T,
) -> Result<Vec<u8>, CompileError> {
    let body = serde_json::to_vec(body).map_err(serialization_failure)?;
    let body_len = u32::try_from(body.len()).map_err(|_| {
        failure(
            CompilerFailureKind::MalformedArtifact,
            "envelope.body",
            "canonical body exceeds the u32 framing limit",
            "reduce or detach target payload bytes",
        )
    })?;
    let digest = digest_bytes(domain, version, &body);
    let mut bytes = Vec::with_capacity(FRAME_HEADER_BYTES + body.len() + DIGEST_BYTES);
    bytes.extend_from_slice(magic);
    bytes.extend_from_slice(&version.to_le_bytes());
    bytes.extend_from_slice(&body_len.to_le_bytes());
    bytes.extend_from_slice(&body);
    bytes.extend_from_slice(&digest);
    Ok(bytes)
}

fn decode_frame<'a>(
    bytes: &'a [u8],
    magic: &[u8; 4],
    expected_version: u16,
    domain: &[u8],
    path: &str,
    version_code: CompilerFailureKind,
    digest_code: CompilerFailureKind,
) -> Result<(u16, &'a [u8], [u8; 32]), CompileError> {
    if bytes.len() < FRAME_HEADER_BYTES + DIGEST_BYTES {
        return Err(failure(
            CompilerFailureKind::MalformedArtifact,
            format!("{path}.header"),
            "framed bytes are shorter than the fixed header and digest",
            "supply one complete canonical frame",
        ));
    }
    if &bytes[..4] != magic {
        return Err(failure(
            CompilerFailureKind::MalformedArtifact,
            format!("{path}.magic"),
            "framing magic is invalid",
            "supply bytes emitted for the expected artifact layer",
        ));
    }
    let version = u16::from_le_bytes([bytes[4], bytes[5]]);
    if version != expected_version {
        return Err(failure(
            version_code,
            format!("{path}.schema_version"),
            format!("schema {version} is unsupported; expected {expected_version}"),
            "recompile or re-materialize with a compatible schema version",
        ));
    }
    let body_len = u32::from_le_bytes(bytes[6..10].try_into().expect("fixed frame slice")) as usize;
    let expected_len = FRAME_HEADER_BYTES
        .checked_add(body_len)
        .and_then(|len| len.checked_add(DIGEST_BYTES))
        .ok_or_else(|| {
            failure(
                CompilerFailureKind::MalformedArtifact,
                format!("{path}.body_length"),
                "framed body length overflowed addressable memory",
                "supply bounded canonical artifact bytes",
            )
        })?;
    if bytes.len() != expected_len {
        return Err(failure(
            CompilerFailureKind::MalformedArtifact,
            format!("{path}.body_length"),
            format!(
                "framing declares {expected_len} bytes but received {}",
                bytes.len()
            ),
            "supply exactly one complete canonical frame",
        ));
    }
    let body = &bytes[FRAME_HEADER_BYTES..FRAME_HEADER_BYTES + body_len];
    let expected_digest = digest_bytes(domain, version, body);
    let encoded_digest: [u8; 32] = bytes[FRAME_HEADER_BYTES + body_len..]
        .try_into()
        .expect("validated digest length");
    if expected_digest != encoded_digest {
        return Err(failure(
            digest_code,
            format!("{path}.digest"),
            "framed body does not match its content identity",
            "discard the corrupted bytes and regenerate them",
        ));
    }
    Ok((version, body, encoded_digest))
}

fn body_digest<T: Serialize>(domain: &[u8], body: &T) -> Result<Digest, CompileError> {
    let body = serde_json::to_vec(body).map_err(serialization_failure)?;
    Ok(Digest(digest_bytes(
        domain,
        TARGET_PAYLOAD_SCHEMA_VERSION,
        &body,
    )))
}

fn digest_bytes(domain: &[u8], version: u16, body: &[u8]) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(domain);
    hasher.update(&version.to_le_bytes());
    hasher.update(&(body.len() as u64).to_le_bytes());
    hasher.update(body);
    *hasher.finalize().as_bytes()
}

fn serialization_failure(error: serde_json::Error) -> CompileError {
    failure(
        CompilerFailureKind::MalformedArtifact,
        "envelope.serialization",
        error.to_string(),
        "report this deterministic canonical serialization failure",
    )
}