1use super::spectrum::WorkBudget;
5use super::*;
6
7const fn r(key: u16, type_tag: u8, count: Option<u32>, required: bool) -> FieldRule {
8 FieldRule {
9 key,
10 type_tag,
11 count,
12 required,
13 }
14}
15
16const RULES_105: &[FieldRule] = &[
17 r(1, 7, Some(32), true),
18 r(2, 6, None, true),
19 r(3, 7, Some(32), true),
20 r(4, 2, Some(1), true),
21 r(5, 8, Some(1), true),
22 r(6, 8, Some(1), false),
23 r(7, 8, Some(1), false),
24 r(8, 6, None, true),
25 r(9, 2, None, true),
26];
27
28const RULES_106: &[FieldRule] = &[
29 r(1, 8, Some(1), true),
30 r(2, 8, Some(1), true),
31 r(3, 6, None, true),
32 r(4, 5, Some(16), true),
33 r(5, 8, Some(1), false),
34 r(6, 3, Some(2), false),
35];
36
37const RULES_107: &[FieldRule] = &[
38 r(1, 6, None, true),
39 r(2, 7, Some(32), true),
40 r(3, 6, None, true),
41 r(4, 5, Some(1), true),
42 r(5, 5, Some(1), true),
43 r(6, 5, Some(1), false),
44 r(7, 6, None, false),
45 r(8, 3, Some(2), false),
46 r(9, 8, Some(1), false),
47];
48
49const RULES_133: &[FieldRule] = &[
50 r(1, 6, None, true),
51 r(2, 5, Some(1), true),
52 r(3, 5, Some(1), true),
53 r(4, 5, Some(1), true),
54 r(5, 5, None, false),
55 r(6, 5, None, false),
56 r(7, 5, None, false),
57 r(8, 5, None, false),
58 r(9, 9, Some(1), false),
59 r(10, 8, Some(1), false),
60 r(11, 8, Some(1), false),
61];
62
63const RULES_134: &[FieldRule] = &[
64 r(1, 6, None, true),
65 r(2, 6, None, true),
66 r(3, 7, Some(32), true),
67 r(4, 6, None, true),
68 r(5, 6, None, false),
69 r(6, 6, None, false),
70 r(7, 6, None, false),
71 r(8, 6, None, true),
72 r(9, 6, None, false),
73 r(10, 3, Some(2), false),
74 r(11, 6, None, false),
75 r(12, 8, Some(1), false),
76];
77
78const RULES_136: &[FieldRule] = &[
79 r(1, 8, Some(1), true),
80 r(2, 2, Some(1), true),
81 r(3, 2, Some(1), true),
82 r(4, 6, None, true),
83 r(5, 6, None, true),
84 r(6, 8, Some(1), true),
85 r(7, 6, None, true),
86 r(8, 6, None, false),
87 r(9, 1, Some(1), false),
88 r(10, 1, Some(1), false),
89 r(11, 6, None, false),
90 r(12, 5, Some(1), false),
91 r(13, 1, Some(1), false),
92];
93
94const RULES_137: &[FieldRule] = &[
95 r(1, 6, None, true),
96 r(2, 6, None, true),
97 r(3, 6, None, true),
98 r(4, 8, Some(1), true),
99 r(5, 8, Some(1), false),
100 r(6, 8, Some(1), false),
101 r(7, 8, Some(1), false),
102];
103
104pub fn material_binding_rules() -> &'static [FieldRule] {
105 RULES_105
106}
107pub fn coordinate_transform_rules() -> &'static [FieldRule] {
108 RULES_106
109}
110pub fn calibration_rules() -> &'static [FieldRule] {
111 RULES_107
112}
113pub fn constitutive_model_rules() -> &'static [FieldRule] {
114 RULES_133
115}
116pub fn model_evidence_rules() -> &'static [FieldRule] {
117 RULES_134
118}
119pub fn acquisition_rules() -> &'static [FieldRule] {
120 RULES_136
121}
122pub fn bio_context_rules() -> &'static [FieldRule] {
123 RULES_137
124}
125
126#[inline]
127pub(super) fn i64_at(b: &[u8], at: usize) -> i64 {
128 i64::from_le_bytes(b[at..at + 8].try_into().unwrap())
129}
130
131#[inline]
132fn f64_scalar(b: Block<'_>, k: u16) -> Result<f64, Error> {
133 let val = f64_at(required(b, k)?.value(), 0);
134 if !val.is_finite() {
135 return Err(Error::NonFinite);
136 }
137 Ok(val)
138}
139
140fn non_empty_text<'a>(b: Block<'a>, k: u16) -> Result<&'a str, Error> {
141 let s = text(required(b, k)?)?;
142 if s.is_empty() {
143 return Err(Error::Descriptor);
144 }
145 Ok(s)
146}
147
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149pub enum ConstitutiveKind {
150 Vacuum,
151 IsotropicNondispersive,
152 DebyeIsotropic,
153 LorentzIsotropic,
154 AnisotropicTabulated,
155}
156
157impl ConstitutiveKind {
158 pub fn parse(name: &str) -> Result<Self, Error> {
159 match name {
160 "vacuum" => Ok(Self::Vacuum),
161 "isotropic_nondispersive" => Ok(Self::IsotropicNondispersive),
162 "debye_isotropic" => Ok(Self::DebyeIsotropic),
163 "lorentz_isotropic" => Ok(Self::LorentzIsotropic),
164 "anisotropic_tabulated" => Ok(Self::AnisotropicTabulated),
165 _ => Err(Error::UnsupportedProfile),
166 }
167 }
168}
169
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub enum TransformKind {
172 RigidMatrix4,
173 AffineMatrix4,
174}
175
176impl TransformKind {
177 pub fn parse(name: &str) -> Result<Self, Error> {
178 match name {
179 "rigid_matrix4" => Ok(Self::RigidMatrix4),
180 "affine_matrix4" => Ok(Self::AffineMatrix4),
181 _ => Err(Error::UnsupportedProfile),
182 }
183 }
184}
185
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187pub enum EpistemicClass {
188 Empirical,
189 ModelEstimate,
190 Hypothesis,
191 Counterfactual,
192 Fictional,
193}
194
195impl EpistemicClass {
196 pub fn parse(name: &str) -> Result<Self, Error> {
197 match name {
198 "empirical" => Ok(Self::Empirical),
199 "model_estimate" => Ok(Self::ModelEstimate),
200 "hypothesis" => Ok(Self::Hypothesis),
201 "counterfactual" => Ok(Self::Counterfactual),
202 "fictional" => Ok(Self::Fictional),
203 _ => Err(Error::Value),
204 }
205 }
206
207 pub const fn is_speculative(self) -> bool {
208 matches!(
209 self,
210 Self::Hypothesis | Self::Counterfactual | Self::Fictional
211 )
212 }
213}
214
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub enum SignalKind {
217 ComplexBaseband,
218 ComplexStft,
219 RealSamples,
220}
221
222impl SignalKind {
223 pub fn parse(name: &str) -> Result<Self, Error> {
224 match name {
225 "complex_baseband" => Ok(Self::ComplexBaseband),
226 "complex_stft" => Ok(Self::ComplexStft),
227 "real_samples" => Ok(Self::RealSamples),
228 _ => Err(Error::Value),
229 }
230 }
231}
232
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub enum WindowKind {
235 Rectangular,
236 Hann,
237}
238
239impl WindowKind {
240 pub fn parse(name: &str) -> Result<Self, Error> {
241 match name {
242 "rectangular" => Ok(Self::Rectangular),
243 "hann" => Ok(Self::Hann),
244 _ => Err(Error::Value),
245 }
246 }
247}
248
249use super::frame_transforms::Schema106Transform;
250
251pub fn validate_material_binding(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
252 if text(required(block, 2)?)? != "BLAKE3-256" {
253 return Err(Error::Value);
254 }
255 let _ = non_empty_text(block, 8)?;
256 ctx.require_schema(scalar32(block, 5)?, 2)
257 .map_err(Error::Shared)?;
258 if let Some(tr) = field(block, 6) {
259 ctx.require_schema(u32_at(tr.value(), 0), 106)
260 .map_err(Error::Shared)?;
261 }
262 if let Some(clk) = field(block, 7) {
263 ctx.require_schema(u32_at(clk.value(), 0), 1)
264 .map_err(Error::Shared)?;
265 }
266 let ids = required(block, 9)?.value();
267 if ids.is_empty() || !ids.len().is_multiple_of(8) {
268 return Err(Error::Descriptor);
269 }
270 let count = ids.len() / 8;
271 let work = (count as u64)
272 .checked_mul(count as u64)
273 .ok_or(Error::Overflow)?;
274 ctx.charge_work(work).map_err(Error::Shared)?;
275 for i in 0..count {
276 let a = u64_at(ids, i * 8);
277 for j in (i + 1)..count {
278 if a == u64_at(ids, j * 8) {
279 return Err(Error::Value);
280 }
281 }
282 }
283 Ok(())
284}
285
286pub fn material_binding_contains(block: Block<'_>, material_id: u64) -> Result<bool, Error> {
287 if block.schema_type() != 105 || block.revision() != 1 {
288 return Err(Error::Shared(semantics::Error::ReferenceSchema));
289 }
290 let ids = required(block, 9)?.value();
291 Ok(ids.chunks_exact(8).any(|c| u64_at(c, 0) == material_id))
292}
293
294pub fn validate_coordinate_transform(
295 block: Block<'_>,
296 ctx: &Context<'_, '_>,
297) -> Result<(), Error> {
298 ctx.require_schema(scalar32(block, 1)?, 2)
299 .map_err(Error::Shared)?;
300 ctx.require_schema(scalar32(block, 2)?, 2)
301 .map_err(Error::Shared)?;
302 if let Some(clk) = field(block, 5) {
303 ctx.require_schema(u32_at(clk.value(), 0), 1)
304 .map_err(Error::Shared)?;
305 } else if field(block, 6).is_some() {
306 return Err(Error::Time);
307 }
308 let _ = Schema106Transform::from_block(block)?;
309 Ok(())
310}
311
312pub fn evaluate_calibration(
314 block: Block<'_>,
315 raw_value: f64,
316 tick: Option<i64>,
317) -> Result<f64, Error> {
318 if block.schema_type() != 107 || block.revision() != 1 {
319 return Err(Error::Shared(semantics::Error::ReferenceSchema));
320 }
321 if !raw_value.is_finite() {
322 return Err(Error::NonFinite);
323 }
324 let scale = f64_scalar(block, 4)?;
325 let offset = f64_scalar(block, 5)?;
326 if scale <= 0.0 {
327 return Err(Error::Value);
328 }
329 if let Some(vt) = field(block, 8) {
330 let from = i64_at(vt.value(), 0);
331 let until = i64_at(vt.value(), 8);
332 if from >= until {
333 return Err(Error::Time);
334 }
335 let t = tick.ok_or(Error::Time)?;
336 if t < from || t >= until {
337 return Err(Error::Time);
338 }
339 }
340 let calibrated = scale * raw_value + offset;
341 if !calibrated.is_finite() {
342 return Err(Error::NonFinite);
343 }
344 Ok(calibrated)
345}
346
347pub fn validate_calibration(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
348 let _ = non_empty_text(block, 1)?;
349 let _ = non_empty_text(block, 3)?;
350 let scale = f64_scalar(block, 4)?;
351 let _ = f64_scalar(block, 5)?;
352 if scale <= 0.0 {
353 return Err(Error::Value);
354 }
355 if let Some(unc) = field(block, 6) {
356 let u = f64_at(unc.value(), 0);
357 if !u.is_finite() {
358 return Err(Error::NonFinite);
359 }
360 if u < 0.0 {
361 return Err(Error::Value);
362 }
363 let _ = non_empty_text(block, 7)?;
364 } else if field(block, 7).is_some() {
365 let _ = non_empty_text(block, 7)?;
366 }
367 if let Some(clk) = field(block, 9) {
368 ctx.require_schema(u32_at(clk.value(), 0), 1)
369 .map_err(Error::Shared)?;
370 }
371 if let Some(vt) = field(block, 8) {
372 if field(block, 9).is_none() {
373 return Err(Error::Time);
374 }
375 let from = i64_at(vt.value(), 0);
376 let until = i64_at(vt.value(), 8);
377 if from >= until {
378 return Err(Error::Time);
379 }
380 }
381 Ok(())
382}
383
384pub fn validate_constitutive_model(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
385 let kind = ConstitutiveKind::parse(text(required(block, 1)?)?)?;
386 let eps = f64_scalar(block, 2)?;
387 let mu = f64_scalar(block, 3)?;
388 let sigma = f64_scalar(block, 4)?;
389 if eps <= 0.0 || mu <= 0.0 || sigma < 0.0 {
390 return Err(Error::Value);
391 }
392 let f5 = field(block, 5);
393 let f6 = field(block, 6);
394 let f7 = field(block, 7);
395 let f8 = field(block, 8);
396 let f9 = field(block, 9);
397 match kind {
398 ConstitutiveKind::Vacuum => {
399 if (eps - 1.0).abs() > 1.0e-12 || (mu - 1.0).abs() > 1.0e-12 || sigma != 0.0 {
400 return Err(Error::Value);
401 }
402 if f5.is_some() || f6.is_some() || f7.is_some() || f8.is_some() || f9.is_some() {
403 return Err(Error::Descriptor);
404 }
405 }
406 ConstitutiveKind::IsotropicNondispersive => {
407 if f5.is_some() || f6.is_some() || f7.is_some() || f8.is_some() || f9.is_some() {
408 return Err(Error::Descriptor);
409 }
410 }
411 ConstitutiveKind::DebyeIsotropic => {
412 let de = f5.ok_or(Error::Descriptor)?;
413 let tau = f6.ok_or(Error::Descriptor)?;
414 if f7.is_some() || f8.is_some() || de.element_count() == 0 {
415 return Err(Error::Descriptor);
416 }
417 if de.element_count() != tau.element_count() {
418 return Err(Error::Shape);
419 }
420 for i in 0..de.element_count() as usize {
421 let d = f64_at(de.value(), i * 8);
422 let t = f64_at(tau.value(), i * 8);
423 if !d.is_finite() || !t.is_finite() {
424 return Err(Error::NonFinite);
425 }
426 if d < 0.0 || t <= 0.0 {
427 return Err(Error::Value);
428 }
429 }
430 }
431 ConstitutiveKind::LorentzIsotropic => {
432 let de = f5.ok_or(Error::Descriptor)?;
433 let w0 = f7.ok_or(Error::Descriptor)?;
434 let gm = f8.ok_or(Error::Descriptor)?;
435 if f6.is_some() || de.element_count() == 0 {
436 return Err(Error::Descriptor);
437 }
438 if de.element_count() != w0.element_count() || de.element_count() != gm.element_count()
439 {
440 return Err(Error::Shape);
441 }
442 for i in 0..de.element_count() as usize {
443 let d = f64_at(de.value(), i * 8);
444 let w = f64_at(w0.value(), i * 8);
445 let g = f64_at(gm.value(), i * 8);
446 if !d.is_finite() || !w.is_finite() || !g.is_finite() {
447 return Err(Error::NonFinite);
448 }
449 if w <= 0.0 || g < 0.0 {
450 return Err(Error::Value);
451 }
452 }
453 }
454 ConstitutiveKind::AnisotropicTabulated => {
455 let att = f9.ok_or(Error::Descriptor)?;
456 let entry_id = u32_at(att.value(), 0);
457 if entry_id == 0 {
458 return Err(Error::Descriptor);
459 }
460 let _ = ctx.entry(entry_id).map_err(Error::Shared)?;
461 }
462 }
463 if let Some(mat) = field(block, 10) {
464 ctx.require_schema(u32_at(mat.value(), 0), 105)
465 .map_err(Error::Shared)?;
466 }
467 if let Some(ev) = field(block, 11) {
468 ctx.require_schema(u32_at(ev.value(), 0), 134)
469 .map_err(Error::Shared)?;
470 }
471 Ok(())
472}
473
474pub fn validate_model_evidence(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
475 let _ = non_empty_text(block, 1)?;
476 let _ = non_empty_text(block, 2)?;
477 let _ = non_empty_text(block, 4)?;
478 let _ = EpistemicClass::parse(text(required(block, 8)?)?)?;
479 for opt_k in [5, 6, 7, 9, 11] {
480 if field(block, opt_k).is_some() {
481 let _ = non_empty_text(block, opt_k)?;
482 }
483 }
484 if let Some(clk) = field(block, 12) {
485 ctx.require_schema(u32_at(clk.value(), 0), 1)
486 .map_err(Error::Shared)?;
487 }
488 if let Some(ticks) = field(block, 10) {
489 if field(block, 12).is_none() {
490 return Err(Error::Time);
491 }
492 if i64_at(ticks.value(), 8) < i64_at(ticks.value(), 0) {
493 return Err(Error::Time);
494 }
495 }
496 Ok(())
497}
498
499pub fn validate_acquisition(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
500 ctx.require_schema(scalar32(block, 1)?, 1)
501 .map_err(Error::Shared)?;
502 let rate_num = scalar64(block, 2)?;
503 let rate_den = scalar64(block, 3)?;
504 if rate_num == 0 || rate_den == 0 {
505 return Err(Error::Time);
506 }
507 let kind = SignalKind::parse(text(required(block, 4)?)?)?;
508 let _ = non_empty_text(block, 5)?;
509 ctx.require_schema(scalar32(block, 6)?, 107)
510 .map_err(Error::Shared)?;
511 if text(required(block, 7)?)? != "I_plus_iQ_exp_minus_iwt" {
512 return Err(Error::UnsupportedProfile);
513 }
514 if let Some(w) = field(block, 8) {
515 let _ = WindowKind::parse(text(w)?)?;
516 }
517 if let Some(fft) = field(block, 9) {
518 let n = u32_at(fft.value(), 0);
519 if !(1..=4096).contains(&n) {
520 return Err(Error::Shape);
521 }
522 }
523 if let Some(hop) = field(block, 10) {
524 if u32_at(hop.value(), 0) == 0 {
525 return Err(Error::Shape);
526 }
527 }
528 if let Some(norm) = field(block, 11) {
529 if text(norm)? != "forward-unscaled-inverse-1/N" {
530 return Err(Error::UnsupportedProfile);
531 }
532 }
533 if kind == SignalKind::ComplexStft {
534 let _ = field(block, 8).ok_or(Error::Descriptor)?;
535 let _ = field(block, 9).ok_or(Error::Descriptor)?;
536 let _ = field(block, 10).ok_or(Error::Descriptor)?;
537 let _ = field(block, 11).ok_or(Error::Descriptor)?;
538 }
539 if field(block, 12).is_some() && f64_scalar(block, 12)? < 0.0 {
540 return Err(Error::Value);
541 }
542 if let Some(ch) = field(block, 13) {
543 if u32_at(ch.value(), 0) == 0 {
544 return Err(Error::Shape);
545 }
546 }
547 Ok(())
548}
549
550pub fn validate_bio_context(block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), Error> {
551 let _ = non_empty_text(block, 1)?;
552 let _ = non_empty_text(block, 2)?;
553 let obs = text(required(block, 3)?)?;
554 if !matches!(
555 obs,
556 "current_dipole" | "radiative_observation" | "model_construct"
557 ) {
558 return Err(Error::Value);
559 }
560 ctx.require_schema(scalar32(block, 4)?, 4)
561 .map_err(Error::Shared)?;
562 if let Some(cal) = field(block, 5) {
563 ctx.require_schema(u32_at(cal.value(), 0), 107)
564 .map_err(Error::Shared)?;
565 }
566 if let Some(ev) = field(block, 6) {
567 ctx.require_schema(u32_at(ev.value(), 0), 134)
568 .map_err(Error::Shared)?;
569 }
570 if let Some(cp) = field(block, 7) {
571 let prov = ctx
572 .require_schema(u32_at(cp.value(), 0), 4)
573 .map_err(Error::Shared)?;
574 let receipt = field(prov, 6).ok_or(Error::Descriptor)?;
575 if receipt.value().len() != 32 || receipt.value().iter().all(|&b| b == 0) {
576 return Err(Error::Descriptor);
577 }
578 }
579 Ok(())
580}
581
582pub struct ProfileResponseValidator<'c, 'v, 'a> {
585 pub ctx: &'c Context<'v, 'a>,
586}
587
588impl spectrum::ResponseValidator for ProfileResponseValidator<'_, '_, '_> {
589 fn validate(&self, id: u32, budget: &mut WorkBudget) -> Result<(), spectrum::Error> {
590 budget.charge(16)?;
591 let block = self.ctx.block(id).map_err(|_| spectrum::Error::UnsupportedResponse)?;
592 match (block.schema_type(), block.revision()) {
593 (107, 1) => {
594 if validate_calibration(block, self.ctx).is_err() {
595 return Err(spectrum::Error::UnsupportedResponse);
596 }
597 Ok(())
598 }
599 (3, 1) => {
600 let q = field(block, 7).and_then(|f| std::str::from_utf8(f.value()).ok());
601 let u = field(block, 8).and_then(|f| std::str::from_utf8(f.value()).ok());
602 if q.is_none_or(str::is_empty) || u.is_none_or(str::is_empty) {
603 return Err(spectrum::Error::UnsupportedResponse);
604 }
605 let ext_ids = field(block, 18).ok_or(spectrum::Error::UnsupportedResponse)?;
606 for chunk in ext_ids.value().chunks_exact(4) {
607 budget.charge(8)?;
608 let ext_id = u32_at(chunk, 0);
609 if let Ok(ext) = self.ctx.require_schema(ext_id, 103) {
610 if let Some(pf) = field(ext, 6) {
611 if let Ok(name) = std::str::from_utf8(pf.value()) {
612 if matches!(name, "spectral_response_v1" | "auxiliary_tensor_v1") {
613 return Ok(());
614 }
615 }
616 }
617 }
618 }
619 Err(spectrum::Error::UnsupportedResponse)
620 }
621 _ => Err(spectrum::Error::UnsupportedResponse),
622 }
623 }
624}