1use std::collections::BTreeSet;
6
7use serde::{Deserialize, Serialize};
8
9use crate::{CoreError, Digest};
10
11pub const MAX_TEXT_MODEL_LAYERS: u32 = 4_096;
13pub const MAX_TEXT_TENSOR_ROW_ELEMENTS: u32 = 1_048_576;
15pub const MAX_TEXT_MODEL_EXPERTS: u32 = 65_536;
17pub const MAX_ACTIVATION_SITES: usize = 128;
19pub const MAX_ACTIVATION_POSITION_RANGES: usize = 128;
21pub const MAX_ACTIVATION_CAPTURE_POSITIONS: u32 = 4_096;
23pub const MAX_ACTIVATION_ELEMENTS: u64 = 16_777_216;
25pub const MAX_ACTIVATION_RETAINED_BYTES: u64 = MAX_ACTIVATION_ELEMENTS * 4;
27pub const MAX_ACTIVATION_VECTOR_ROWS: usize = 4_096;
29pub const MAX_ACTIVATION_OPERATIONS: usize = 256;
31pub const MAX_ACTIVATION_OBSERVATIONS: usize = 128;
33pub const MAX_ACTIVATION_VECTOR_INPUTS: usize = 65_536;
35pub const MAX_ACTIVATION_INVOCATION_RECEIPTS: usize = 65_536;
37pub const MAX_ACTIVATION_TRANSACTION_ROWS: usize = 4_096;
39pub const MAX_ACTIVATION_ROW_SEQUENCES: usize = 4_096;
41pub const MAX_TEXT_TENSOR_NAME_BYTES: usize = 256;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
46#[serde(rename_all = "snake_case")]
47pub enum TextSpeculativeMechanismV1 {
48 Mtp,
50 Eagle3,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct TextModelTopologyV1 {
58 pub model: Digest,
60 pub backend: Digest,
62 pub architecture_implementation: Digest,
64 pub layers: u32,
66 pub embedding_width: u32,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub experts: Option<u32>,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub experts_used: Option<u32>,
74 pub nextn_layers: u32,
76 #[serde(default)]
78 pub supported_speculation: Vec<TextSpeculativeMechanismV1>,
79}
80
81impl TextModelTopologyV1 {
82 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum TextTensorElementTypeV1 {
152 F32,
154 I32,
156}
157
158#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
160#[serde(rename_all = "snake_case")]
161pub enum TextTensorSiteFamilyV1 {
162 LayerOutput,
164 RouterLogits,
166 RouterProbabilities,
168 SelectedExperts,
170 Named,
172}
173
174#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
176#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
177pub enum TextTensorSiteV1 {
178 LayerOutput {
180 layer: u32,
182 },
183 RouterLogits {
185 layer: u32,
187 selector: Digest,
189 },
190 RouterProbabilities {
192 layer: u32,
194 selector: Digest,
196 },
197 SelectedExperts {
199 layer: u32,
201 selector: Digest,
203 },
204 Named {
206 name: String,
208 selector: Digest,
210 element_type: TextTensorElementTypeV1,
212 row_elements: u32,
214 },
215}
216
217impl TextTensorSiteV1 {
218 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 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 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 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
342#[serde(deny_unknown_fields)]
343pub struct CausalPositionRangeV1 {
344 pub start: u64,
346 pub end: u64,
348}
349
350impl CausalPositionRangeV1 {
351 pub const fn is_empty(self) -> bool {
354 self.start > self.end
355 }
356
357 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 pub const fn contains(self, position: u64) -> bool {
373 position >= self.start && position <= self.end
374 }
375}
376
377#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(tag = "kind", content = "ranges", rename_all = "snake_case")]
380pub enum ActivationCapturePositionsV1 {
381 LastPrefillToken,
383 InclusiveRanges(Vec<CausalPositionRangeV1>),
385}
386
387impl ActivationCapturePositionsV1 {
388 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(rename_all = "snake_case")]
435pub enum ActivationCaptureRetentionV1 {
436 Digest,
438 Statistics,
440 Snapshot,
442}
443
444#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(deny_unknown_fields)]
447pub struct ActivationCapturePlanV1 {
448 pub topology: Digest,
450 pub sites: Vec<TextTensorSiteV1>,
452 pub positions: ActivationCapturePositionsV1,
454 pub retention: ActivationCaptureRetentionV1,
456 pub maximum_elements: u64,
458 pub maximum_retained_bytes: u64,
460}
461
462impl ActivationCapturePlanV1 {
463 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
542#[serde(rename_all = "snake_case")]
543pub enum ActivationTelemetryDispositionV1 {
544 Provisional,
546 Admitted,
548 Rejected,
550}
551
552#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
554#[serde(deny_unknown_fields)]
555pub struct ActivationStatisticsV1 {
556 pub minimum_bits: u32,
558 pub maximum_bits: u32,
560 pub mean_bits: u32,
562 pub l2_norm_bits: u32,
564}
565
566impl ActivationStatisticsV1 {
567 #[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
632#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
633pub enum ActivationCapturedDataV1 {
634 Digest {
636 data: Digest,
638 elements: u32,
640 },
641 Statistics {
643 data: Digest,
645 elements: u32,
647 statistics: ActivationStatisticsV1,
649 },
650 F32Snapshot {
652 data: Digest,
654 values: Vec<f32>,
656 },
657 I32Snapshot {
659 data: Digest,
661 values: Vec<i32>,
663 },
664}
665
666impl ActivationCapturedDataV1 {
667 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 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 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 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
805#[serde(deny_unknown_fields)]
806pub struct ActivationCaptureRecordV1 {
807 pub plan: Digest,
809 pub site: TextTensorSiteV1,
811 pub position: u64,
813 pub disposition: ActivationTelemetryDispositionV1,
815 pub retained: ActivationCapturedDataV1,
817}
818
819impl ActivationCaptureRecordV1 {
820 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
862#[serde(deny_unknown_fields)]
863pub struct ActivationCaptureReceiptV1 {
864 pub plan: Digest,
866 pub records: Vec<Digest>,
868 pub elements: u64,
870 pub retained_bytes: u64,
872}
873
874impl ActivationCaptureReceiptV1 {
875 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
898#[serde(rename_all = "snake_case")]
899pub enum ActivationVectorNormalizationV1 {
900 None,
902 UnitL2,
904}
905
906#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
908#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
909pub enum ActivationVectorOperationV1 {
910 Mean {
912 count: u32,
914 },
915 DifferenceOfMeans {
917 left_count: u32,
919 right_count: u32,
921 },
922}
923
924#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
926#[serde(deny_unknown_fields)]
927pub struct ActivationVectorProvenanceV1 {
928 pub accumulator: Digest,
930 pub operation: ActivationVectorOperationV1,
932 pub ordered_inputs: Vec<Digest>,
934}
935
936impl ActivationVectorProvenanceV1 {
937 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
986#[serde(deny_unknown_fields)]
987pub struct ActivationVectorRowV1 {
988 pub layer: u32,
990 pub values: Vec<f32>,
992}
993
994#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
996#[serde(deny_unknown_fields)]
997pub struct ActivationVectorBankV1 {
998 pub topology: Digest,
1000 pub site_family: TextTensorSiteFamilyV1,
1002 pub row_elements: u32,
1004 pub normalization: ActivationVectorNormalizationV1,
1006 pub rows: Vec<ActivationVectorRowV1>,
1008 pub data: Digest,
1010 pub provenance: ActivationVectorProvenanceV1,
1012}
1013
1014impl ActivationVectorBankV1 {
1015 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1164#[serde(rename_all = "snake_case")]
1165pub enum ActivationPhaseV1 {
1166 Prefill,
1168 Generation,
1170 Verification,
1172 Draft,
1174}
1175
1176#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1178#[serde(tag = "kind", content = "ranges", rename_all = "snake_case")]
1179pub enum ActivationPositionScopeV1 {
1180 All,
1182 InclusiveRanges(Vec<CausalPositionRangeV1>),
1184}
1185
1186impl ActivationPositionScopeV1 {
1187 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1211#[serde(rename_all = "snake_case")]
1212pub enum ActivationOperatorV1 {
1213 ScaledAdd,
1215 ScaledProjectionRemoval,
1217}
1218
1219#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1221#[serde(deny_unknown_fields)]
1222pub struct ActivationOperationV1 {
1223 pub sites: Vec<TextTensorSiteV1>,
1225 pub phase: ActivationPhaseV1,
1227 pub positions: ActivationPositionScopeV1,
1229 pub vector_bank: Digest,
1231 pub operator: ActivationOperatorV1,
1233 pub scale_bits: u32,
1235}
1236
1237impl ActivationOperationV1 {
1238 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1298#[serde(deny_unknown_fields)]
1299pub struct ActivationProgramV1 {
1300 pub topology: Digest,
1302 pub operations: Vec<ActivationOperationV1>,
1304 #[serde(default)]
1306 pub observations: Vec<Digest>,
1307}
1308
1309impl ActivationProgramV1 {
1310 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1353#[serde(deny_unknown_fields)]
1354pub struct ActivationInvocationRowV1 {
1355 pub batch_index: u32,
1357 pub operations: Vec<u32>,
1359 pub sequence_ids: Vec<u32>,
1361 pub position: u64,
1363 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1392#[serde(deny_unknown_fields)]
1393pub struct ActivationInvocationReceiptV1 {
1394 pub site: TextTensorSiteV1,
1396 pub phase: ActivationPhaseV1,
1398 pub rows: Vec<ActivationInvocationRowV1>,
1400 pub elements: u32,
1402 pub input: Digest,
1404 pub output: Digest,
1406}
1407
1408impl ActivationInvocationReceiptV1 {
1409 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1440#[serde(deny_unknown_fields)]
1441pub struct ActivationProgramReceiptV1 {
1442 pub program: Digest,
1444 pub topology: Digest,
1446 pub invocations: Vec<Digest>,
1448 pub elements_copied: u64,
1450 pub write_backs: u64,
1452}
1453
1454impl ActivationProgramReceiptV1 {
1455 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
1485pub 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}