Skip to main content

logit_loom_core/
activation.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Versioned topology, activation-capture, vector, and program contracts.
4
5use std::collections::BTreeSet;
6
7use serde::{Deserialize, Serialize};
8
9use crate::{CoreError, Digest};
10
11/// Maximum transformer layers represented by one topology contract.
12pub const MAX_TEXT_MODEL_LAYERS: u32 = 4_096;
13/// Maximum elements in one reported model row.
14pub const MAX_TEXT_TENSOR_ROW_ELEMENTS: u32 = 1_048_576;
15/// Maximum experts represented by one topology contract.
16pub const MAX_TEXT_MODEL_EXPERTS: u32 = 65_536;
17/// Maximum exact tensor sites selected by one capture or operation.
18pub const MAX_ACTIVATION_SITES: usize = 128;
19/// Maximum inclusive causal ranges selected by one contract.
20pub const MAX_ACTIVATION_POSITION_RANGES: usize = 128;
21/// Maximum causal positions selected by one capture.
22pub const MAX_ACTIVATION_CAPTURE_POSITIONS: u32 = 4_096;
23/// Maximum `f32` elements copied or retained by one activation operation.
24pub const MAX_ACTIVATION_ELEMENTS: u64 = 16_777_216;
25/// Maximum retained activation bytes declared by one capture.
26pub const MAX_ACTIVATION_RETAINED_BYTES: u64 = MAX_ACTIVATION_ELEMENTS * 4;
27/// Maximum sparse vector rows in one bank.
28pub const MAX_ACTIVATION_VECTOR_ROWS: usize = 4_096;
29/// Maximum ordered activation operations in one program.
30pub const MAX_ACTIVATION_OPERATIONS: usize = 256;
31/// Maximum capture-plan observations named by one program.
32pub const MAX_ACTIVATION_OBSERVATIONS: usize = 128;
33/// Maximum input artifacts represented by vector provenance.
34pub const MAX_ACTIVATION_VECTOR_INPUTS: usize = 65_536;
35/// Maximum successful tensor transactions retained in one program receipt.
36pub const MAX_ACTIVATION_INVOCATION_RECEIPTS: usize = 65_536;
37/// Maximum logical rows represented by one tensor transaction.
38pub const MAX_ACTIVATION_TRANSACTION_ROWS: usize = 4_096;
39/// Maximum sequence identifiers attached to one logical tensor row.
40pub const MAX_ACTIVATION_ROW_SEQUENCES: usize = 4_096;
41/// Maximum UTF-8 bytes in a backend-profile tensor name.
42pub const MAX_TEXT_TENSOR_NAME_BYTES: usize = 256;
43
44/// Speculative mechanisms a loaded text topology can report.
45#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum TextSpeculativeMechanismV1 {
48    /// Same-model multi-token prediction heads.
49    Mtp,
50    /// A separately trained EAGLE-3 draft model.
51    Eagle3,
52}
53
54/// Backend-neutral, content-bound model topology.
55#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct TextModelTopologyV1 {
58    /// Exact model artifact identity.
59    pub model: Digest,
60    /// Exact backend and safe-binding build identity.
61    pub backend: Digest,
62    /// Architecture-selector implementation identity.
63    pub architecture_implementation: Digest,
64    /// Number of transformer layers.
65    pub layers: u32,
66    /// Residual-stream row width.
67    pub embedding_width: u32,
68    /// Total `MoE` experts per applicable layer, when reported.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub experts: Option<u32>,
71    /// Experts selected per token, when reported.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub experts_used: Option<u32>,
74    /// Number of same-model NextN/MTP heads.
75    pub nextn_layers: u32,
76    /// Canonically ordered speculative mechanisms available to this topology.
77    #[serde(default)]
78    pub supported_speculation: Vec<TextSpeculativeMechanismV1>,
79}
80
81impl TextModelTopologyV1 {
82    /// Validates topology bounds and returns its stable identity.
83    ///
84    /// # Errors
85    ///
86    /// Returns an error for unusable dimensions, inconsistent expert
87    /// accounting, or a non-canonical mechanism set.
88    pub fn digest(&self) -> Result<Digest, CoreError> {
89        if self.layers == 0 || self.layers > MAX_TEXT_MODEL_LAYERS {
90            return Err(CoreError::invalid(
91                "text model topology",
92                "layer count is outside the supported bound",
93            ));
94        }
95        if self.embedding_width == 0 || self.embedding_width > MAX_TEXT_TENSOR_ROW_ELEMENTS {
96            return Err(CoreError::invalid(
97                "text model topology",
98                "embedding width is outside the supported bound",
99            ));
100        }
101        if let Some(experts) = self.experts
102            && (experts == 0 || experts > MAX_TEXT_MODEL_EXPERTS)
103        {
104            return Err(CoreError::invalid(
105                "text model topology",
106                "expert count is outside the supported bound",
107            ));
108        }
109        match (self.experts, self.experts_used) {
110            (None, Some(_)) => {
111                return Err(CoreError::invalid(
112                    "text model topology",
113                    "experts-used requires a reported expert count",
114                ));
115            }
116            (Some(experts), Some(used)) if used == 0 || used > experts => {
117                return Err(CoreError::invalid(
118                    "text model topology",
119                    "experts-used must be within the reported expert count",
120                ));
121            }
122            _ => {}
123        }
124        if self.nextn_layers > self.layers {
125            return Err(CoreError::invalid(
126                "text model topology",
127                "NextN layer count exceeds transformer layers",
128            ));
129        }
130        validate_canonical_unique(
131            &self.supported_speculation,
132            "text model topology",
133            "speculative mechanisms must be unique and canonically ordered",
134        )?;
135        let has_mtp = self
136            .supported_speculation
137            .contains(&TextSpeculativeMechanismV1::Mtp);
138        if has_mtp != (self.nextn_layers > 0) {
139            return Err(CoreError::invalid(
140                "text model topology",
141                "MTP support and NextN layer count disagree",
142            ));
143        }
144        Digest::of_serializable("text-model-topology-v1", self)
145    }
146}
147
148/// Tensor element representation expected at a selected graph site.
149#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum TextTensorElementTypeV1 {
152    /// Finite IEEE-754 single-precision values.
153    F32,
154    /// Signed 32-bit integer values.
155    I32,
156}
157
158/// Stable family shared by compatible activation vector rows and tensor sites.
159#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum TextTensorSiteFamilyV1 {
162    /// Transformer residual layer output.
163    LayerOutput,
164    /// `MoE` router logits before probability normalization.
165    RouterLogits,
166    /// `MoE` router probabilities.
167    RouterProbabilities,
168    /// Integer selected-expert indices.
169    SelectedExperts,
170    /// A compatibility-profile-defined exact graph node.
171    Named,
172}
173
174/// Exact graph tensor selected for capture or mutation.
175#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
176#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
177pub enum TextTensorSiteV1 {
178    /// Built-in transformer residual layer output.
179    LayerOutput {
180        /// Zero-based transformer layer.
181        layer: u32,
182    },
183    /// Architecture-profile-bound `MoE` router logits.
184    RouterLogits {
185        /// Zero-based transformer layer.
186        layer: u32,
187        /// Exact graph selector implementation.
188        selector: Digest,
189    },
190    /// Architecture-profile-bound `MoE` router probabilities.
191    RouterProbabilities {
192        /// Zero-based transformer layer.
193        layer: u32,
194        /// Exact graph selector implementation.
195        selector: Digest,
196    },
197    /// Architecture-profile-bound selected-expert indices.
198    SelectedExperts {
199        /// Zero-based transformer layer.
200        layer: u32,
201        /// Exact graph selector implementation.
202        selector: Digest,
203    },
204    /// Exact graph node defined by a compatibility profile.
205    Named {
206        /// Exact UTF-8 graph-node name.
207        name: String,
208        /// Exact graph selector implementation.
209        selector: Digest,
210        /// Required element representation.
211        element_type: TextTensorElementTypeV1,
212        /// Required elements in each selected causal row.
213        row_elements: u32,
214    },
215}
216
217impl TextTensorSiteV1 {
218    /// Returns the stable site family.
219    pub const fn family(&self) -> TextTensorSiteFamilyV1 {
220        match self {
221            Self::LayerOutput { .. } => TextTensorSiteFamilyV1::LayerOutput,
222            Self::RouterLogits { .. } => TextTensorSiteFamilyV1::RouterLogits,
223            Self::RouterProbabilities { .. } => TextTensorSiteFamilyV1::RouterProbabilities,
224            Self::SelectedExperts { .. } => TextTensorSiteFamilyV1::SelectedExperts,
225            Self::Named { .. } => TextTensorSiteFamilyV1::Named,
226        }
227    }
228
229    /// Returns the selected layer for built-in layer-scoped sites.
230    pub const fn layer(&self) -> Option<u32> {
231        match self {
232            Self::LayerOutput { layer }
233            | Self::RouterLogits { layer, .. }
234            | Self::RouterProbabilities { layer, .. }
235            | Self::SelectedExperts { layer, .. } => Some(*layer),
236            Self::Named { .. } => None,
237        }
238    }
239
240    /// Returns the required element representation.
241    pub const fn element_type(&self) -> TextTensorElementTypeV1 {
242        match self {
243            Self::SelectedExperts { .. } => TextTensorElementTypeV1::I32,
244            Self::LayerOutput { .. }
245            | Self::RouterLogits { .. }
246            | Self::RouterProbabilities { .. } => TextTensorElementTypeV1::F32,
247            Self::Named { element_type, .. } => *element_type,
248        }
249    }
250
251    /// Returns the expected row width for the supplied topology.
252    ///
253    /// # Errors
254    ///
255    /// Returns an error when the site is incompatible with the topology or
256    /// depends on expert metadata the topology does not report.
257    pub fn row_elements(&self, topology: &TextModelTopologyV1) -> Result<u32, CoreError> {
258        self.validate_for(topology)?;
259        match self {
260            Self::LayerOutput { .. } => Ok(topology.embedding_width),
261            Self::RouterLogits { .. } | Self::RouterProbabilities { .. } => {
262                topology.experts.ok_or_else(|| {
263                    CoreError::invalid("text tensor site", "topology does not report experts")
264                })
265            }
266            Self::SelectedExperts { .. } => topology.experts_used.ok_or_else(|| {
267                CoreError::invalid(
268                    "text tensor site",
269                    "topology does not report selected experts",
270                )
271            }),
272            Self::Named { row_elements, .. } => Ok(*row_elements),
273        }
274    }
275
276    /// Validates the site against a loaded topology.
277    ///
278    /// # Errors
279    ///
280    /// Returns an error for an out-of-range layer, missing expert topology, an
281    /// invalid named-node contract, or malformed topology.
282    pub fn validate_for(&self, topology: &TextModelTopologyV1) -> Result<(), CoreError> {
283        topology.digest()?;
284        if let Some(layer) = self.layer()
285            && layer >= topology.layers
286        {
287            return Err(CoreError::invalid(
288                "text tensor site",
289                "selected layer is outside the topology",
290            ));
291        }
292        match self {
293            Self::RouterLogits { .. } | Self::RouterProbabilities { .. } => {
294                if topology.experts.is_none() {
295                    return Err(CoreError::invalid(
296                        "text tensor site",
297                        "router site requires reported expert topology",
298                    ));
299                }
300            }
301            Self::SelectedExperts { .. } => {
302                if topology.experts_used.is_none() {
303                    return Err(CoreError::invalid(
304                        "text tensor site",
305                        "selected-expert site requires experts-used topology",
306                    ));
307                }
308            }
309            Self::Named {
310                name, row_elements, ..
311            } => {
312                if name.is_empty()
313                    || name.len() > MAX_TEXT_TENSOR_NAME_BYTES
314                    || name.as_bytes().contains(&0)
315                    || *row_elements == 0
316                    || *row_elements > MAX_TEXT_TENSOR_ROW_ELEMENTS
317                {
318                    return Err(CoreError::invalid(
319                        "text tensor site",
320                        "named site requires a bounded non-NUL name and row width",
321                    ));
322                }
323            }
324            Self::LayerOutput { .. } => {}
325        }
326        Ok(())
327    }
328
329    /// Returns a topology-bound site identity.
330    ///
331    /// # Errors
332    ///
333    /// Returns a validation or serialization error.
334    pub fn digest_for(&self, topology: &TextModelTopologyV1) -> Result<Digest, CoreError> {
335        self.validate_for(topology)?;
336        Digest::of_serializable("text-tensor-site-v1", &(topology.digest()?, self))
337    }
338}
339
340/// Inclusive causal-position interval.
341#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
342#[serde(deny_unknown_fields)]
343pub struct CausalPositionRangeV1 {
344    /// Inclusive first causal position.
345    pub start: u64,
346    /// Inclusive final causal position.
347    pub end: u64,
348}
349
350impl CausalPositionRangeV1 {
351    /// Returns whether the range is reversed and therefore selects no
352    /// positions.
353    pub const fn is_empty(self) -> bool {
354        self.start > self.end
355    }
356
357    /// Returns the number of positions in this inclusive range.
358    ///
359    /// # Errors
360    ///
361    /// Returns an error for a reversed or overflowing range.
362    pub fn len(self) -> Result<u64, CoreError> {
363        self.end
364            .checked_sub(self.start)
365            .and_then(|distance| distance.checked_add(1))
366            .ok_or_else(|| {
367                CoreError::invalid("causal position range", "range is reversed or overflowed")
368            })
369    }
370
371    /// Returns whether the inclusive range contains a position.
372    pub const fn contains(self, position: u64) -> bool {
373        position >= self.start && position <= self.end
374    }
375}
376
377/// Causal positions retained by one activation capture.
378#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(tag = "kind", content = "ranges", rename_all = "snake_case")]
380pub enum ActivationCapturePositionsV1 {
381    /// Capture only the last token of a non-empty prefill.
382    LastPrefillToken,
383    /// Capture canonically ordered, disjoint inclusive causal ranges.
384    InclusiveRanges(Vec<CausalPositionRangeV1>),
385}
386
387impl ActivationCapturePositionsV1 {
388    /// Returns the exact explicit position count, or one for last-prefill mode.
389    ///
390    /// # Errors
391    ///
392    /// Returns an error for empty, unordered, overlapping, or over-bound
393    /// ranges.
394    pub fn position_count(&self) -> Result<u32, CoreError> {
395        match self {
396            Self::LastPrefillToken => Ok(1),
397            Self::InclusiveRanges(ranges) => {
398                validate_ranges(ranges, "activation capture positions")?;
399                let count = ranges.iter().try_fold(0_u64, |total, range| {
400                    total.checked_add(range.len()?).ok_or_else(|| {
401                        CoreError::invalid(
402                            "activation capture positions",
403                            "position count overflowed",
404                        )
405                    })
406                })?;
407                let count = u32::try_from(count).map_err(|_| {
408                    CoreError::invalid("activation capture positions", "position count exceeds u32")
409                })?;
410                if count > MAX_ACTIVATION_CAPTURE_POSITIONS {
411                    return Err(CoreError::invalid(
412                        "activation capture positions",
413                        "position count exceeds the supported bound",
414                    ));
415                }
416                Ok(count)
417            }
418        }
419    }
420
421    /// Returns whether an explicit range selection contains a position.
422    ///
423    /// Last-prefill selection is resolved by the adapter and returns `false`.
424    pub fn contains_explicit(&self, position: u64) -> bool {
425        match self {
426            Self::LastPrefillToken => false,
427            Self::InclusiveRanges(ranges) => ranges.iter().any(|range| range.contains(position)),
428        }
429    }
430}
431
432/// Data retained for each selected tensor row.
433#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(rename_all = "snake_case")]
435pub enum ActivationCaptureRetentionV1 {
436    /// Retain only exact tensor-byte identity and element count.
437    Digest,
438    /// Retain identity plus deterministic scalar statistics.
439    Statistics,
440    /// Retain the complete bounded typed row.
441    Snapshot,
442}
443
444/// Bounded activation-capture request.
445#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(deny_unknown_fields)]
447pub struct ActivationCapturePlanV1 {
448    /// Required model-topology identity.
449    pub topology: Digest,
450    /// Canonically ordered exact tensor sites.
451    pub sites: Vec<TextTensorSiteV1>,
452    /// Causal positions to retain.
453    pub positions: ActivationCapturePositionsV1,
454    /// Per-row retention mode.
455    pub retention: ActivationCaptureRetentionV1,
456    /// Inclusive total element bound across all retained rows.
457    pub maximum_elements: u64,
458    /// Inclusive retained-byte bound across all retained records.
459    pub maximum_retained_bytes: u64,
460}
461
462impl ActivationCapturePlanV1 {
463    /// Validates this request against a topology and returns its identity.
464    ///
465    /// # Errors
466    ///
467    /// Returns an error for topology mismatch, empty or non-canonical sites,
468    /// malformed positions, or inconsistent allocation bounds.
469    pub fn digest_for(&self, topology: &TextModelTopologyV1) -> Result<Digest, CoreError> {
470        let topology_identity = topology.digest()?;
471        if self.topology != topology_identity {
472            return Err(CoreError::invalid(
473                "activation capture plan",
474                "topology identity does not match",
475            ));
476        }
477        if self.sites.is_empty() || self.sites.len() > MAX_ACTIVATION_SITES {
478            return Err(CoreError::invalid(
479                "activation capture plan",
480                "site count is outside the supported bound",
481            ));
482        }
483        validate_canonical_unique(
484            &self.sites,
485            "activation capture plan",
486            "sites must be unique and canonically ordered",
487        )?;
488        let positions = u64::from(self.positions.position_count()?);
489        let elements_per_position = self.sites.iter().try_fold(0_u64, |total, site| {
490            total
491                .checked_add(u64::from(site.row_elements(topology)?))
492                .ok_or_else(|| {
493                    CoreError::invalid("activation capture plan", "site width sum overflowed")
494                })
495        })?;
496        let required_elements = positions
497            .checked_mul(elements_per_position)
498            .ok_or_else(|| {
499                CoreError::invalid("activation capture plan", "element bound overflowed")
500            })?;
501        if self.maximum_elements == 0
502            || self.maximum_elements > MAX_ACTIVATION_ELEMENTS
503            || self.maximum_elements < required_elements
504        {
505            return Err(CoreError::invalid(
506                "activation capture plan",
507                "element bound is zero, excessive, or smaller than selected rows",
508            ));
509        }
510        let minimum_retained_bytes = match self.retention {
511            ActivationCaptureRetentionV1::Digest => 0,
512            ActivationCaptureRetentionV1::Statistics => u64::try_from(self.sites.len())
513                .ok()
514                .and_then(|sites| sites.checked_mul(positions))
515                .and_then(|rows| rows.checked_mul(4 * 4))
516                .ok_or_else(|| {
517                    CoreError::invalid(
518                        "activation capture plan",
519                        "statistics byte bound overflowed",
520                    )
521                })?,
522            ActivationCaptureRetentionV1::Snapshot => {
523                required_elements.checked_mul(4).ok_or_else(|| {
524                    CoreError::invalid("activation capture plan", "snapshot byte bound overflowed")
525                })?
526            }
527        };
528        if self.maximum_retained_bytes > MAX_ACTIVATION_RETAINED_BYTES
529            || self.maximum_retained_bytes < minimum_retained_bytes
530        {
531            return Err(CoreError::invalid(
532                "activation capture plan",
533                "retained-byte bound is excessive or smaller than selected retention",
534            ));
535        }
536        Digest::of_serializable("activation-capture-plan-v1", self)
537    }
538}
539
540/// Causal status of telemetry created during target or draft evaluation.
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum ActivationTelemetryDispositionV1 {
544    /// Target verification has not yet resolved the proposal.
545    Provisional,
546    /// The row belongs to target-admitted causal state.
547    Admitted,
548    /// The row belongs only to a rejected proposal.
549    Rejected,
550}
551
552/// Deterministic scalar statistics represented by exact `f32` bits.
553#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(deny_unknown_fields)]
555pub struct ActivationStatisticsV1 {
556    /// Minimum value bits.
557    pub minimum_bits: u32,
558    /// Maximum value bits.
559    pub maximum_bits: u32,
560    /// Arithmetic mean bits.
561    pub mean_bits: u32,
562    /// Euclidean norm bits.
563    pub l2_norm_bits: u32,
564}
565
566impl ActivationStatisticsV1 {
567    /// Computes statistics in stable row order using `f64` accumulators.
568    ///
569    /// # Errors
570    ///
571    /// Returns an error for an empty or non-finite row.
572    #[allow(
573        clippy::cast_possible_truncation,
574        clippy::cast_precision_loss,
575        reason = "bounded f32 rows are accumulated in f64 and intentionally represented as f32 bits"
576    )]
577    pub fn from_f32(values: &[f32]) -> Result<Self, CoreError> {
578        validate_finite_row(values, "activation statistics")?;
579        let mut minimum = values[0];
580        let mut maximum = values[0];
581        let mut sum = 0.0_f64;
582        let mut squared = 0.0_f64;
583        for value in values {
584            minimum = minimum.min(*value);
585            maximum = maximum.max(*value);
586            let wide = f64::from(*value);
587            sum += wide;
588            squared += wide * wide;
589        }
590        let length = values.len() as f64;
591        let mean = (sum / length) as f32;
592        let norm = squared.sqrt() as f32;
593        if !mean.is_finite() || !norm.is_finite() {
594            return Err(CoreError::invalid(
595                "activation statistics",
596                "statistics overflowed finite f32",
597            ));
598        }
599        Ok(Self {
600            minimum_bits: minimum.to_bits(),
601            maximum_bits: maximum.to_bits(),
602            mean_bits: mean.to_bits(),
603            l2_norm_bits: norm.to_bits(),
604        })
605    }
606
607    fn validate(self) -> Result<(), CoreError> {
608        let minimum = f32::from_bits(self.minimum_bits);
609        let maximum = f32::from_bits(self.maximum_bits);
610        let mean = f32::from_bits(self.mean_bits);
611        let norm = f32::from_bits(self.l2_norm_bits);
612        if !minimum.is_finite()
613            || !maximum.is_finite()
614            || !mean.is_finite()
615            || !norm.is_finite()
616            || minimum > maximum
617            || mean < minimum
618            || mean > maximum
619            || norm < 0.0
620        {
621            return Err(CoreError::invalid(
622                "activation statistics",
623                "statistics must be finite and internally consistent",
624            ));
625        }
626        Ok(())
627    }
628}
629
630/// Retained data for one captured tensor row.
631#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
632#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
633pub enum ActivationCapturedDataV1 {
634    /// Exact byte identity only.
635    Digest {
636        /// Canonical typed-row byte identity.
637        data: Digest,
638        /// Number of elements in the row.
639        elements: u32,
640    },
641    /// Exact byte identity and deterministic scalar statistics.
642    Statistics {
643        /// Canonical typed-row byte identity.
644        data: Digest,
645        /// Number of elements in the row.
646        elements: u32,
647        /// Stable scalar statistics.
648        statistics: ActivationStatisticsV1,
649    },
650    /// Complete finite `f32` row.
651    F32Snapshot {
652        /// Canonical typed-row byte identity.
653        data: Digest,
654        /// Exact finite row values.
655        values: Vec<f32>,
656    },
657    /// Complete signed-integer row.
658    I32Snapshot {
659        /// Canonical typed-row byte identity.
660        data: Digest,
661        /// Exact row values.
662        values: Vec<i32>,
663    },
664}
665
666impl ActivationCapturedDataV1 {
667    /// Constructs retained data from one finite `f32` row.
668    ///
669    /// # Errors
670    ///
671    /// Returns an error for an empty, non-finite, or over-bound row.
672    pub fn from_f32(
673        values: &[f32],
674        retention: ActivationCaptureRetentionV1,
675    ) -> Result<Self, CoreError> {
676        validate_finite_row(values, "activation capture row")?;
677        let elements = bounded_element_count(values.len(), "activation capture row")?;
678        let data = digest_f32_row("activation-captured-f32-v1", values);
679        Ok(match retention {
680            ActivationCaptureRetentionV1::Digest => Self::Digest { data, elements },
681            ActivationCaptureRetentionV1::Statistics => Self::Statistics {
682                data,
683                elements,
684                statistics: ActivationStatisticsV1::from_f32(values)?,
685            },
686            ActivationCaptureRetentionV1::Snapshot => Self::F32Snapshot {
687                data,
688                values: values.to_vec(),
689            },
690        })
691    }
692
693    /// Constructs retained data from one signed-integer row.
694    ///
695    /// Statistics retention is not defined for selected-expert indices.
696    ///
697    /// # Errors
698    ///
699    /// Returns an error for an empty or over-bound row, or for statistics
700    /// retention.
701    pub fn from_i32(
702        values: &[i32],
703        retention: ActivationCaptureRetentionV1,
704    ) -> Result<Self, CoreError> {
705        let elements = bounded_element_count(values.len(), "activation capture row")?;
706        let data = digest_i32_row("activation-captured-i32-v1", values);
707        match retention {
708            ActivationCaptureRetentionV1::Digest => Ok(Self::Digest { data, elements }),
709            ActivationCaptureRetentionV1::Snapshot => Ok(Self::I32Snapshot {
710                data,
711                values: values.to_vec(),
712            }),
713            ActivationCaptureRetentionV1::Statistics => Err(CoreError::invalid(
714                "activation capture row",
715                "statistics retention requires f32 elements",
716            )),
717        }
718    }
719
720    /// Returns the exact row identity.
721    pub const fn data_identity(&self) -> &Digest {
722        match self {
723            Self::Digest { data, .. }
724            | Self::Statistics { data, .. }
725            | Self::F32Snapshot { data, .. }
726            | Self::I32Snapshot { data, .. } => data,
727        }
728    }
729
730    /// Returns the retained element count.
731    pub fn elements(&self) -> u32 {
732        match self {
733            Self::Digest { elements, .. } | Self::Statistics { elements, .. } => *elements,
734            Self::F32Snapshot { values, .. } => u32::try_from(values.len()).unwrap_or(u32::MAX),
735            Self::I32Snapshot { values, .. } => u32::try_from(values.len()).unwrap_or(u32::MAX),
736        }
737    }
738
739    fn validate(
740        &self,
741        element_type: TextTensorElementTypeV1,
742        retention: ActivationCaptureRetentionV1,
743        expected_elements: u32,
744    ) -> Result<u64, CoreError> {
745        let retained_bytes = match (self, element_type, retention) {
746            (Self::Digest { data, elements }, _, ActivationCaptureRetentionV1::Digest)
747                if *elements == expected_elements =>
748            {
749                let _ = data;
750                0
751            }
752            (
753                Self::Statistics {
754                    data,
755                    elements,
756                    statistics,
757                },
758                TextTensorElementTypeV1::F32,
759                ActivationCaptureRetentionV1::Statistics,
760            ) if *elements == expected_elements => {
761                let _ = data;
762                statistics.validate()?;
763                4 * 4
764            }
765            (
766                Self::F32Snapshot { data, values },
767                TextTensorElementTypeV1::F32,
768                ActivationCaptureRetentionV1::Snapshot,
769            ) if self.elements() == expected_elements => {
770                validate_finite_row(values, "activation capture record")?;
771                if *data != digest_f32_row("activation-captured-f32-v1", values) {
772                    return Err(CoreError::invalid(
773                        "activation capture record",
774                        "f32 snapshot identity does not match its values",
775                    ));
776                }
777                u64::from(expected_elements) * 4
778            }
779            (
780                Self::I32Snapshot { data, values },
781                TextTensorElementTypeV1::I32,
782                ActivationCaptureRetentionV1::Snapshot,
783            ) if self.elements() == expected_elements => {
784                if *data != digest_i32_row("activation-captured-i32-v1", values) {
785                    return Err(CoreError::invalid(
786                        "activation capture record",
787                        "i32 snapshot identity does not match its values",
788                    ));
789                }
790                u64::from(expected_elements) * 4
791            }
792            _ => {
793                return Err(CoreError::invalid(
794                    "activation capture record",
795                    "retained data does not match site type, retention, or row width",
796                ));
797            }
798        };
799        Ok(retained_bytes)
800    }
801}
802
803/// One topology-bound captured tensor row.
804#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
805#[serde(deny_unknown_fields)]
806pub struct ActivationCaptureRecordV1 {
807    /// Exact capture-plan identity.
808    pub plan: Digest,
809    /// Exact selected site.
810    pub site: TextTensorSiteV1,
811    /// Causal position represented by this row.
812    pub position: u64,
813    /// Causal status of the row.
814    pub disposition: ActivationTelemetryDispositionV1,
815    /// Retained typed data.
816    pub retained: ActivationCapturedDataV1,
817}
818
819impl ActivationCaptureRecordV1 {
820    /// Validates this row against a capture plan and topology.
821    ///
822    /// # Errors
823    ///
824    /// Returns an error for incompatible lineage, position, shape, type, or
825    /// retained data.
826    pub fn digest_for(
827        &self,
828        plan: &ActivationCapturePlanV1,
829        topology: &TextModelTopologyV1,
830    ) -> Result<Digest, CoreError> {
831        if self.plan != plan.digest_for(topology)? {
832            return Err(CoreError::invalid(
833                "activation capture record",
834                "capture-plan identity does not match",
835            ));
836        }
837        if !plan.sites.contains(&self.site) {
838            return Err(CoreError::invalid(
839                "activation capture record",
840                "site was not selected by the capture plan",
841            ));
842        }
843        if matches!(
844            plan.positions,
845            ActivationCapturePositionsV1::InclusiveRanges(_)
846        ) && !plan.positions.contains_explicit(self.position)
847        {
848            return Err(CoreError::invalid(
849                "activation capture record",
850                "position was not selected by the capture plan",
851            ));
852        }
853        let expected = self.site.row_elements(topology)?;
854        self.retained
855            .validate(self.site.element_type(), plan.retention, expected)?;
856        Digest::of_serializable("activation-capture-record-v1", self)
857    }
858}
859
860/// Aggregate evidence for one completed activation capture.
861#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
862#[serde(deny_unknown_fields)]
863pub struct ActivationCaptureReceiptV1 {
864    /// Exact capture-plan identity.
865    pub plan: Digest,
866    /// Canonically execution-ordered record identities.
867    pub records: Vec<Digest>,
868    /// Total selected elements.
869    pub elements: u64,
870    /// Total retained bytes, excluding digest/contract overhead.
871    pub retained_bytes: u64,
872}
873
874impl ActivationCaptureReceiptV1 {
875    /// Validates aggregate bounds and returns the receipt identity.
876    ///
877    /// # Errors
878    ///
879    /// Returns an error for empty evidence or plan-bound overrun.
880    pub fn digest_for(&self, plan: &ActivationCapturePlanV1) -> Result<Digest, CoreError> {
881        if self.plan != Digest::of_serializable("activation-capture-plan-v1", plan)?
882            || self.records.is_empty()
883            || self.elements == 0
884            || self.elements > plan.maximum_elements
885            || self.retained_bytes > plan.maximum_retained_bytes
886        {
887            return Err(CoreError::invalid(
888                "activation capture receipt",
889                "receipt is empty or exceeds capture bounds",
890            ));
891        }
892        Digest::of_serializable("activation-capture-receipt-v1", self)
893    }
894}
895
896/// Per-row vector normalization contract.
897#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
898#[serde(rename_all = "snake_case")]
899pub enum ActivationVectorNormalizationV1 {
900    /// Preserve accumulator output without normalization.
901    None,
902    /// Require every sparse row to have unit Euclidean norm.
903    UnitL2,
904}
905
906/// Content-free vector construction performed by an accumulator.
907#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
908#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
909pub enum ActivationVectorOperationV1 {
910    /// Arithmetic mean of one caller-ordered group.
911    Mean {
912        /// Number of input samples.
913        count: u32,
914    },
915    /// Left group mean minus right group mean.
916    DifferenceOfMeans {
917        /// Number of left-group samples.
918        left_count: u32,
919        /// Number of right-group samples.
920        right_count: u32,
921    },
922}
923
924/// Mechanical provenance for vector construction.
925#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
926#[serde(deny_unknown_fields)]
927pub struct ActivationVectorProvenanceV1 {
928    /// Exact accumulator implementation.
929    pub accumulator: Digest,
930    /// Construction operation and group counts.
931    pub operation: ActivationVectorOperationV1,
932    /// Caller-ordered input row or sample identities.
933    pub ordered_inputs: Vec<Digest>,
934}
935
936impl ActivationVectorProvenanceV1 {
937    /// Validates count accounting and input bounds.
938    ///
939    /// # Errors
940    ///
941    /// Returns an error for empty, excessive, or inconsistent input lineage.
942    pub fn validate(&self) -> Result<(), CoreError> {
943        if self.ordered_inputs.is_empty()
944            || self.ordered_inputs.len() > MAX_ACTIVATION_VECTOR_INPUTS
945        {
946            return Err(CoreError::invalid(
947                "activation vector provenance",
948                "input count is outside the supported bound",
949            ));
950        }
951        let expected = match self.operation {
952            ActivationVectorOperationV1::Mean { count } => {
953                if count == 0 {
954                    return Err(CoreError::invalid(
955                        "activation vector provenance",
956                        "mean count must be nonzero",
957                    ));
958                }
959                u64::from(count)
960            }
961            ActivationVectorOperationV1::DifferenceOfMeans {
962                left_count,
963                right_count,
964            } => {
965                if left_count == 0 || right_count == 0 {
966                    return Err(CoreError::invalid(
967                        "activation vector provenance",
968                        "both difference groups must be nonempty",
969                    ));
970                }
971                u64::from(left_count) + u64::from(right_count)
972            }
973        };
974        if expected != u64::try_from(self.ordered_inputs.len()).unwrap_or(u64::MAX) {
975            return Err(CoreError::invalid(
976                "activation vector provenance",
977                "group counts do not match ordered input identities",
978            ));
979        }
980        Ok(())
981    }
982}
983
984/// One canonical sparse vector row.
985#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
986#[serde(deny_unknown_fields)]
987pub struct ActivationVectorRowV1 {
988    /// Zero-based model layer.
989    pub layer: u32,
990    /// Exact finite row values.
991    pub values: Vec<f32>,
992}
993
994/// Topology-bound sparse activation vectors.
995#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
996#[serde(deny_unknown_fields)]
997pub struct ActivationVectorBankV1 {
998    /// Required model-topology identity.
999    pub topology: Digest,
1000    /// Compatible mutable site family.
1001    pub site_family: TextTensorSiteFamilyV1,
1002    /// Elements in every sparse row.
1003    pub row_elements: u32,
1004    /// Required per-row normalization.
1005    pub normalization: ActivationVectorNormalizationV1,
1006    /// Canonically layer-ordered sparse rows.
1007    pub rows: Vec<ActivationVectorRowV1>,
1008    /// Exact canonical layer and little-endian `f32` byte identity.
1009    pub data: Digest,
1010    /// Content-free construction lineage.
1011    pub provenance: ActivationVectorProvenanceV1,
1012}
1013
1014impl ActivationVectorBankV1 {
1015    /// Constructs a bank and binds its exact sparse `f32` bytes.
1016    ///
1017    /// # Errors
1018    ///
1019    /// Returns an error for malformed topology, unsupported site family,
1020    /// non-canonical rows, invalid values, normalization, or bounds.
1021    pub fn new(
1022        topology: &TextModelTopologyV1,
1023        site_family: TextTensorSiteFamilyV1,
1024        row_elements: u32,
1025        normalization: ActivationVectorNormalizationV1,
1026        rows: Vec<ActivationVectorRowV1>,
1027        provenance: ActivationVectorProvenanceV1,
1028    ) -> Result<Self, CoreError> {
1029        let mut bank = Self {
1030            topology: topology.digest()?,
1031            site_family,
1032            row_elements,
1033            normalization,
1034            rows,
1035            data: Digest::of_bytes("activation-vector-bank-placeholder-v1", b""),
1036            provenance,
1037        };
1038        bank.data = bank.canonical_data_identity()?;
1039        bank.digest_for(topology)?;
1040        Ok(bank)
1041    }
1042
1043    /// Validates this bank against a topology and returns its identity.
1044    ///
1045    /// # Errors
1046    ///
1047    /// Returns an error for topology mismatch, unsupported family, malformed
1048    /// sparse rows, non-finite values, incorrect normalization, or byte
1049    /// identity mismatch.
1050    pub fn digest_for(&self, topology: &TextModelTopologyV1) -> Result<Digest, CoreError> {
1051        if self.topology != topology.digest()? {
1052            return Err(CoreError::invalid(
1053                "activation vector bank",
1054                "topology identity does not match",
1055            ));
1056        }
1057        if !matches!(
1058            self.site_family,
1059            TextTensorSiteFamilyV1::LayerOutput | TextTensorSiteFamilyV1::RouterLogits
1060        ) {
1061            return Err(CoreError::invalid(
1062                "activation vector bank",
1063                "only residual outputs and router logits are mutable site families",
1064            ));
1065        }
1066        let expected_width = match self.site_family {
1067            TextTensorSiteFamilyV1::LayerOutput => topology.embedding_width,
1068            TextTensorSiteFamilyV1::RouterLogits => topology.experts.ok_or_else(|| {
1069                CoreError::invalid(
1070                    "activation vector bank",
1071                    "router vectors require reported expert topology",
1072                )
1073            })?,
1074            _ => unreachable!("family checked above"),
1075        };
1076        if self.row_elements == 0
1077            || self.row_elements != expected_width
1078            || self.rows.is_empty()
1079            || self.rows.len() > MAX_ACTIVATION_VECTOR_ROWS
1080        {
1081            return Err(CoreError::invalid(
1082                "activation vector bank",
1083                "row width or sparse row count is incompatible with topology",
1084            ));
1085        }
1086        self.provenance.validate()?;
1087        let mut prior_layer = None;
1088        let mut total_elements = 0_u64;
1089        for row in &self.rows {
1090            if row.layer >= topology.layers
1091                || prior_layer.is_some_and(|prior| row.layer <= prior)
1092                || row.values.len() != usize::try_from(self.row_elements).unwrap_or(usize::MAX)
1093            {
1094                return Err(CoreError::invalid(
1095                    "activation vector bank",
1096                    "rows must be width-matched and strictly layer-ordered",
1097                ));
1098            }
1099            validate_finite_row(&row.values, "activation vector bank")?;
1100            if self.normalization == ActivationVectorNormalizationV1::UnitL2 {
1101                validate_unit_row(&row.values)?;
1102            }
1103            prior_layer = Some(row.layer);
1104            total_elements = total_elements
1105                .checked_add(u64::from(self.row_elements))
1106                .ok_or_else(|| {
1107                    CoreError::invalid("activation vector bank", "element count overflowed")
1108                })?;
1109        }
1110        if total_elements > MAX_ACTIVATION_ELEMENTS {
1111            return Err(CoreError::invalid(
1112                "activation vector bank",
1113                "vector elements exceed the supported bound",
1114            ));
1115        }
1116        if self.data != self.canonical_data_identity()? {
1117            return Err(CoreError::invalid(
1118                "activation vector bank",
1119                "data identity does not match canonical sparse row bytes",
1120            ));
1121        }
1122        Digest::of_serializable("activation-vector-bank-v1", self)
1123    }
1124
1125    /// Returns one sparse row by exact layer.
1126    pub fn row(&self, layer: u32) -> Option<&[f32]> {
1127        self.rows
1128            .binary_search_by_key(&layer, |row| row.layer)
1129            .ok()
1130            .map(|index| self.rows[index].values.as_slice())
1131    }
1132
1133    fn canonical_data_identity(&self) -> Result<Digest, CoreError> {
1134        let row_count = u32::try_from(self.rows.len())
1135            .map_err(|_| CoreError::invalid("activation vector bank", "row count exceeds u32"))?;
1136        let capacity = self
1137            .rows
1138            .len()
1139            .checked_mul(
1140                usize::try_from(self.row_elements)
1141                    .unwrap_or(usize::MAX)
1142                    .saturating_mul(4)
1143                    .saturating_add(4),
1144            )
1145            .and_then(|bytes| bytes.checked_add(8))
1146            .ok_or_else(|| {
1147                CoreError::invalid("activation vector bank", "canonical byte size overflowed")
1148            })?;
1149        let mut bytes = Vec::with_capacity(capacity);
1150        bytes.extend_from_slice(&self.row_elements.to_le_bytes());
1151        bytes.extend_from_slice(&row_count.to_le_bytes());
1152        for row in &self.rows {
1153            bytes.extend_from_slice(&row.layer.to_le_bytes());
1154            for value in &row.values {
1155                bytes.extend_from_slice(&value.to_bits().to_le_bytes());
1156            }
1157        }
1158        Ok(Digest::of_bytes("activation-vector-f32-le-v1", &bytes))
1159    }
1160}
1161
1162/// Decode phase at which one activation operation executes.
1163#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1164#[serde(rename_all = "snake_case")]
1165pub enum ActivationPhaseV1 {
1166    /// Prompt admission in the selected target or draft context.
1167    Prefill,
1168    /// Ordinary target generation.
1169    Generation,
1170    /// Target verification of speculative proposals.
1171    Verification,
1172    /// Draft-model proposal evaluation.
1173    Draft,
1174}
1175
1176/// Causal positions selected by one activation operation.
1177#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1178#[serde(tag = "kind", content = "ranges", rename_all = "snake_case")]
1179pub enum ActivationPositionScopeV1 {
1180    /// Every position evaluated in the declared phase.
1181    All,
1182    /// Canonically ordered, disjoint inclusive causal ranges.
1183    InclusiveRanges(Vec<CausalPositionRangeV1>),
1184}
1185
1186impl ActivationPositionScopeV1 {
1187    /// Validates range ordering and bounds.
1188    ///
1189    /// # Errors
1190    ///
1191    /// Returns an error for an empty, reversed, overlapping, or excessive
1192    /// explicit range set.
1193    pub fn validate(&self) -> Result<(), CoreError> {
1194        if let Self::InclusiveRanges(ranges) = self {
1195            validate_ranges(ranges, "activation position scope")?;
1196        }
1197        Ok(())
1198    }
1199
1200    /// Returns whether this scope contains a causal position.
1201    pub fn contains(&self, position: u64) -> bool {
1202        match self {
1203            Self::All => true,
1204            Self::InclusiveRanges(ranges) => ranges.iter().any(|range| range.contains(position)),
1205        }
1206    }
1207}
1208
1209/// Built-in transactional tensor operator.
1210#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1211#[serde(rename_all = "snake_case")]
1212pub enum ActivationOperatorV1 {
1213    /// `x' = x + alpha * v`.
1214    ScaledAdd,
1215    /// `x' = x - alpha * dot(x, v) * v`.
1216    ScaledProjectionRemoval,
1217}
1218
1219/// One ordered, position-scoped activation operation.
1220#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1221#[serde(deny_unknown_fields)]
1222pub struct ActivationOperationV1 {
1223    /// Canonically ordered exact tensor sites.
1224    pub sites: Vec<TextTensorSiteV1>,
1225    /// Decode phase.
1226    pub phase: ActivationPhaseV1,
1227    /// Selected causal positions.
1228    pub positions: ActivationPositionScopeV1,
1229    /// Exact vector-bank identity.
1230    pub vector_bank: Digest,
1231    /// Built-in operation.
1232    pub operator: ActivationOperatorV1,
1233    /// Exact IEEE-754 scale bits.
1234    pub scale_bits: u32,
1235}
1236
1237impl ActivationOperationV1 {
1238    /// Returns the finite nonzero operation scale.
1239    ///
1240    /// # Errors
1241    ///
1242    /// Returns an error when the bound bits represent zero, NaN, or infinity.
1243    pub fn scale(&self) -> Result<f32, CoreError> {
1244        let scale = f32::from_bits(self.scale_bits);
1245        if !scale.is_finite() || scale == 0.0 {
1246            return Err(CoreError::invalid(
1247                "activation operation",
1248                "scale must be finite and nonzero",
1249            ));
1250        }
1251        Ok(scale)
1252    }
1253
1254    fn validate_for(&self, topology: &TextModelTopologyV1) -> Result<(), CoreError> {
1255        if self.sites.is_empty() || self.sites.len() > MAX_ACTIVATION_SITES {
1256            return Err(CoreError::invalid(
1257                "activation operation",
1258                "site count is outside the supported bound",
1259            ));
1260        }
1261        validate_canonical_unique(
1262            &self.sites,
1263            "activation operation",
1264            "sites must be unique and canonically ordered",
1265        )?;
1266        self.positions.validate()?;
1267        self.scale()?;
1268        for site in &self.sites {
1269            site.validate_for(topology)?;
1270            if !matches!(
1271                site.family(),
1272                TextTensorSiteFamilyV1::LayerOutput | TextTensorSiteFamilyV1::RouterLogits
1273            ) || site.element_type() != TextTensorElementTypeV1::F32
1274            {
1275                return Err(CoreError::invalid(
1276                    "activation operation",
1277                    "selected site is observable but not a built-in mutable f32 site",
1278                ));
1279            }
1280        }
1281        let families = self
1282            .sites
1283            .iter()
1284            .map(TextTensorSiteV1::family)
1285            .collect::<BTreeSet<_>>();
1286        if families.len() != 1 {
1287            return Err(CoreError::invalid(
1288                "activation operation",
1289                "one operation cannot cross tensor-site families",
1290            ));
1291        }
1292        Ok(())
1293    }
1294}
1295
1296/// Ordered activation operations and observation requests.
1297#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1298#[serde(deny_unknown_fields)]
1299pub struct ActivationProgramV1 {
1300    /// Required model-topology identity.
1301    pub topology: Digest,
1302    /// Ordered tensor operations.
1303    pub operations: Vec<ActivationOperationV1>,
1304    /// Canonically ordered capture-plan identities requested for observation.
1305    #[serde(default)]
1306    pub observations: Vec<Digest>,
1307}
1308
1309impl ActivationProgramV1 {
1310    /// Validates the program against a topology and returns its identity.
1311    ///
1312    /// Vector-bank references are resolved separately by an execution runtime.
1313    ///
1314    /// # Errors
1315    ///
1316    /// Returns an error for topology mismatch, empty or excessive operations,
1317    /// malformed sites, positions, scales, or observation identities.
1318    pub fn digest_for(&self, topology: &TextModelTopologyV1) -> Result<Digest, CoreError> {
1319        if self.topology != topology.digest()? {
1320            return Err(CoreError::invalid(
1321                "activation program",
1322                "topology identity does not match",
1323            ));
1324        }
1325        if self.operations.len() > MAX_ACTIVATION_OPERATIONS
1326            || (self.operations.is_empty() && self.observations.is_empty())
1327        {
1328            return Err(CoreError::invalid(
1329                "activation program",
1330                "the program is empty or has too many operations",
1331            ));
1332        }
1333        if self.observations.len() > MAX_ACTIVATION_OBSERVATIONS {
1334            return Err(CoreError::invalid(
1335                "activation program",
1336                "observation count exceeds the supported bound",
1337            ));
1338        }
1339        validate_canonical_unique(
1340            &self.observations,
1341            "activation program",
1342            "observation identities must be unique and canonically ordered",
1343        )?;
1344        for operation in &self.operations {
1345            operation.validate_for(topology)?;
1346        }
1347        Digest::of_serializable("activation-program-v1", self)
1348    }
1349}
1350
1351/// Evidence for one successful copy-transform-write transaction.
1352#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1353#[serde(deny_unknown_fields)]
1354pub struct ActivationInvocationRowV1 {
1355    /// Zero-based logical row within the submitted decode batch.
1356    pub batch_index: u32,
1357    /// Zero-based operation indices that ran, in declared order.
1358    pub operations: Vec<u32>,
1359    /// Canonically ordered native sequence IDs attached to this row.
1360    pub sequence_ids: Vec<u32>,
1361    /// Causal position.
1362    pub position: u64,
1363    /// Target-authoritative status of this evaluated row.
1364    pub disposition: ActivationTelemetryDispositionV1,
1365}
1366
1367impl ActivationInvocationRowV1 {
1368    fn validate(&self) -> Result<(), CoreError> {
1369        if self.operations.is_empty()
1370            || self
1371                .operations
1372                .windows(2)
1373                .any(|window| window[0] >= window[1])
1374            || self.sequence_ids.is_empty()
1375            || self.sequence_ids.len() > MAX_ACTIVATION_ROW_SEQUENCES
1376            || self
1377                .sequence_ids
1378                .windows(2)
1379                .any(|window| window[0] >= window[1])
1380        {
1381            return Err(CoreError::invalid(
1382                "activation invocation row",
1383                "operation or sequence identifiers are empty, excessive, or non-canonical",
1384            ));
1385        }
1386        Ok(())
1387    }
1388}
1389
1390/// Evidence for one successful native tensor write-back.
1391#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1392#[serde(deny_unknown_fields)]
1393pub struct ActivationInvocationReceiptV1 {
1394    /// Exact tensor site.
1395    pub site: TextTensorSiteV1,
1396    /// Decode phase.
1397    pub phase: ActivationPhaseV1,
1398    /// Changed logical rows in ascending batch order.
1399    pub rows: Vec<ActivationInvocationRowV1>,
1400    /// Number of finite `f32` elements copied for the complete tensor.
1401    pub elements: u32,
1402    /// Complete tensor identity before operations.
1403    pub input: Digest,
1404    /// Complete tensor identity committed after every operation succeeded.
1405    pub output: Digest,
1406}
1407
1408impl ActivationInvocationReceiptV1 {
1409    /// Returns the stable transaction identity.
1410    ///
1411    /// # Errors
1412    ///
1413    /// Returns an error for empty or non-canonical row accounting, unchanged
1414    /// tensor identity, or a zero/excessive element count.
1415    pub fn digest(&self) -> Result<Digest, CoreError> {
1416        if self.rows.is_empty()
1417            || self.rows.len() > MAX_ACTIVATION_TRANSACTION_ROWS
1418            || self
1419                .rows
1420                .windows(2)
1421                .any(|window| window[0].batch_index >= window[1].batch_index)
1422            || self.elements == 0
1423            || u64::from(self.elements) > MAX_ACTIVATION_ELEMENTS
1424            || self.input == self.output
1425        {
1426            return Err(CoreError::invalid(
1427                "activation invocation receipt",
1428                "row accounting, element count, or tensor identities are invalid",
1429            ));
1430        }
1431        for row in &self.rows {
1432            row.validate()?;
1433        }
1434        Digest::of_serializable("activation-invocation-receipt-v1", self)
1435    }
1436}
1437
1438/// Aggregate successful accounting for one activation program runtime.
1439#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1440#[serde(deny_unknown_fields)]
1441pub struct ActivationProgramReceiptV1 {
1442    /// Exact program identity.
1443    pub program: Digest,
1444    /// Required model-topology identity.
1445    pub topology: Digest,
1446    /// Ordered successful transaction identities.
1447    pub invocations: Vec<Digest>,
1448    /// Total elements copied into Rust-owned transactional storage.
1449    pub elements_copied: u64,
1450    /// Number of complete native write-backs.
1451    pub write_backs: u64,
1452}
1453
1454impl ActivationProgramReceiptV1 {
1455    /// Validates aggregate accounting and returns its identity.
1456    ///
1457    /// # Errors
1458    ///
1459    /// Returns an error for excessive evidence or mismatched transaction and
1460    /// write-back counts.
1461    pub fn digest_for(&self, program: &ActivationProgramV1) -> Result<Digest, CoreError> {
1462        if self.program != Digest::of_serializable("activation-program-v1", program)?
1463            || self.topology != program.topology
1464            || self.invocations.len() > MAX_ACTIVATION_INVOCATION_RECEIPTS
1465            || self.write_backs != u64::try_from(self.invocations.len()).unwrap_or(u64::MAX)
1466            || self.elements_copied > MAX_ACTIVATION_ELEMENTS.saturating_mul(self.write_backs)
1467        {
1468            return Err(CoreError::invalid(
1469                "activation program receipt",
1470                "program lineage or transaction accounting is invalid",
1471            ));
1472        }
1473        Digest::of_serializable("activation-program-receipt-v1", self)
1474    }
1475}
1476
1477pub(crate) fn digest_f32_row(domain: &str, values: &[f32]) -> Digest {
1478    let mut bytes = Vec::with_capacity(values.len().saturating_mul(4));
1479    for value in values {
1480        bytes.extend_from_slice(&value.to_bits().to_le_bytes());
1481    }
1482    Digest::of_bytes(domain, &bytes)
1483}
1484
1485/// Returns the canonical identity of one bounded finite activation `f32` row.
1486///
1487/// # Errors
1488///
1489/// Returns an error for an empty, excessive, or non-finite row.
1490pub fn activation_f32_row_identity(values: &[f32]) -> Result<Digest, CoreError> {
1491    validate_finite_row(values, "activation f32 row identity")?;
1492    Ok(digest_f32_row("activation-runtime-f32-v1", values))
1493}
1494
1495fn digest_i32_row(domain: &str, values: &[i32]) -> Digest {
1496    let mut bytes = Vec::with_capacity(values.len().saturating_mul(4));
1497    for value in values {
1498        bytes.extend_from_slice(&value.to_le_bytes());
1499    }
1500    Digest::of_bytes(domain, &bytes)
1501}
1502
1503fn validate_finite_row(values: &[f32], field: &'static str) -> Result<(), CoreError> {
1504    if values.is_empty()
1505        || u64::try_from(values.len()).unwrap_or(u64::MAX) > MAX_ACTIVATION_ELEMENTS
1506        || values.iter().any(|value| !value.is_finite())
1507    {
1508        return Err(CoreError::invalid(
1509            field,
1510            "row must be nonempty, bounded, and finite",
1511        ));
1512    }
1513    Ok(())
1514}
1515
1516fn bounded_element_count(values: usize, field: &'static str) -> Result<u32, CoreError> {
1517    let elements = u32::try_from(values)
1518        .map_err(|_| CoreError::invalid(field, "element count exceeds u32"))?;
1519    if elements == 0 || u64::from(elements) > MAX_ACTIVATION_ELEMENTS {
1520        return Err(CoreError::invalid(
1521            field,
1522            "element count is outside the supported bound",
1523        ));
1524    }
1525    Ok(elements)
1526}
1527
1528fn validate_unit_row(values: &[f32]) -> Result<(), CoreError> {
1529    let squared = values.iter().try_fold(0.0_f64, |total, value| {
1530        let wide = f64::from(*value);
1531        let next = total + wide * wide;
1532        next.is_finite()
1533            .then_some(next)
1534            .ok_or_else(|| CoreError::invalid("activation vector bank", "row norm overflowed"))
1535    })?;
1536    let norm = squared.sqrt();
1537    if (norm - 1.0).abs() > 1.0e-5 {
1538        return Err(CoreError::invalid(
1539            "activation vector bank",
1540            "unit-normalized row is outside tolerance",
1541        ));
1542    }
1543    Ok(())
1544}
1545
1546fn validate_ranges(ranges: &[CausalPositionRangeV1], field: &'static str) -> Result<(), CoreError> {
1547    if ranges.is_empty() || ranges.len() > MAX_ACTIVATION_POSITION_RANGES {
1548        return Err(CoreError::invalid(
1549            field,
1550            "range count is outside the supported bound",
1551        ));
1552    }
1553    let mut prior_end = None;
1554    for range in ranges {
1555        range.len()?;
1556        if prior_end.is_some_and(|end| range.start <= end) {
1557            return Err(CoreError::invalid(
1558                field,
1559                "ranges must be strictly ordered and disjoint",
1560            ));
1561        }
1562        prior_end = Some(range.end);
1563    }
1564    Ok(())
1565}
1566
1567fn validate_canonical_unique<T: Ord>(
1568    values: &[T],
1569    field: &'static str,
1570    reason: &'static str,
1571) -> Result<(), CoreError> {
1572    if values.windows(2).any(|window| window[0] >= window[1]) {
1573        return Err(CoreError::invalid(field, reason));
1574    }
1575    Ok(())
1576}
1577
1578#[cfg(test)]
1579mod tests {
1580    use super::*;
1581
1582    fn topology() -> TextModelTopologyV1 {
1583        TextModelTopologyV1 {
1584            model: Digest::of_bytes("test-model", b"one"),
1585            backend: Digest::of_bytes("test-backend", b"one"),
1586            architecture_implementation: Digest::of_bytes("test-architecture", b"one"),
1587            layers: 4,
1588            embedding_width: 3,
1589            experts: Some(4),
1590            experts_used: Some(2),
1591            nextn_layers: 1,
1592            supported_speculation: vec![
1593                TextSpeculativeMechanismV1::Mtp,
1594                TextSpeculativeMechanismV1::Eagle3,
1595            ],
1596        }
1597    }
1598
1599    fn provenance() -> ActivationVectorProvenanceV1 {
1600        ActivationVectorProvenanceV1 {
1601            accumulator: Digest::of_bytes("test-accumulator", b"one"),
1602            operation: ActivationVectorOperationV1::Mean { count: 1 },
1603            ordered_inputs: vec![Digest::of_bytes("test-input", b"one")],
1604        }
1605    }
1606
1607    #[test]
1608    fn topology_rejects_inconsistent_mechanisms_and_experts() {
1609        let mut value = topology();
1610        assert!(value.digest().is_ok());
1611        value.supported_speculation.reverse();
1612        assert!(value.digest().is_err());
1613        let mut value = topology();
1614        value.experts_used = Some(5);
1615        assert!(value.digest().is_err());
1616        let mut value = topology();
1617        value.nextn_layers = 0;
1618        assert!(value.digest().is_err());
1619    }
1620
1621    #[test]
1622    fn sites_are_topology_checked_and_content_bound() {
1623        let topology = topology();
1624        let layer = TextTensorSiteV1::LayerOutput { layer: 3 };
1625        assert_eq!(layer.row_elements(&topology).unwrap(), 3);
1626        assert!(layer.digest_for(&topology).is_ok());
1627        assert!(
1628            TextTensorSiteV1::LayerOutput { layer: 4 }
1629                .validate_for(&topology)
1630                .is_err()
1631        );
1632        assert!(
1633            TextTensorSiteV1::Named {
1634                name: "bad\0name".to_owned(),
1635                selector: Digest::of_bytes("selector", b"one"),
1636                element_type: TextTensorElementTypeV1::F32,
1637                row_elements: 3,
1638            }
1639            .validate_for(&topology)
1640            .is_err()
1641        );
1642    }
1643
1644    #[test]
1645    fn capture_rejects_duplicate_unordered_and_underbounded_selections() {
1646        let topology = topology();
1647        let site_a = TextTensorSiteV1::LayerOutput { layer: 0 };
1648        let site_b = TextTensorSiteV1::LayerOutput { layer: 1 };
1649        let valid = ActivationCapturePlanV1 {
1650            topology: topology.digest().unwrap(),
1651            sites: vec![site_a.clone(), site_b.clone()],
1652            positions: ActivationCapturePositionsV1::InclusiveRanges(vec![CausalPositionRangeV1 {
1653                start: 2,
1654                end: 3,
1655            }]),
1656            retention: ActivationCaptureRetentionV1::Snapshot,
1657            maximum_elements: 6 * 2,
1658            maximum_retained_bytes: 6 * 2 * 4,
1659        };
1660        assert!(valid.digest_for(&topology).is_ok());
1661
1662        let mut duplicate = valid.clone();
1663        duplicate.sites = vec![site_a.clone(), site_a];
1664        assert!(duplicate.digest_for(&topology).is_err());
1665
1666        let mut unordered = valid.clone();
1667        unordered.sites = vec![site_b, TextTensorSiteV1::LayerOutput { layer: 0 }];
1668        assert!(unordered.digest_for(&topology).is_err());
1669
1670        let mut underbounded = valid;
1671        underbounded.maximum_elements = 1;
1672        assert!(underbounded.digest_for(&topology).is_err());
1673    }
1674
1675    #[test]
1676    fn capture_rows_preserve_exact_bits_and_retention_contract() {
1677        let values = [0.0_f32, -0.0, 2.0];
1678        let snapshot =
1679            ActivationCapturedDataV1::from_f32(&values, ActivationCaptureRetentionV1::Snapshot)
1680                .unwrap();
1681        if let ActivationCapturedDataV1::F32Snapshot {
1682            data,
1683            values: retained,
1684        } = snapshot
1685        {
1686            assert_ne!(retained[0].to_bits(), retained[1].to_bits());
1687            assert_eq!(data, digest_f32_row("activation-captured-f32-v1", &values));
1688        } else {
1689            panic!("expected f32 snapshot");
1690        }
1691        assert!(
1692            ActivationCapturedDataV1::from_f32(&[f32::NAN], ActivationCaptureRetentionV1::Digest)
1693                .is_err()
1694        );
1695        assert!(
1696            ActivationCapturedDataV1::from_i32(&[1, 2], ActivationCaptureRetentionV1::Statistics)
1697                .is_err()
1698        );
1699    }
1700
1701    #[test]
1702    fn vector_bank_binds_sparse_rows_and_normalization() {
1703        let topology = topology();
1704        let bank = ActivationVectorBankV1::new(
1705            &topology,
1706            TextTensorSiteFamilyV1::LayerOutput,
1707            3,
1708            ActivationVectorNormalizationV1::UnitL2,
1709            vec![
1710                ActivationVectorRowV1 {
1711                    layer: 0,
1712                    values: vec![1.0, 0.0, 0.0],
1713                },
1714                ActivationVectorRowV1 {
1715                    layer: 2,
1716                    values: vec![0.0, 1.0, 0.0],
1717                },
1718            ],
1719            provenance(),
1720        )
1721        .unwrap();
1722        assert_eq!(bank.row(2), Some(&[0.0, 1.0, 0.0][..]));
1723        assert!(bank.digest_for(&topology).is_ok());
1724
1725        let mut malformed = bank;
1726        malformed.rows[0].values[0] = 0.5;
1727        assert!(malformed.digest_for(&topology).is_err());
1728    }
1729
1730    #[test]
1731    fn program_rejects_observable_only_mutation_sites() {
1732        let topology = topology();
1733        let bank = Digest::of_bytes("test-bank", b"one");
1734        let valid = ActivationProgramV1 {
1735            topology: topology.digest().unwrap(),
1736            operations: vec![ActivationOperationV1 {
1737                sites: vec![TextTensorSiteV1::LayerOutput { layer: 0 }],
1738                phase: ActivationPhaseV1::Generation,
1739                positions: ActivationPositionScopeV1::All,
1740                vector_bank: bank.clone(),
1741                operator: ActivationOperatorV1::ScaledAdd,
1742                scale_bits: 0.5_f32.to_bits(),
1743            }],
1744            observations: Vec::new(),
1745        };
1746        assert!(valid.digest_for(&topology).is_ok());
1747
1748        let mut invalid = valid;
1749        invalid.operations[0].sites = vec![TextTensorSiteV1::RouterProbabilities {
1750            layer: 0,
1751            selector: Digest::of_bytes("selector", b"one"),
1752        }];
1753        assert!(invalid.digest_for(&topology).is_err());
1754    }
1755
1756    #[test]
1757    fn invocation_rows_bind_provisional_and_final_causal_status() {
1758        let provisional = ActivationInvocationReceiptV1 {
1759            site: TextTensorSiteV1::LayerOutput { layer: 1 },
1760            phase: ActivationPhaseV1::Verification,
1761            rows: vec![ActivationInvocationRowV1 {
1762                batch_index: 0,
1763                operations: vec![0],
1764                sequence_ids: vec![0],
1765                position: 7,
1766                disposition: ActivationTelemetryDispositionV1::Provisional,
1767            }],
1768            elements: 3,
1769            input: Digest::of_bytes("test-activation-input", b"one"),
1770            output: Digest::of_bytes("test-activation-output", b"one"),
1771        };
1772        let mut admitted = provisional.clone();
1773        admitted.rows[0].disposition = ActivationTelemetryDispositionV1::Admitted;
1774        assert_ne!(provisional.digest().unwrap(), admitted.digest().unwrap());
1775    }
1776}