Skip to main content

hyprstream_rpc/
activation_envelope.rs

1//! Pure-data activation envelope for inter-host pipeline stages (#324/N1).
2//!
3//! This module deliberately contains no transport, chunk splitting, reassembly,
4//! credit, execution-ordering, cancellation, or tensor-execution code. It is
5//! crate-internal until one of those reviewed consumers needs the contract.
6//!
7//! # Deterministic wire profile
8//!
9//! The wire representation is a fixed, numeric-key CBOR map. Keys are exactly
10//! `0..=18`, in RFC 8949 deterministic order; every nested record is a fixed
11//! array. Integers and container lengths use shortest-form encodings, maps and
12//! arrays are definite-length, and byte/text fields are bounded before
13//! allocation. Decode also re-encodes and compares byte-for-byte, so alternate
14//! spellings never silently normalize into the same security identity.
15
16use thiserror::Error;
17
18const ACTIVATION_ENVELOPE_VERSION: u16 = 1;
19const ENVELOPE_FIELDS: usize = 19;
20const MAX_ENCODED_ENVELOPE_BYTES: usize = 16 * 1024;
21const MAX_TENANT_ID_BYTES: usize = 512;
22const MAX_ERROR_MESSAGE_BYTES: usize = 1024;
23
24/// All v1 digests are BLAKE3-256. Later consumers must prepend the matching
25/// domain before hashing; the algorithm/domain are not negotiated on the wire.
26pub(crate) const DIGEST_ALGORITHM: &str = "BLAKE3-256";
27pub(crate) const PLAN_DIGEST_DOMAIN: &str = "hyprstream activation plan digest v1";
28pub(crate) const CHUNK_DIGEST_DOMAIN: &str = "hyprstream activation chunk digest v1";
29pub(crate) const WHOLE_ACTIVATION_DIGEST_DOMAIN: &str = "hyprstream whole activation digest v1";
30
31macro_rules! fixed_bytes_type {
32    ($name:ident, $len:literal) => {
33        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
34        pub(crate) struct $name(pub(crate) [u8; $len]);
35
36        impl $name {
37            fn validate_nonzero(&self, label: &'static str) -> Result<(), ActivationEnvelopeError> {
38                validate_nonzero(&self.0, label)
39            }
40        }
41    };
42}
43
44fixed_bytes_type!(PlanDigest, 32);
45fixed_bytes_type!(RequestId, 16);
46fixed_bytes_type!(SessionId, 16);
47fixed_bytes_type!(DeltaDigest, 32);
48fixed_bytes_type!(ChunkDigest, 32);
49fixed_bytes_type!(WholeActivationDigest, 32);
50fixed_bytes_type!(ProducerIdentity, 32);
51
52/// Git object identity of the immutable model snapshot.
53///
54/// Both repository object formats are explicit on the wire; abbreviated or
55/// textual object IDs cannot enter the activation identity.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub(crate) enum ModelOid {
58    Sha1([u8; 20]),
59    Sha256([u8; 32]),
60}
61
62impl ModelOid {
63    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
64        match self {
65            Self::Sha1(bytes) => validate_nonzero(bytes, "model OID"),
66            Self::Sha256(bytes) => validate_nonzero(bytes, "model OID"),
67        }
68    }
69}
70
71/// Exact tenant identity used for authorization and state isolation.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub(crate) struct TenantId(pub(crate) String);
74
75impl TenantId {
76    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
77        validate_visible_text(
78            &self.0,
79            MAX_TENANT_ID_BYTES,
80            "tenant identity must contain 1..=512 non-whitespace bytes",
81        )
82    }
83}
84
85/// Exact delta identity admitted for this invocation.
86#[derive(Clone, Copy, Debug, PartialEq, Eq)]
87pub(crate) enum DeltaRevision {
88    BaseModel,
89    Digest(DeltaDigest),
90}
91
92impl DeltaRevision {
93    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
94        match self {
95            Self::BaseModel => Ok(()),
96            Self::Digest(digest) => digest.validate_nonzero("delta revision digest"),
97        }
98    }
99}
100
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub(crate) struct StageId(pub(crate) u32);
103
104/// The source stage's position in the complete ordered pipeline.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub(crate) enum StageRole {
107    First,
108    Interior,
109    Last,
110    Only,
111}
112
113/// Source stage's half-open global model-layer interval `[start_layer, end_layer)`.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub(crate) struct StageBoundary {
116    pub(crate) start_layer: u32,
117    pub(crate) end_layer: u32,
118    pub(crate) role: StageRole,
119}
120
121impl StageBoundary {
122    fn validate(
123        &self,
124        source_stage_id: StageId,
125        destination_stage_id: StageId,
126    ) -> Result<(), ActivationEnvelopeError> {
127        if self.start_layer >= self.end_layer {
128            return Err(ActivationEnvelopeError::Invalid(
129                "stage boundary must be a non-empty half-open interval",
130            ));
131        }
132
133        match self.role {
134            StageRole::First if source_stage_id.0 != 0 || self.start_layer != 0 => {
135                return Err(ActivationEnvelopeError::Invalid(
136                    "first stage must have identity and start layer zero",
137                ));
138            }
139            StageRole::Interior if source_stage_id.0 == 0 || self.start_layer == 0 => {
140                return Err(ActivationEnvelopeError::Invalid(
141                    "interior stage must have non-zero identity and start layer",
142                ));
143            }
144            StageRole::Last | StageRole::Only => {
145                return Err(ActivationEnvelopeError::Invalid(
146                    "last/only stage does not emit a next-stage activation",
147                ));
148            }
149            _ => {}
150        }
151
152        let expected_destination =
153            source_stage_id
154                .0
155                .checked_add(1)
156                .ok_or(ActivationEnvelopeError::Invalid(
157                    "source stage identity cannot advance without overflow",
158                ))?;
159        if destination_stage_id.0 != expected_destination {
160            return Err(ActivationEnvelopeError::Invalid(
161                "destination stage must immediately follow source stage",
162            ));
163        }
164        Ok(())
165    }
166}
167
168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
169pub(crate) enum ActivationPhase {
170    Prefill,
171    Decode,
172}
173
174/// Scalar types admitted by the dense activation ABI.
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub(crate) enum ActivationDtype {
177    Float16,
178    Bfloat16,
179    Float32,
180}
181
182impl ActivationDtype {
183    const fn byte_width(self) -> u64 {
184        match self {
185            Self::Float16 | Self::Bfloat16 => 2,
186            Self::Float32 => 4,
187        }
188    }
189}
190
191/// The sole v1 activation codec: dense row-major `[B,Q,H]`, with each scalar
192/// encoded in the admitted dtype's IEEE/raw little-endian representation.
193#[derive(Clone, Copy, Debug, PartialEq, Eq)]
194pub(crate) enum ActivationCodec {
195    RawLittleEndian,
196}
197
198/// Authoritative dense hidden-state ABI. Rank is structurally fixed at three.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub(crate) struct TensorMetadata {
201    pub(crate) dtype: ActivationDtype,
202    pub(crate) shape: [u64; 3],
203    pub(crate) byte_length: u64,
204    pub(crate) codec: ActivationCodec,
205}
206
207impl TensorMetadata {
208    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
209        let [batch, query, hidden] = self.shape;
210        if batch == 0 || query == 0 || hidden == 0 {
211            return Err(ActivationEnvelopeError::Invalid(
212                "activation shape [B,Q,H] requires three non-zero dimensions",
213            ));
214        }
215
216        let expected_length = batch
217            .checked_mul(query)
218            .and_then(|elements| elements.checked_mul(hidden))
219            .and_then(|elements| elements.checked_mul(self.dtype.byte_width()));
220        if expected_length != Some(self.byte_length) {
221            return Err(ActivationEnvelopeError::Invalid(
222                "activation byte length does not match dense [B,Q,H] dtype",
223            ));
224        }
225        Ok(())
226    }
227}
228
229/// Zero-based coordinate and exact logical byte span of one chunk.
230#[derive(Clone, Copy, Debug, PartialEq, Eq)]
231pub(crate) struct ChunkCoordinate {
232    pub(crate) index: u32,
233    pub(crate) count: u32,
234    pub(crate) offset: u64,
235    pub(crate) length: u64,
236}
237
238impl ChunkCoordinate {
239    fn validate(self, logical_length: u64) -> Result<(), ActivationEnvelopeError> {
240        if self.count == 0 || self.index >= self.count {
241            return Err(ActivationEnvelopeError::Invalid(
242                "chunk coordinate requires count > 0 and index < count",
243            ));
244        }
245        if self.length == 0 {
246            return Err(ActivationEnvelopeError::Invalid(
247                "chunk length must be non-zero",
248            ));
249        }
250        let end = self
251            .offset
252            .checked_add(self.length)
253            .ok_or(ActivationEnvelopeError::Invalid(
254                "chunk byte span overflows",
255            ))?;
256        if end > logical_length {
257            return Err(ActivationEnvelopeError::Invalid(
258                "chunk byte span exceeds logical activation length",
259            ));
260        }
261        if self.index == 0 && self.offset != 0 {
262            return Err(ActivationEnvelopeError::Invalid(
263                "first chunk must begin at logical byte zero",
264            ));
265        }
266        if self.index + 1 == self.count && end != logical_length {
267            return Err(ActivationEnvelopeError::Invalid(
268                "last chunk must end at the logical activation length",
269            ));
270        }
271        Ok(())
272    }
273}
274
275/// Claimed producing identity and the key epoch under which it will be bound.
276///
277/// N1 carries this data only. Cryptographic host binding is explicitly N5.
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279pub(crate) struct ActivationProvenance {
280    pub(crate) producer: ProducerIdentity,
281    pub(crate) key_epoch: u64,
282}
283
284impl ActivationProvenance {
285    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
286        self.producer.validate_nonzero("producer identity")
287    }
288}
289
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
291pub(crate) struct ActivationChunk {
292    pub(crate) tensor: TensorMetadata,
293    pub(crate) coordinate: ChunkCoordinate,
294    pub(crate) chunk_digest: ChunkDigest,
295    pub(crate) whole_activation_digest: WholeActivationDigest,
296}
297
298impl ActivationChunk {
299    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
300        self.tensor.validate()?;
301        self.coordinate.validate(self.tensor.byte_length)?;
302        self.chunk_digest.validate_nonzero("chunk digest")?;
303        self.whole_activation_digest
304            .validate_nonzero("whole activation digest")
305    }
306}
307
308/// Successful terminal marker following the final activation chunk.
309#[derive(Clone, Copy, Debug, PartialEq, Eq)]
310pub(crate) struct ActivationTerminal {
311    pub(crate) chunk_count: u32,
312    pub(crate) whole_activation_digest: WholeActivationDigest,
313}
314
315impl ActivationTerminal {
316    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
317        if self.chunk_count == 0 {
318            return Err(ActivationEnvelopeError::Invalid(
319                "terminal chunk count must be non-zero",
320            ));
321        }
322        self.whole_activation_digest
323            .validate_nonzero("whole activation digest")
324    }
325}
326
327#[derive(Clone, Copy, Debug, PartialEq, Eq)]
328pub(crate) enum ActivationErrorCode {
329    InvalidRequest,
330    StaleEpoch,
331    OutOfOrder,
332    Integrity,
333    Cancelled,
334    Internal,
335}
336
337#[derive(Clone, Debug, PartialEq, Eq)]
338pub(crate) struct ActivationError {
339    pub(crate) code: ActivationErrorCode,
340    pub(crate) message: String,
341    pub(crate) retryable: bool,
342}
343
344impl ActivationError {
345    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
346        validate_visible_text(
347            &self.message,
348            MAX_ERROR_MESSAGE_BYTES,
349            "error message must contain 1..=1024 non-whitespace bytes",
350        )
351    }
352}
353
354#[derive(Clone, Debug, PartialEq, Eq)]
355pub(crate) enum ActivationEnvelopeBody {
356    Chunk(ActivationChunk),
357    Terminal(ActivationTerminal),
358    Error(ActivationError),
359}
360
361impl ActivationEnvelopeBody {
362    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
363        match self {
364            Self::Chunk(chunk) => chunk.validate(),
365            Self::Terminal(terminal) => terminal.validate(),
366            Self::Error(error) => error.validate(),
367        }
368    }
369}
370
371/// Complete identity, ordering position, direction, tensor, integrity, and
372/// terminal data required for one activation protocol record.
373#[derive(Clone, Debug, PartialEq, Eq)]
374pub(crate) struct ActivationEnvelope {
375    pub(crate) version: u16,
376    pub(crate) model_oid: ModelOid,
377    pub(crate) plan_digest: PlanDigest,
378    pub(crate) request_id: RequestId,
379    pub(crate) session_id: SessionId,
380    pub(crate) tenant_id: TenantId,
381    pub(crate) delta_revision: DeltaRevision,
382    pub(crate) pipeline_epoch: u64,
383    pub(crate) microbatch_id: u64,
384    pub(crate) sequence_id: u64,
385    pub(crate) activation_seq: u64,
386    pub(crate) source_stage_id: StageId,
387    pub(crate) destination_stage_id: StageId,
388    pub(crate) source_boundary: StageBoundary,
389    pub(crate) phase: ActivationPhase,
390    pub(crate) start_position: u64,
391    pub(crate) accepted_token_index: Option<u64>,
392    pub(crate) provenance: ActivationProvenance,
393    pub(crate) body: ActivationEnvelopeBody,
394}
395
396impl ActivationEnvelope {
397    /// Serialize one semantically valid envelope in the sole canonical v1 form.
398    pub(crate) fn to_cbor(&self) -> Result<Vec<u8>, ActivationEnvelopeError> {
399        self.validate()?;
400        let bytes = self.encode_canonical();
401        if bytes.len() > MAX_ENCODED_ENVELOPE_BYTES {
402            return Err(ActivationEnvelopeError::TooLarge(bytes.len()));
403        }
404        Ok(bytes)
405    }
406
407    /// Preflight, decode, validate, and re-encode exactly one canonical envelope.
408    pub(crate) fn from_cbor(bytes: &[u8]) -> Result<Self, ActivationEnvelopeError> {
409        if bytes.len() > MAX_ENCODED_ENVELOPE_BYTES {
410            return Err(ActivationEnvelopeError::TooLarge(bytes.len()));
411        }
412
413        let envelope = Self::decode_preflight(bytes)?;
414        envelope.validate()?;
415        if envelope.encode_canonical() != bytes {
416            return Err(ActivationEnvelopeError::NonCanonical);
417        }
418        Ok(envelope)
419    }
420
421    fn validate(&self) -> Result<(), ActivationEnvelopeError> {
422        if self.version != ACTIVATION_ENVELOPE_VERSION {
423            return Err(ActivationEnvelopeError::Invalid(
424                "unsupported activation envelope version",
425            ));
426        }
427        self.model_oid.validate()?;
428        self.plan_digest.validate_nonzero("plan digest")?;
429        self.request_id.validate_nonzero("request identity")?;
430        self.session_id.validate_nonzero("session identity")?;
431        self.tenant_id.validate()?;
432        self.delta_revision.validate()?;
433        self.source_boundary
434            .validate(self.source_stage_id, self.destination_stage_id)?;
435
436        match (self.phase, self.activation_seq, self.accepted_token_index) {
437            (ActivationPhase::Prefill, 0, None) => {}
438            (ActivationPhase::Prefill, _, _) => {
439                return Err(ActivationEnvelopeError::Invalid(
440                    "prefill requires activation sequence zero and no accepted-token index",
441                ));
442            }
443            (ActivationPhase::Decode, activation_seq, Some(token_index))
444                if token_index
445                    .checked_add(1)
446                    .is_some_and(|expected| expected == activation_seq) => {}
447            (ActivationPhase::Decode, _, _) => {
448                return Err(ActivationEnvelopeError::Invalid(
449                    "decode activation sequence must equal accepted-token index plus one",
450                ));
451            }
452        }
453
454        self.provenance.validate()?;
455        self.body.validate()
456    }
457
458    fn encode_canonical(&self) -> Vec<u8> {
459        let mut out = Vec::with_capacity(512);
460        put_map(&mut out, ENVELOPE_FIELDS);
461        put_field(&mut out, 0, |out| put_uint(out, u64::from(self.version)));
462        put_field(&mut out, 1, |out| put_model_oid(out, self.model_oid));
463        put_field(&mut out, 2, |out| put_bytes(out, &self.plan_digest.0));
464        put_field(&mut out, 3, |out| put_bytes(out, &self.request_id.0));
465        put_field(&mut out, 4, |out| put_bytes(out, &self.session_id.0));
466        put_field(&mut out, 5, |out| put_text(out, &self.tenant_id.0));
467        put_field(&mut out, 6, |out| {
468            put_delta_revision(out, self.delta_revision);
469        });
470        put_field(&mut out, 7, |out| put_uint(out, self.pipeline_epoch));
471        put_field(&mut out, 8, |out| put_uint(out, self.microbatch_id));
472        put_field(&mut out, 9, |out| put_uint(out, self.sequence_id));
473        put_field(&mut out, 10, |out| put_uint(out, self.activation_seq));
474        put_field(&mut out, 11, |out| {
475            put_uint(out, u64::from(self.source_stage_id.0));
476        });
477        put_field(&mut out, 12, |out| {
478            put_uint(out, u64::from(self.destination_stage_id.0));
479        });
480        put_field(&mut out, 13, |out| {
481            put_stage_boundary(out, self.source_boundary);
482        });
483        put_field(&mut out, 14, |out| {
484            put_uint(out, activation_phase_code(self.phase));
485        });
486        put_field(&mut out, 15, |out| put_uint(out, self.start_position));
487        put_field(&mut out, 16, |out| match self.accepted_token_index {
488            Some(index) => put_uint(out, index),
489            None => put_null(out),
490        });
491        put_field(&mut out, 17, |out| {
492            put_provenance(out, self.provenance);
493        });
494        put_field(&mut out, 18, |out| put_body(out, &self.body));
495        out
496    }
497
498    fn decode_preflight(bytes: &[u8]) -> Result<Self, ActivationEnvelopeError> {
499        let mut input = CanonicalDecoder::new(bytes);
500        input.map_exact(ENVELOPE_FIELDS)?;
501
502        input.field(0)?;
503        let version = input.u16()?;
504        input.field(1)?;
505        let model_oid = input.model_oid()?;
506        input.field(2)?;
507        let plan_digest = PlanDigest(input.fixed_bytes()?);
508        input.field(3)?;
509        let request_id = RequestId(input.fixed_bytes()?);
510        input.field(4)?;
511        let session_id = SessionId(input.fixed_bytes()?);
512        input.field(5)?;
513        let tenant_id = TenantId(input.text(MAX_TENANT_ID_BYTES)?);
514        input.field(6)?;
515        let delta_revision = input.delta_revision()?;
516        input.field(7)?;
517        let pipeline_epoch = input.uint()?;
518        input.field(8)?;
519        let microbatch_id = input.uint()?;
520        input.field(9)?;
521        let sequence_id = input.uint()?;
522        input.field(10)?;
523        let activation_seq = input.uint()?;
524        input.field(11)?;
525        let source_stage_id = StageId(input.u32()?);
526        input.field(12)?;
527        let destination_stage_id = StageId(input.u32()?);
528        input.field(13)?;
529        let source_boundary = input.stage_boundary()?;
530        input.field(14)?;
531        let phase = input.activation_phase()?;
532        input.field(15)?;
533        let start_position = input.uint()?;
534        input.field(16)?;
535        let accepted_token_index = input.optional_uint()?;
536        input.field(17)?;
537        let provenance = input.provenance()?;
538        input.field(18)?;
539        let body = input.body()?;
540        input.finish()?;
541
542        Ok(Self {
543            version,
544            model_oid,
545            plan_digest,
546            request_id,
547            session_id,
548            tenant_id,
549            delta_revision,
550            pipeline_epoch,
551            microbatch_id,
552            sequence_id,
553            activation_seq,
554            source_stage_id,
555            destination_stage_id,
556            source_boundary,
557            phase,
558            start_position,
559            accepted_token_index,
560            provenance,
561            body,
562        })
563    }
564}
565
566#[derive(Debug, Error, PartialEq, Eq)]
567pub(crate) enum ActivationEnvelopeError {
568    #[error("activation envelope CBOR decode failed: {0}")]
569    Decode(String),
570    #[error("activation envelope is invalid: {0}")]
571    Invalid(&'static str),
572    #[error("activation envelope exceeds the {MAX_ENCODED_ENVELOPE_BYTES}-byte metadata cap: {0}")]
573    TooLarge(usize),
574    #[error("activation envelope is not deterministic canonical CBOR")]
575    NonCanonical,
576}
577
578fn validate_nonzero(bytes: &[u8], label: &'static str) -> Result<(), ActivationEnvelopeError> {
579    if bytes.iter().all(|byte| *byte == 0) {
580        return Err(ActivationEnvelopeError::Invalid(label));
581    }
582    Ok(())
583}
584
585fn validate_visible_text(
586    text: &str,
587    max_bytes: usize,
588    error: &'static str,
589) -> Result<(), ActivationEnvelopeError> {
590    if text.is_empty()
591        || text.len() > max_bytes
592        || text
593            .chars()
594            .any(|character| character.is_control() || character.is_whitespace())
595    {
596        return Err(ActivationEnvelopeError::Invalid(error));
597    }
598    Ok(())
599}
600
601fn put_field(out: &mut Vec<u8>, key: u64, value: impl FnOnce(&mut Vec<u8>)) {
602    put_uint(out, key);
603    value(out);
604}
605
606fn put_head(out: &mut Vec<u8>, major: u8, argument: u64) {
607    let prefix = major << 5;
608    match argument {
609        0..=23 => out.push(prefix | argument as u8),
610        24..=0xff => {
611            out.push(prefix | 24);
612            out.push(argument as u8);
613        }
614        0x100..=0xffff => {
615            out.push(prefix | 25);
616            out.extend_from_slice(&(argument as u16).to_be_bytes());
617        }
618        0x1_0000..=0xffff_ffff => {
619            out.push(prefix | 26);
620            out.extend_from_slice(&(argument as u32).to_be_bytes());
621        }
622        _ => {
623            out.push(prefix | 27);
624            out.extend_from_slice(&argument.to_be_bytes());
625        }
626    }
627}
628
629fn put_uint(out: &mut Vec<u8>, value: u64) {
630    put_head(out, 0, value);
631}
632
633fn put_bytes(out: &mut Vec<u8>, value: &[u8]) {
634    put_head(out, 2, value.len() as u64);
635    out.extend_from_slice(value);
636}
637
638fn put_text(out: &mut Vec<u8>, value: &str) {
639    put_head(out, 3, value.len() as u64);
640    out.extend_from_slice(value.as_bytes());
641}
642
643fn put_array(out: &mut Vec<u8>, length: usize) {
644    put_head(out, 4, length as u64);
645}
646
647fn put_map(out: &mut Vec<u8>, length: usize) {
648    put_head(out, 5, length as u64);
649}
650
651fn put_bool(out: &mut Vec<u8>, value: bool) {
652    out.push(if value { 0xf5 } else { 0xf4 });
653}
654
655fn put_null(out: &mut Vec<u8>) {
656    out.push(0xf6);
657}
658
659fn put_model_oid(out: &mut Vec<u8>, oid: ModelOid) {
660    put_array(out, 2);
661    match oid {
662        ModelOid::Sha1(bytes) => {
663            put_uint(out, 0);
664            put_bytes(out, &bytes);
665        }
666        ModelOid::Sha256(bytes) => {
667            put_uint(out, 1);
668            put_bytes(out, &bytes);
669        }
670    }
671}
672
673fn put_delta_revision(out: &mut Vec<u8>, revision: DeltaRevision) {
674    match revision {
675        DeltaRevision::BaseModel => {
676            put_array(out, 1);
677            put_uint(out, 0);
678        }
679        DeltaRevision::Digest(digest) => {
680            put_array(out, 2);
681            put_uint(out, 1);
682            put_bytes(out, &digest.0);
683        }
684    }
685}
686
687fn stage_role_code(role: StageRole) -> u64 {
688    match role {
689        StageRole::First => 0,
690        StageRole::Interior => 1,
691        StageRole::Last => 2,
692        StageRole::Only => 3,
693    }
694}
695
696fn put_stage_boundary(out: &mut Vec<u8>, boundary: StageBoundary) {
697    put_array(out, 3);
698    put_uint(out, u64::from(boundary.start_layer));
699    put_uint(out, u64::from(boundary.end_layer));
700    put_uint(out, stage_role_code(boundary.role));
701}
702
703fn activation_phase_code(phase: ActivationPhase) -> u64 {
704    match phase {
705        ActivationPhase::Prefill => 0,
706        ActivationPhase::Decode => 1,
707    }
708}
709
710fn dtype_code(dtype: ActivationDtype) -> u64 {
711    match dtype {
712        ActivationDtype::Float16 => 0,
713        ActivationDtype::Bfloat16 => 1,
714        ActivationDtype::Float32 => 2,
715    }
716}
717
718fn codec_code(codec: ActivationCodec) -> u64 {
719    match codec {
720        ActivationCodec::RawLittleEndian => 0,
721    }
722}
723
724fn put_tensor(out: &mut Vec<u8>, tensor: TensorMetadata) {
725    put_array(out, 6);
726    put_uint(out, dtype_code(tensor.dtype));
727    for dimension in tensor.shape {
728        put_uint(out, dimension);
729    }
730    put_uint(out, tensor.byte_length);
731    put_uint(out, codec_code(tensor.codec));
732}
733
734fn put_coordinate(out: &mut Vec<u8>, coordinate: ChunkCoordinate) {
735    put_array(out, 4);
736    put_uint(out, u64::from(coordinate.index));
737    put_uint(out, u64::from(coordinate.count));
738    put_uint(out, coordinate.offset);
739    put_uint(out, coordinate.length);
740}
741
742fn put_provenance(out: &mut Vec<u8>, provenance: ActivationProvenance) {
743    put_array(out, 2);
744    put_bytes(out, &provenance.producer.0);
745    put_uint(out, provenance.key_epoch);
746}
747
748fn error_code(error: ActivationErrorCode) -> u64 {
749    match error {
750        ActivationErrorCode::InvalidRequest => 0,
751        ActivationErrorCode::StaleEpoch => 1,
752        ActivationErrorCode::OutOfOrder => 2,
753        ActivationErrorCode::Integrity => 3,
754        ActivationErrorCode::Cancelled => 4,
755        ActivationErrorCode::Internal => 5,
756    }
757}
758
759fn put_body(out: &mut Vec<u8>, body: &ActivationEnvelopeBody) {
760    match body {
761        ActivationEnvelopeBody::Chunk(chunk) => {
762            put_array(out, 5);
763            put_uint(out, 0);
764            put_tensor(out, chunk.tensor);
765            put_coordinate(out, chunk.coordinate);
766            put_bytes(out, &chunk.chunk_digest.0);
767            put_bytes(out, &chunk.whole_activation_digest.0);
768        }
769        ActivationEnvelopeBody::Terminal(terminal) => {
770            put_array(out, 3);
771            put_uint(out, 1);
772            put_uint(out, u64::from(terminal.chunk_count));
773            put_bytes(out, &terminal.whole_activation_digest.0);
774        }
775        ActivationEnvelopeBody::Error(error) => {
776            put_array(out, 4);
777            put_uint(out, 2);
778            put_uint(out, error_code(error.code));
779            put_text(out, &error.message);
780            put_bool(out, error.retryable);
781        }
782    }
783}
784
785/// Bounded semantic decoder for the exact deterministic CBOR subset above.
786struct CanonicalDecoder<'a> {
787    input: &'a [u8],
788    offset: usize,
789    items: usize,
790}
791
792impl<'a> CanonicalDecoder<'a> {
793    fn new(input: &'a [u8]) -> Self {
794        Self {
795            input,
796            offset: 0,
797            items: 0,
798        }
799    }
800
801    fn error(message: impl Into<String>) -> ActivationEnvelopeError {
802        ActivationEnvelopeError::Decode(message.into())
803    }
804
805    fn finish(self) -> Result<(), ActivationEnvelopeError> {
806        if self.offset != self.input.len() {
807            return Err(Self::error("CBOR contains trailing data"));
808        }
809        Ok(())
810    }
811
812    fn read_byte(&mut self) -> Result<u8, ActivationEnvelopeError> {
813        let byte = self
814            .input
815            .get(self.offset)
816            .copied()
817            .ok_or_else(|| Self::error("truncated CBOR item"))?;
818        self.offset += 1;
819        Ok(byte)
820    }
821
822    fn read_exact<const N: usize>(&mut self) -> Result<[u8; N], ActivationEnvelopeError> {
823        let end = self
824            .offset
825            .checked_add(N)
826            .ok_or_else(|| Self::error("CBOR length overflow"))?;
827        let bytes = self
828            .input
829            .get(self.offset..end)
830            .ok_or_else(|| Self::error("truncated CBOR argument"))?;
831        self.offset = end;
832        bytes
833            .try_into()
834            .map_err(|_| Self::error("invalid CBOR argument width"))
835    }
836
837    fn head(&mut self) -> Result<(u8, u64), ActivationEnvelopeError> {
838        self.items = self
839            .items
840            .checked_add(1)
841            .ok_or_else(|| Self::error("CBOR item counter overflow"))?;
842        if self.items > 128 {
843            return Err(Self::error("CBOR item count exceeds envelope profile"));
844        }
845
846        let initial = self.read_byte()?;
847        let major = initial >> 5;
848        let additional = initial & 0x1f;
849        let argument = match additional {
850            value @ 0..=23 => u64::from(value),
851            24 => {
852                let value = u64::from(self.read_byte()?);
853                if value < 24 {
854                    return Err(Self::error("CBOR argument is not shortest-form encoded"));
855                }
856                value
857            }
858            25 => {
859                let value = u64::from(u16::from_be_bytes(self.read_exact()?));
860                if value <= u64::from(u8::MAX) {
861                    return Err(Self::error("CBOR argument is not shortest-form encoded"));
862                }
863                value
864            }
865            26 => {
866                let value = u64::from(u32::from_be_bytes(self.read_exact()?));
867                if value <= u64::from(u16::MAX) {
868                    return Err(Self::error("CBOR argument is not shortest-form encoded"));
869                }
870                value
871            }
872            27 => {
873                let value = u64::from_be_bytes(self.read_exact()?);
874                if value <= u64::from(u32::MAX) {
875                    return Err(Self::error("CBOR argument is not shortest-form encoded"));
876                }
877                value
878            }
879            31 => return Err(Self::error("indefinite-length CBOR is forbidden")),
880            _ => {
881                return Err(Self::error("reserved CBOR additional-information value"));
882            }
883        };
884        Ok((major, argument))
885    }
886
887    fn length(argument: u64) -> Result<usize, ActivationEnvelopeError> {
888        usize::try_from(argument).map_err(|_| Self::error("CBOR length does not fit address space"))
889    }
890
891    fn container_exact(
892        &mut self,
893        expected_major: u8,
894        expected_length: usize,
895    ) -> Result<(), ActivationEnvelopeError> {
896        let (major, argument) = self.head()?;
897        if major != expected_major {
898            return Err(Self::error(format!(
899                "unexpected CBOR major type {major}, expected {expected_major}"
900            )));
901        }
902        let length = Self::length(argument)?;
903        if length != expected_length {
904            return Err(Self::error(format!(
905                "CBOR container has {length} entries, expected {expected_length}"
906            )));
907        }
908        Ok(())
909    }
910
911    fn array_exact(&mut self, length: usize) -> Result<(), ActivationEnvelopeError> {
912        self.container_exact(4, length)
913    }
914
915    fn map_exact(&mut self, length: usize) -> Result<(), ActivationEnvelopeError> {
916        self.container_exact(5, length)
917    }
918
919    fn uint(&mut self) -> Result<u64, ActivationEnvelopeError> {
920        let (major, argument) = self.head()?;
921        if major != 0 {
922            return Err(Self::error("expected unsigned CBOR integer"));
923        }
924        Ok(argument)
925    }
926
927    fn u16(&mut self) -> Result<u16, ActivationEnvelopeError> {
928        u16::try_from(self.uint()?).map_err(|_| Self::error("integer does not fit u16"))
929    }
930
931    fn u32(&mut self) -> Result<u32, ActivationEnvelopeError> {
932        u32::try_from(self.uint()?).map_err(|_| Self::error("integer does not fit u32"))
933    }
934
935    fn field(&mut self, expected: u64) -> Result<(), ActivationEnvelopeError> {
936        let actual = self.uint()?;
937        if actual != expected {
938            return Err(Self::error(format!(
939                "activation map field is missing, duplicate, unknown, or reordered: expected {expected}, got {actual}"
940            )));
941        }
942        Ok(())
943    }
944
945    fn bytes(&mut self, limit: usize) -> Result<&'a [u8], ActivationEnvelopeError> {
946        let (major, argument) = self.head()?;
947        if major != 2 {
948            return Err(Self::error("expected CBOR byte string"));
949        }
950        let length = Self::length(argument)?;
951        if length > limit {
952            return Err(Self::error(format!(
953                "CBOR byte string length {length} exceeds {limit}"
954            )));
955        }
956        let end = self
957            .offset
958            .checked_add(length)
959            .ok_or_else(|| Self::error("CBOR byte string length overflow"))?;
960        let bytes = self
961            .input
962            .get(self.offset..end)
963            .ok_or_else(|| Self::error("truncated CBOR byte string"))?;
964        self.offset = end;
965        Ok(bytes)
966    }
967
968    fn fixed_bytes<const N: usize>(&mut self) -> Result<[u8; N], ActivationEnvelopeError> {
969        let bytes = self.bytes(N)?;
970        if bytes.len() != N {
971            return Err(Self::error(format!(
972                "CBOR byte string has {} bytes, expected {N}",
973                bytes.len()
974            )));
975        }
976        bytes
977            .try_into()
978            .map_err(|_| Self::error("invalid fixed byte string width"))
979    }
980
981    fn text(&mut self, limit: usize) -> Result<String, ActivationEnvelopeError> {
982        let (major, argument) = self.head()?;
983        if major != 3 {
984            return Err(Self::error("expected CBOR text string"));
985        }
986        let length = Self::length(argument)?;
987        if length > limit {
988            return Err(Self::error(format!(
989                "CBOR text length {length} exceeds {limit}"
990            )));
991        }
992        let end = self
993            .offset
994            .checked_add(length)
995            .ok_or_else(|| Self::error("CBOR text length overflow"))?;
996        let bytes = self
997            .input
998            .get(self.offset..end)
999            .ok_or_else(|| Self::error("truncated CBOR text"))?;
1000        self.offset = end;
1001        let text =
1002            std::str::from_utf8(bytes).map_err(|_| Self::error("CBOR text is not valid UTF-8"))?;
1003        Ok(text.to_owned())
1004    }
1005
1006    fn optional_uint(&mut self) -> Result<Option<u64>, ActivationEnvelopeError> {
1007        match self.input.get(self.offset).copied() {
1008            Some(0xf6) => {
1009                self.offset += 1;
1010                self.items += 1;
1011                Ok(None)
1012            }
1013            Some(_) => self.uint().map(Some),
1014            None => Err(Self::error("truncated optional integer")),
1015        }
1016    }
1017
1018    fn boolean(&mut self) -> Result<bool, ActivationEnvelopeError> {
1019        let byte = self.read_byte()?;
1020        self.items += 1;
1021        match byte {
1022            0xf4 => Ok(false),
1023            0xf5 => Ok(true),
1024            _ => Err(Self::error("expected canonical CBOR boolean")),
1025        }
1026    }
1027
1028    fn model_oid(&mut self) -> Result<ModelOid, ActivationEnvelopeError> {
1029        self.array_exact(2)?;
1030        match self.uint()? {
1031            0 => Ok(ModelOid::Sha1(self.fixed_bytes()?)),
1032            1 => Ok(ModelOid::Sha256(self.fixed_bytes()?)),
1033            value => Err(Self::error(format!("unknown model OID algorithm {value}"))),
1034        }
1035    }
1036
1037    fn delta_revision(&mut self) -> Result<DeltaRevision, ActivationEnvelopeError> {
1038        let start = self.offset;
1039        let (major, length) = self.head()?;
1040        if major != 4 {
1041            return Err(Self::error("delta revision must be a CBOR array"));
1042        }
1043        match (length, self.uint()?) {
1044            (1, 0) => Ok(DeltaRevision::BaseModel),
1045            (2, 1) => Ok(DeltaRevision::Digest(DeltaDigest(self.fixed_bytes()?))),
1046            _ => {
1047                self.offset = start;
1048                Err(Self::error("unknown or malformed delta revision"))
1049            }
1050        }
1051    }
1052
1053    fn stage_boundary(&mut self) -> Result<StageBoundary, ActivationEnvelopeError> {
1054        self.array_exact(3)?;
1055        let start_layer = self.u32()?;
1056        let end_layer = self.u32()?;
1057        let role = match self.uint()? {
1058            0 => StageRole::First,
1059            1 => StageRole::Interior,
1060            2 => StageRole::Last,
1061            3 => StageRole::Only,
1062            value => return Err(Self::error(format!("unknown stage role {value}"))),
1063        };
1064        Ok(StageBoundary {
1065            start_layer,
1066            end_layer,
1067            role,
1068        })
1069    }
1070
1071    fn activation_phase(&mut self) -> Result<ActivationPhase, ActivationEnvelopeError> {
1072        match self.uint()? {
1073            0 => Ok(ActivationPhase::Prefill),
1074            1 => Ok(ActivationPhase::Decode),
1075            value => Err(Self::error(format!("unknown activation phase {value}"))),
1076        }
1077    }
1078
1079    fn provenance(&mut self) -> Result<ActivationProvenance, ActivationEnvelopeError> {
1080        self.array_exact(2)?;
1081        Ok(ActivationProvenance {
1082            producer: ProducerIdentity(self.fixed_bytes()?),
1083            key_epoch: self.uint()?,
1084        })
1085    }
1086
1087    fn tensor(&mut self) -> Result<TensorMetadata, ActivationEnvelopeError> {
1088        self.array_exact(6)?;
1089        let dtype = match self.uint()? {
1090            0 => ActivationDtype::Float16,
1091            1 => ActivationDtype::Bfloat16,
1092            2 => ActivationDtype::Float32,
1093            value => return Err(Self::error(format!("unknown activation dtype {value}"))),
1094        };
1095        let shape = [self.uint()?, self.uint()?, self.uint()?];
1096        let byte_length = self.uint()?;
1097        let codec = match self.uint()? {
1098            0 => ActivationCodec::RawLittleEndian,
1099            value => return Err(Self::error(format!("unknown activation codec {value}"))),
1100        };
1101        Ok(TensorMetadata {
1102            dtype,
1103            shape,
1104            byte_length,
1105            codec,
1106        })
1107    }
1108
1109    fn coordinate(&mut self) -> Result<ChunkCoordinate, ActivationEnvelopeError> {
1110        self.array_exact(4)?;
1111        Ok(ChunkCoordinate {
1112            index: self.u32()?,
1113            count: self.u32()?,
1114            offset: self.uint()?,
1115            length: self.uint()?,
1116        })
1117    }
1118
1119    fn body(&mut self) -> Result<ActivationEnvelopeBody, ActivationEnvelopeError> {
1120        let start = self.offset;
1121        let (major, length) = self.head()?;
1122        if major != 4 {
1123            return Err(Self::error("activation body must be a CBOR array"));
1124        }
1125        let kind = self.uint()?;
1126        match (kind, length) {
1127            (0, 5) => Ok(ActivationEnvelopeBody::Chunk(ActivationChunk {
1128                tensor: self.tensor()?,
1129                coordinate: self.coordinate()?,
1130                chunk_digest: ChunkDigest(self.fixed_bytes()?),
1131                whole_activation_digest: WholeActivationDigest(self.fixed_bytes()?),
1132            })),
1133            (1, 3) => Ok(ActivationEnvelopeBody::Terminal(ActivationTerminal {
1134                chunk_count: self.u32()?,
1135                whole_activation_digest: WholeActivationDigest(self.fixed_bytes()?),
1136            })),
1137            (2, 4) => {
1138                let code = match self.uint()? {
1139                    0 => ActivationErrorCode::InvalidRequest,
1140                    1 => ActivationErrorCode::StaleEpoch,
1141                    2 => ActivationErrorCode::OutOfOrder,
1142                    3 => ActivationErrorCode::Integrity,
1143                    4 => ActivationErrorCode::Cancelled,
1144                    5 => ActivationErrorCode::Internal,
1145                    value => {
1146                        return Err(Self::error(format!(
1147                            "unknown activation error code {value}"
1148                        )));
1149                    }
1150                };
1151                Ok(ActivationEnvelopeBody::Error(ActivationError {
1152                    code,
1153                    message: self.text(MAX_ERROR_MESSAGE_BYTES)?,
1154                    retryable: self.boolean()?,
1155                }))
1156            }
1157            _ => {
1158                self.offset = start;
1159                Err(Self::error("unknown or malformed activation body"))
1160            }
1161        }
1162    }
1163}
1164
1165#[cfg(test)]
1166#[allow(clippy::unwrap_used, clippy::expect_used)]
1167mod tests {
1168    use super::*;
1169
1170    fn chunk_envelope() -> ActivationEnvelope {
1171        ActivationEnvelope {
1172            version: ACTIVATION_ENVELOPE_VERSION,
1173            model_oid: ModelOid::Sha1([1; 20]),
1174            plan_digest: PlanDigest([2; 32]),
1175            request_id: RequestId([3; 16]),
1176            session_id: SessionId([4; 16]),
1177            tenant_id: TenantId("did:web:tenant.example".to_owned()),
1178            delta_revision: DeltaRevision::Digest(DeltaDigest([5; 32])),
1179            pipeline_epoch: 7,
1180            microbatch_id: 11,
1181            sequence_id: 13,
1182            activation_seq: 21,
1183            source_stage_id: StageId(1),
1184            destination_stage_id: StageId(2),
1185            source_boundary: StageBoundary {
1186                start_layer: 8,
1187                end_layer: 16,
1188                role: StageRole::Interior,
1189            },
1190            phase: ActivationPhase::Decode,
1191            start_position: 21,
1192            accepted_token_index: Some(20),
1193            provenance: ActivationProvenance {
1194                producer: ProducerIdentity([6; 32]),
1195                key_epoch: 9,
1196            },
1197            body: ActivationEnvelopeBody::Chunk(ActivationChunk {
1198                tensor: TensorMetadata {
1199                    dtype: ActivationDtype::Bfloat16,
1200                    shape: [2, 4, 8],
1201                    byte_length: 128,
1202                    codec: ActivationCodec::RawLittleEndian,
1203                },
1204                coordinate: ChunkCoordinate {
1205                    index: 1,
1206                    count: 3,
1207                    offset: 32,
1208                    length: 32,
1209                },
1210                chunk_digest: ChunkDigest([7; 32]),
1211                whole_activation_digest: WholeActivationDigest([8; 32]),
1212            }),
1213        }
1214    }
1215
1216    fn prefill_envelope() -> ActivationEnvelope {
1217        let mut envelope = chunk_envelope();
1218        envelope.delta_revision = DeltaRevision::BaseModel;
1219        envelope.activation_seq = 0;
1220        envelope.source_stage_id = StageId(0);
1221        envelope.destination_stage_id = StageId(1);
1222        envelope.source_boundary = StageBoundary {
1223            start_layer: 0,
1224            end_layer: 8,
1225            role: StageRole::First,
1226        };
1227        envelope.phase = ActivationPhase::Prefill;
1228        envelope.start_position = 0;
1229        envelope.accepted_token_index = None;
1230        envelope
1231    }
1232
1233    fn chunk_mut(envelope: &mut ActivationEnvelope) -> &mut ActivationChunk {
1234        let ActivationEnvelopeBody::Chunk(chunk) = &mut envelope.body else {
1235            panic!("fixture is a chunk");
1236        };
1237        chunk
1238    }
1239
1240    fn unchecked_canonical(envelope: &ActivationEnvelope) -> Vec<u8> {
1241        envelope.encode_canonical()
1242    }
1243
1244    fn unique_subslice(haystack: &[u8], needle: &[u8]) -> usize {
1245        let matches: Vec<_> = haystack
1246            .windows(needle.len())
1247            .enumerate()
1248            .filter_map(|(index, window)| (window == needle).then_some(index))
1249            .collect();
1250        assert_eq!(matches.len(), 1, "wire marker must be unique");
1251        matches[0]
1252    }
1253
1254    fn assert_sender_and_receiver_invalid(envelope: &ActivationEnvelope, expected: &'static str) {
1255        assert_eq!(
1256            envelope.to_cbor().unwrap_err(),
1257            ActivationEnvelopeError::Invalid(expected),
1258            "sender guard did not fail causally"
1259        );
1260        assert_eq!(
1261            ActivationEnvelope::from_cbor(&unchecked_canonical(envelope)).unwrap_err(),
1262            ActivationEnvelopeError::Invalid(expected),
1263            "receiver guard did not fail causally"
1264        );
1265    }
1266
1267    #[test]
1268    fn chunk_round_trip_is_deterministic_and_preserves_every_contract_field() {
1269        let envelope = chunk_envelope();
1270        let first = envelope.to_cbor().unwrap();
1271        let second = envelope.to_cbor().unwrap();
1272        assert_eq!(first, second);
1273        assert_eq!(ActivationEnvelope::from_cbor(&first).unwrap(), envelope);
1274        assert_eq!(first[0], 0xb3, "top-level wire item must be a 19-field map");
1275    }
1276
1277    #[test]
1278    fn terminal_and_error_variants_round_trip() {
1279        let mut terminal = prefill_envelope();
1280        terminal.model_oid = ModelOid::Sha256([10; 32]);
1281        terminal.body = ActivationEnvelopeBody::Terminal(ActivationTerminal {
1282            chunk_count: 3,
1283            whole_activation_digest: WholeActivationDigest([9; 32]),
1284        });
1285
1286        let mut error = terminal.clone();
1287        error.body = ActivationEnvelopeBody::Error(ActivationError {
1288            code: ActivationErrorCode::Integrity,
1289            message: "whole-activation-digest-mismatch".to_owned(),
1290            retryable: false,
1291        });
1292
1293        for envelope in [terminal, error] {
1294            let encoded = envelope.to_cbor().unwrap();
1295            assert_eq!(ActivationEnvelope::from_cbor(&encoded).unwrap(), envelope);
1296        }
1297    }
1298
1299    #[test]
1300    fn sender_and_receiver_reject_identity_guard_inversions() {
1301        let mut envelope = chunk_envelope();
1302        envelope.version = 2;
1303        assert_sender_and_receiver_invalid(&envelope, "unsupported activation envelope version");
1304
1305        envelope = chunk_envelope();
1306        envelope.model_oid = ModelOid::Sha1([0; 20]);
1307        assert_sender_and_receiver_invalid(&envelope, "model OID");
1308
1309        envelope = chunk_envelope();
1310        envelope.plan_digest = PlanDigest([0; 32]);
1311        assert_sender_and_receiver_invalid(&envelope, "plan digest");
1312
1313        envelope = chunk_envelope();
1314        envelope.request_id = RequestId([0; 16]);
1315        assert_sender_and_receiver_invalid(&envelope, "request identity");
1316
1317        envelope = chunk_envelope();
1318        envelope.session_id = SessionId([0; 16]);
1319        assert_sender_and_receiver_invalid(&envelope, "session identity");
1320
1321        envelope = chunk_envelope();
1322        envelope.tenant_id = TenantId(String::new());
1323        assert_sender_and_receiver_invalid(
1324            &envelope,
1325            "tenant identity must contain 1..=512 non-whitespace bytes",
1326        );
1327
1328        envelope = chunk_envelope();
1329        envelope.delta_revision = DeltaRevision::Digest(DeltaDigest([0; 32]));
1330        assert_sender_and_receiver_invalid(&envelope, "delta revision digest");
1331
1332        envelope = chunk_envelope();
1333        envelope.provenance.producer = ProducerIdentity([0; 32]);
1334        assert_sender_and_receiver_invalid(&envelope, "producer identity");
1335    }
1336
1337    #[test]
1338    fn sender_and_receiver_enforce_phase_activation_sequence_causality() {
1339        let mut envelope = prefill_envelope();
1340        envelope.activation_seq = 1;
1341        assert_sender_and_receiver_invalid(
1342            &envelope,
1343            "prefill requires activation sequence zero and no accepted-token index",
1344        );
1345
1346        envelope = prefill_envelope();
1347        envelope.accepted_token_index = Some(0);
1348        assert_sender_and_receiver_invalid(
1349            &envelope,
1350            "prefill requires activation sequence zero and no accepted-token index",
1351        );
1352
1353        envelope = chunk_envelope();
1354        envelope.activation_seq = 20;
1355        assert_sender_and_receiver_invalid(
1356            &envelope,
1357            "decode activation sequence must equal accepted-token index plus one",
1358        );
1359
1360        envelope = chunk_envelope();
1361        envelope.accepted_token_index = None;
1362        assert_sender_and_receiver_invalid(
1363            &envelope,
1364            "decode activation sequence must equal accepted-token index plus one",
1365        );
1366
1367        envelope = chunk_envelope();
1368        envelope.accepted_token_index = Some(u64::MAX);
1369        assert_sender_and_receiver_invalid(
1370            &envelope,
1371            "decode activation sequence must equal accepted-token index plus one",
1372        );
1373    }
1374
1375    #[test]
1376    fn sender_and_receiver_enforce_stage_role_and_direction() {
1377        let mut envelope = prefill_envelope();
1378        envelope.source_stage_id = StageId(1);
1379        assert_sender_and_receiver_invalid(
1380            &envelope,
1381            "first stage must have identity and start layer zero",
1382        );
1383
1384        envelope = chunk_envelope();
1385        envelope.source_stage_id = StageId(0);
1386        envelope.destination_stage_id = StageId(1);
1387        assert_sender_and_receiver_invalid(
1388            &envelope,
1389            "interior stage must have non-zero identity and start layer",
1390        );
1391
1392        envelope = chunk_envelope();
1393        envelope.destination_stage_id = StageId(3);
1394        assert_sender_and_receiver_invalid(
1395            &envelope,
1396            "destination stage must immediately follow source stage",
1397        );
1398
1399        envelope = chunk_envelope();
1400        envelope.source_stage_id = StageId(u32::MAX);
1401        assert_sender_and_receiver_invalid(
1402            &envelope,
1403            "source stage identity cannot advance without overflow",
1404        );
1405
1406        for role in [StageRole::Last, StageRole::Only] {
1407            envelope = chunk_envelope();
1408            envelope.source_boundary.role = role;
1409            assert_sender_and_receiver_invalid(
1410                &envelope,
1411                "last/only stage does not emit a next-stage activation",
1412            );
1413        }
1414
1415        envelope = chunk_envelope();
1416        envelope.source_boundary.end_layer = envelope.source_boundary.start_layer;
1417        assert_sender_and_receiver_invalid(
1418            &envelope,
1419            "stage boundary must be a non-empty half-open interval",
1420        );
1421    }
1422
1423    #[test]
1424    fn sender_and_receiver_enforce_dense_activation_abi() {
1425        let mut envelope = chunk_envelope();
1426        chunk_mut(&mut envelope).tensor.shape = [0, 4, 8];
1427        assert_sender_and_receiver_invalid(
1428            &envelope,
1429            "activation shape [B,Q,H] requires three non-zero dimensions",
1430        );
1431
1432        envelope = chunk_envelope();
1433        chunk_mut(&mut envelope).tensor.byte_length = 127;
1434        assert_sender_and_receiver_invalid(
1435            &envelope,
1436            "activation byte length does not match dense [B,Q,H] dtype",
1437        );
1438
1439        envelope = chunk_envelope();
1440        chunk_mut(&mut envelope).tensor.shape = [u64::MAX, 2, 2];
1441        assert_sender_and_receiver_invalid(
1442            &envelope,
1443            "activation byte length does not match dense [B,Q,H] dtype",
1444        );
1445    }
1446
1447    #[test]
1448    fn sender_and_receiver_enforce_chunk_span_and_integrity() {
1449        let mut envelope = chunk_envelope();
1450        chunk_mut(&mut envelope).coordinate.count = 0;
1451        assert_sender_and_receiver_invalid(
1452            &envelope,
1453            "chunk coordinate requires count > 0 and index < count",
1454        );
1455
1456        envelope = chunk_envelope();
1457        chunk_mut(&mut envelope).coordinate.length = 0;
1458        assert_sender_and_receiver_invalid(&envelope, "chunk length must be non-zero");
1459
1460        envelope = chunk_envelope();
1461        chunk_mut(&mut envelope).coordinate = ChunkCoordinate {
1462            index: 0,
1463            count: 3,
1464            offset: 1,
1465            length: 31,
1466        };
1467        assert_sender_and_receiver_invalid(
1468            &envelope,
1469            "first chunk must begin at logical byte zero",
1470        );
1471
1472        envelope = chunk_envelope();
1473        chunk_mut(&mut envelope).coordinate = ChunkCoordinate {
1474            index: 2,
1475            count: 3,
1476            offset: 64,
1477            length: 63,
1478        };
1479        assert_sender_and_receiver_invalid(
1480            &envelope,
1481            "last chunk must end at the logical activation length",
1482        );
1483
1484        envelope = chunk_envelope();
1485        chunk_mut(&mut envelope).coordinate = ChunkCoordinate {
1486            index: 2,
1487            count: 3,
1488            offset: u64::MAX,
1489            length: 2,
1490        };
1491        assert_sender_and_receiver_invalid(&envelope, "chunk byte span overflows");
1492
1493        envelope = chunk_envelope();
1494        chunk_mut(&mut envelope).coordinate = ChunkCoordinate {
1495            index: 1,
1496            count: 3,
1497            offset: 120,
1498            length: 9,
1499        };
1500        assert_sender_and_receiver_invalid(
1501            &envelope,
1502            "chunk byte span exceeds logical activation length",
1503        );
1504
1505        envelope = chunk_envelope();
1506        chunk_mut(&mut envelope).chunk_digest = ChunkDigest([0; 32]);
1507        assert_sender_and_receiver_invalid(&envelope, "chunk digest");
1508
1509        envelope = chunk_envelope();
1510        chunk_mut(&mut envelope).whole_activation_digest = WholeActivationDigest([0; 32]);
1511        assert_sender_and_receiver_invalid(&envelope, "whole activation digest");
1512    }
1513
1514    #[test]
1515    fn sender_and_receiver_enforce_terminal_and_error_guards() {
1516        let mut envelope = prefill_envelope();
1517        envelope.body = ActivationEnvelopeBody::Terminal(ActivationTerminal {
1518            chunk_count: 0,
1519            whole_activation_digest: WholeActivationDigest([9; 32]),
1520        });
1521        assert_sender_and_receiver_invalid(&envelope, "terminal chunk count must be non-zero");
1522
1523        envelope.body = ActivationEnvelopeBody::Terminal(ActivationTerminal {
1524            chunk_count: 1,
1525            whole_activation_digest: WholeActivationDigest([0; 32]),
1526        });
1527        assert_sender_and_receiver_invalid(&envelope, "whole activation digest");
1528
1529        envelope.body = ActivationEnvelopeBody::Error(ActivationError {
1530            code: ActivationErrorCode::Internal,
1531            message: String::new(),
1532            retryable: false,
1533        });
1534        assert_sender_and_receiver_invalid(
1535            &envelope,
1536            "error message must contain 1..=1024 non-whitespace bytes",
1537        );
1538
1539        let mut oversized = "x".repeat(MAX_ERROR_MESSAGE_BYTES);
1540        oversized.push('x');
1541        envelope.body = ActivationEnvelopeBody::Error(ActivationError {
1542            code: ActivationErrorCode::Internal,
1543            message: oversized,
1544            retryable: false,
1545        });
1546        assert_eq!(
1547            envelope.to_cbor().unwrap_err(),
1548            ActivationEnvelopeError::Invalid(
1549                "error message must contain 1..=1024 non-whitespace bytes"
1550            )
1551        );
1552        assert!(matches!(
1553            ActivationEnvelope::from_cbor(&unchecked_canonical(&envelope)),
1554            Err(ActivationEnvelopeError::Decode(message))
1555                if message.contains("text length 1025 exceeds 1024")
1556        ));
1557    }
1558
1559    #[test]
1560    fn receiver_rejects_noncanonical_duplicate_reordered_missing_and_unknown_fields() {
1561        let canonical = chunk_envelope().to_cbor().unwrap();
1562        assert_eq!(canonical[0], 0xb3);
1563        assert_eq!(canonical[1], 0);
1564        assert_eq!(canonical[2], 1);
1565        assert_eq!(canonical[3], 1);
1566
1567        let mut non_shortest = canonical.clone();
1568        non_shortest.splice(1..2, [0x18, 0x00]);
1569        assert!(matches!(
1570            ActivationEnvelope::from_cbor(&non_shortest),
1571            Err(ActivationEnvelopeError::Decode(message))
1572                if message.contains("shortest-form")
1573        ));
1574
1575        let mut duplicate = canonical.clone();
1576        duplicate[3] = 0;
1577        assert!(matches!(
1578            ActivationEnvelope::from_cbor(&duplicate),
1579            Err(ActivationEnvelopeError::Decode(message))
1580                if message.contains("duplicate")
1581        ));
1582
1583        let mut reordered = canonical.clone();
1584        reordered[1] = 1;
1585        assert!(matches!(
1586            ActivationEnvelope::from_cbor(&reordered),
1587            Err(ActivationEnvelopeError::Decode(message))
1588                if message.contains("reordered")
1589        ));
1590
1591        let mut missing = canonical.clone();
1592        missing[0] = 0xb2;
1593        assert!(matches!(
1594            ActivationEnvelope::from_cbor(&missing),
1595            Err(ActivationEnvelopeError::Decode(message))
1596                if message.contains("expected 19")
1597        ));
1598
1599        let mut unknown = canonical.clone();
1600        unknown[1] = 23;
1601        assert!(matches!(
1602            ActivationEnvelope::from_cbor(&unknown),
1603            Err(ActivationEnvelopeError::Decode(message))
1604                if message.contains("unknown")
1605        ));
1606
1607        let mut indefinite = canonical.clone();
1608        indefinite[0] = 0xbf;
1609        assert!(matches!(
1610            ActivationEnvelope::from_cbor(&indefinite),
1611            Err(ActivationEnvelopeError::Decode(message))
1612                if message.contains("indefinite")
1613        ));
1614    }
1615
1616    #[test]
1617    fn receiver_rejects_unknown_admitted_wire_values_and_trailing_data() {
1618        let canonical = chunk_envelope().to_cbor().unwrap();
1619
1620        let mut unknown_model_algorithm = canonical.clone();
1621        // Top map, key 0, version 1, key 1, model array(2), algorithm.
1622        assert_eq!(&unknown_model_algorithm[..6], &[0xb3, 0, 1, 1, 0x82, 0]);
1623        unknown_model_algorithm[5] = 2;
1624        assert!(matches!(
1625            ActivationEnvelope::from_cbor(&unknown_model_algorithm),
1626            Err(ActivationEnvelopeError::Decode(message))
1627                if message.contains("unknown model OID algorithm")
1628        ));
1629
1630        let tensor_marker = [0x86, 1, 2, 4, 8, 0x18, 0x80, 0];
1631        let tensor_start = unique_subslice(&canonical, &tensor_marker);
1632
1633        let mut wrong_rank = canonical.clone();
1634        wrong_rank[tensor_start] = 0x85;
1635        assert!(matches!(
1636            ActivationEnvelope::from_cbor(&wrong_rank),
1637            Err(ActivationEnvelopeError::Decode(message))
1638                if message.contains("expected 6")
1639        ));
1640
1641        let mut unknown_dtype = canonical.clone();
1642        unknown_dtype[tensor_start + 1] = 3;
1643        assert!(matches!(
1644            ActivationEnvelope::from_cbor(&unknown_dtype),
1645            Err(ActivationEnvelopeError::Decode(message))
1646                if message.contains("unknown activation dtype")
1647        ));
1648
1649        let mut unknown_codec = canonical.clone();
1650        unknown_codec[tensor_start + tensor_marker.len() - 1] = 1;
1651        assert!(matches!(
1652            ActivationEnvelope::from_cbor(&unknown_codec),
1653            Err(ActivationEnvelopeError::Decode(message))
1654                if message.contains("unknown activation codec")
1655        ));
1656
1657        let body_marker = [0x85, 0, 0x86];
1658        let body_start = unique_subslice(&canonical, &body_marker);
1659        let mut unknown_body = canonical.clone();
1660        unknown_body[body_start + 1] = 3;
1661        assert!(matches!(
1662            ActivationEnvelope::from_cbor(&unknown_body),
1663            Err(ActivationEnvelopeError::Decode(message))
1664                if message.contains("unknown or malformed activation body")
1665        ));
1666
1667        let mut trailing = canonical;
1668        trailing.push(0);
1669        assert!(matches!(
1670            ActivationEnvelope::from_cbor(&trailing),
1671            Err(ActivationEnvelopeError::Decode(message))
1672                if message.contains("trailing data")
1673        ));
1674
1675        let oversized = vec![0; MAX_ENCODED_ENVELOPE_BYTES + 1];
1676        assert_eq!(
1677            ActivationEnvelope::from_cbor(&oversized).unwrap_err(),
1678            ActivationEnvelopeError::TooLarge(MAX_ENCODED_ENVELOPE_BYTES + 1)
1679        );
1680    }
1681}