1use crate::audio::qac::metadata::{self as meta, SignalRegistry};
4use crate::audio::qac::signal::{samples::finite, Error, Limits, Rate, Scalar, SignalView, Timing};
5use crate::q42::{
6 field_envelope::{self as env, Block, Entry, Family, StructuralView},
7 field_semantics::{self as sem, Context, DomainRegistry, FieldRule},
8};
9use crate::sensing::acquisition::{self as a, storage};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum BridgeError {
13 Envelope(env::Error), Semantic(sem::Error), Signal(Error), Acquisition(storage::Error),
14 AcquisitionCore(a::Error), UnsupportedFamily, Index, Limit, Profile, MismatchedSourceDigest,
15 MissingSourceEntry, InvalidSourceMode, Reference, Overflow,
16}
17
18impl From<env::Error> for BridgeError { fn from(e: env::Error) -> Self { Self::Envelope(e) } }
19impl From<sem::Error> for BridgeError {
20 fn from(e: sem::Error) -> Self {
21 match e {
22 sem::Error::Provenance => Self::MismatchedSourceDigest,
23 other => Self::Semantic(other),
24 }
25 }
26}
27impl From<Error> for BridgeError { fn from(e: Error) -> Self { Self::Signal(e) } }
28impl From<storage::Error> for BridgeError { fn from(e: storage::Error) -> Self { Self::Acquisition(e) } }
29impl From<a::Error> for BridgeError { fn from(e: a::Error) -> Self { Self::AcquisitionCore(e) } }
30
31#[derive(Clone, Copy, Debug, Default)]
32pub struct QacAcquisitionRegistry {
33 pub acquisition_limits: storage::Limits,
34}
35
36impl DomainRegistry for QacAcquisitionRegistry {
37 fn rules(&self, s: u16, v: u16) -> Option<&'static [FieldRule]> {
38 if v != 1 { return None; }
39 match s {
40 storage::ACQUISITION_SCHEMA | storage::DERIVATION_SCHEMA => {
41 storage::AcquisitionRegistry { limits: self.acquisition_limits }.rules(s, v)
42 }
43 _ => SignalRegistry.rules(s, v),
44 }
45 }
46 fn validate_block(&self, b: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), sem::Error> {
47 match b.schema_type() {
48 storage::ACQUISITION_SCHEMA | storage::DERIVATION_SCHEMA => {
49 storage::AcquisitionRegistry { limits: self.acquisition_limits }.validate_block(b, ctx)
50 }
51 _ => SignalRegistry.validate_block(b, ctx),
52 }
53 }
54 fn descriptor_target_schema(&self, k: u16) -> Option<u16> { SignalRegistry.descriptor_target_schema(k) }
55 fn validate_units(&self, u: &str, ctx: &Context<'_, '_>) -> Result<(), sem::Error> { SignalRegistry.validate_units(u, ctx) }
56}
57
58#[derive(Clone, Copy, Debug)]
59pub struct AdmittedAcquisitionEntry<'a> {
60 pub entry_index: u32, pub original: a::Original<'a>, pub region: a::Region<'a>,
61 pub kind: u32, pub descriptor_id: u32, pub view_block_id: u32, pub lineage_block_id: Option<u32>,
62}
63
64impl<'a> AdmittedAcquisitionEntry<'a> {
65 pub fn bytes(&self) -> &'a [u8] { self.region.bytes() }
66 pub fn original_bytes(&self) -> &'a [u8] { self.original.bytes() }
67 pub fn digest(&self) -> [u8; 32] { self.original.digest() }
68}
69
70#[derive(Clone, Copy, Debug)]
71pub struct QacSignalWithAcquisitionSource<'a> {
72 pub signal: SignalView<'a>, pub acquisition_source: AdmittedAcquisitionEntry<'a>,
73}
74
75#[derive(Clone, Copy, Debug)]
76pub enum QacMixedEntry<'a> {
77 Signal(SignalView<'a>), Acquisition(AdmittedAcquisitionEntry<'a>),
78}
79
80fn extension<'a>(d: Block<'a>, schema: u16, ctx: &Context<'_, 'a>) -> Result<Block<'a>, BridgeError> {
81 let mut found = None;
82 for raw in meta::get(d, 18)?.value().chunks_exact(4) {
83 let block = ctx.block(u32::from_le_bytes(raw.try_into().unwrap()))?;
84 if block.schema_type() == schema {
85 if found.is_some() { return Err(BridgeError::Signal(Error::Profile)); }
86 found = Some(block);
87 }
88 }
89 found.ok_or(BridgeError::Signal(Error::Profile))
90}
91
92fn labels(s: &str, n: u32, ctx: &Context<'_, '_>) -> Result<(), BridgeError> {
93 ctx.charge_work((s.len() as u64).checked_mul(u64::from(n) + 1).ok_or(BridgeError::Overflow)?)?;
94 let mut count = 0u32;
95 for (i, label) in s.split(',').enumerate() {
96 if label.is_empty() || label.trim() != label || s.split(',').take(i).any(|old| old == label) {
97 return Err(BridgeError::Signal(Error::Profile));
98 }
99 count = count.checked_add(1).ok_or(BridgeError::Overflow)?;
100 }
101 if count != n { return Err(BridgeError::Signal(Error::Shape)); }
102 Ok(())
103}
104
105fn inspect_signal_entry<'a>(
106 index: u32, e: Entry<'a>, ctx: &Context<'_, 'a>, view: &StructuralView<'a>,
107) -> Result<SignalView<'a>, BridgeError> {
108 if e.revision() != 1 || ![0x100, 0x101, 0x104].contains(&e.mode()) {
109 return Err(BridgeError::Signal(Error::Unsupported));
110 }
111 let d = ctx.require_schema(e.descriptor_id(), 3)?;
112 for key in [9, 10, 11, 18] {
113 if meta::get(d, key)?.flags() & 1 == 0 { return Err(BridgeError::Signal(Error::Profile)); }
114 }
115 let model = meta::text(d, 12)?;
116 let scalar = Scalar::from_code(meta::u32v(d, 11)?)?;
117 let channels = meta::u32v(d, 9)?;
118 if channels == 0 { return Err(BridgeError::Signal(Error::Shape)); }
119 let shape = extension(d, 205, ctx)?;
120 if shape.revision() != 1 || meta::text(shape, 1)? != model || meta::text(shape, 2)? != "1" {
121 return Err(BridgeError::Signal(Error::Profile));
122 }
123 let dimensions = meta::get(shape, 14)?.value();
124 let n = dimensions.len() / 8;
125 let dim = |i: usize| u64::from_le_bytes(dimensions[i * 8..i * 8 + 8].try_into().unwrap());
126 let quantity = meta::text(d, 7)?;
127 let units = meta::text(d, 8)?;
128 let layout = meta::text(d, 10)?;
129 let mut timing = None;
130 let mut channel_order = "";
131 let mut purpose = "";
132 let mut relation = "";
133 let mut units_per_stored_sample = 1.0;
134 let mut stored_offset = 0.0;
135 let bins = 1;
136
137 if e.mode() == 0x104 {
138 if model != "urn:qualia:qac:opaque-original:1" || quantity != "original_bytes" || units != "1"
139 || scalar != Scalar::U8 || channels != 1 || layout != "byte" || n != 1
140 || dim(0) != e.record_count() || e.flags() & 2 != 0 || sem::field(d, 5).is_some()
141 || sem::field(d, 6).is_some() || meta::text(shape, 15)? != "byte"
142 {
143 return Err(BridgeError::Signal(Error::Profile));
144 }
145 } else {
146 if e.flags() & 2 == 0 || e.time_count() != e.record_count() {
147 return Err(BridgeError::Signal(Error::Clock));
148 }
149 let clock = ctx.require_schema(meta::u32v(d, 1)?, 1)?;
150 timing = Some(Timing {
151 scale: meta::u32v(clock, 1)?, epoch_seconds: meta::u64v(clock, 2)? as i64, epoch_nanoseconds: meta::u32v(clock, 3)?,
152 ticks: Rate::new(meta::u64v(clock, 4)?, meta::u64v(clock, 5)?)?, samples: Rate::new(meta::u64v(d, 13)?, meta::u64v(d, 14)?)?,
153 start_tick: e.start_tick(),
154 });
155 let encoding = extension(d, 210, ctx)?;
156 channel_order = meta::text(encoding, 1)?;
157 labels(channel_order, channels, ctx)?;
158 purpose = meta::text(encoding, 4)?; relation = meta::text(encoding, 5)?;
159 units_per_stored_sample = meta::f64v(encoding, 2)?; stored_offset = meta::f64v(encoding, 3)?;
160 match relation {
161 "digital-unrelated-to-pressure" => if units != "1" || !["digital_sample", "complex_digital_spectrum", "magnitude_digital_spectrum"].contains(&quantity) { return Err(BridgeError::Signal(Error::Unit)); },
162 "raw-counts" => if quantity != "raw_sample_count" || units != "1" || ![Scalar::I16, Scalar::I24, Scalar::I32].contains(&scalar) { return Err(BridgeError::Signal(Error::Unit)); },
163 "physical-base-units" => if units != "Pa" || !["pressure", "complex_pressure_spectrum", "magnitude_pressure_spectrum"].contains(&quantity) { return Err(BridgeError::Signal(Error::Unit)); },
164 _ => return Err(BridgeError::Signal(Error::Profile)),
165 }
166 if n < 2 || dim(0) != e.record_count() || dim(1) != u64::from(channels) {
167 return Err(BridgeError::Signal(Error::Shape));
168 }
169 if e.mode() == 0x100 && (n != 2 || model != "urn:qualia:qac:pcm-preservation:1" || layout != "time-channel"
170 || matches!(scalar, Scalar::ComplexF32 | Scalar::U8) || sem::field(d, 5).is_some()
171 || !["digital_sample", "raw_sample_count", "pressure"].contains(&quantity) || meta::text(shape, 15)? != "sample")
172 {
173 return Err(BridgeError::Signal(Error::Profile));
174 }
175 timing.unwrap().time_at(e.record_count().checked_sub(1).ok_or(BridgeError::Signal(Error::Shape))?)?;
176 }
177 let stride = channels.checked_mul(bins).and_then(|x| x.checked_mul(scalar.bytes())).ok_or(BridgeError::Overflow)?;
178 if stride != e.stride() || e.record_count().checked_mul(stride.into()).ok_or(BridgeError::Overflow)? != e.decoded_bytes() {
179 return Err(BridgeError::Signal(Error::Shape));
180 }
181 let payload = view.verify_chunk(index)?;
182 finite(scalar, payload)?;
183 Ok(SignalView {
184 payload, mode: e.mode(), scalar, channels, bins, records: e.record_count(),
185 stream_id: e.stream_id(), frame_id: e.frame_id(), timing, transform: None,
186 window_coefficients_le: None, channel_order, purpose, relation, quantity,
187 units, units_per_stored_sample, stored_offset,
188 })
189}
190
191fn inspect_acquisition_entry<'a>(
192 index: u32, e: Entry<'a>, ctx: &Context<'_, 'a>, view: &StructuralView<'a>, acq_limits: storage::Limits,
193) -> Result<AdmittedAcquisitionEntry<'a>, BridgeError> {
194 if e.mode() != 0x104 || e.revision() != 1 || e.flags() != 0 || e.stride() != 1 || e.frame_id() != 0 {
195 return Err(BridgeError::InvalidSourceMode);
196 }
197 let d = ctx.require_schema(e.descriptor_id(), 3)?;
198 if meta::text(d, 7)? != "original_bytes" || meta::text(d, 8)? != "1" || meta::text(d, 10)? != "byte"
199 || meta::u32v(d, 9)? != 1 || meta::u32v(d, 11)? != 7
200 {
201 return Err(BridgeError::Profile);
202 }
203 let model = meta::text(d, 12)?;
204 if model != storage::ORIGINAL_MODEL && model != "urn:qualia:qac:opaque-original:1" {
205 return Err(BridgeError::Profile);
206 }
207 let ext_field = meta::get(d, 18)?;
208 let mut view_block_id = None;
209 let mut lineage_block_id = None;
210 for raw in ext_field.value().chunks_exact(4) {
211 let bid = u32::from_le_bytes(raw.try_into().unwrap());
212 let b = ctx.block(bid)?;
213 match b.schema_type() {
214 storage::ACQUISITION_SCHEMA => {
215 if view_block_id.is_some() { return Err(BridgeError::Profile); }
216 view_block_id = Some(bid);
217 }
218 storage::DERIVATION_SCHEMA => {
219 if lineage_block_id.is_some() { return Err(BridgeError::Profile); }
220 lineage_block_id = Some(bid);
221 }
222 _ => {}
223 }
224 }
225 let b6_id = view_block_id.ok_or(BridgeError::Profile)?;
226 let b6 = ctx.block(b6_id)?;
227 let kind = meta::u32v(b6, 1)?;
228 if meta::u32v(b6, 2)? != index { return Err(BridgeError::Reference); }
229 if meta::get(b6, 3)?.value() != e.digest() { return Err(BridgeError::MismatchedSourceDigest); }
230 let offset = usize::try_from(meta::u64v(b6, 4)?).map_err(|_| BridgeError::Overflow)?;
231 let bytes = usize::try_from(meta::u64v(b6, 5)?).map_err(|_| BridgeError::Overflow)?;
232 if offset.checked_add(bytes).ok_or(BridgeError::Overflow)? as u64 > e.decoded_bytes() {
233 return Err(BridgeError::Signal(Error::Shape));
234 }
235 if let Some(b7_id) = lineage_block_id {
236 let b7 = ctx.block(b7_id)?;
237 if meta::u32v(b7, 1)? != index { return Err(BridgeError::Reference); }
238 if meta::get(b7, 2)?.value() != e.digest() { return Err(BridgeError::MismatchedSourceDigest); }
239 }
240 let payload = view.verify_chunk(index)?;
241 let original = a::Original::admit(payload, usize::try_from(acq_limits.source_bytes).map_err(|_| BridgeError::Overflow)?)?;
242 let region = original.region(offset, bytes).map_err(BridgeError::AcquisitionCore)?;
243 Ok(AdmittedAcquisitionEntry {
244 entry_index: index, original, region, kind, descriptor_id: e.descriptor_id(),
245 view_block_id: b6_id, lineage_block_id,
246 })
247}
248
249fn verify_source_lineage<'a>(
250 sig_entry_idx: u32, sig_desc: Block<'a>, ctx: &Context<'_, 'a>,
251 view: &StructuralView<'a>, acq_limits: storage::Limits,
252) -> Result<AdmittedAcquisitionEntry<'a>, BridgeError> {
253 let sources = sem::field(sig_desc, 17).ok_or(BridgeError::MissingSourceEntry)?;
254 if sources.flags() & 1 == 0 || sources.type_tag() != 9 || sources.element_count() != 1 || sources.value().len() != 4 {
255 return Err(BridgeError::MissingSourceEntry);
256 }
257 let src_idx = u32::from_le_bytes(sources.value().try_into().unwrap());
258 if src_idx == 0 || src_idx == sig_entry_idx || src_idx > view.entry_count() {
259 return Err(BridgeError::Reference);
260 }
261 let src_e = ctx.entry(src_idx)?;
262 let acq_entry = inspect_acquisition_entry(src_idx, src_e, ctx, view, acq_limits)?;
263 let prov_id = meta::u32v(sig_desc, 3)?;
264 let prov_block = ctx.require_schema(prov_id, 4)?;
265 if let Some(f2) = sem::field(prov_block, 2) {
266 if f2.value() != acq_entry.original.digest() {
267 return Err(BridgeError::MismatchedSourceDigest);
268 }
269 }
270 Ok(acq_entry)
271}
272
273pub fn admit_qac_mixed_entry<'a>(
274 view: &StructuralView<'a>, selected: u32, scratch: &mut sem::Scratch<'_>,
275 shared_limits: sem::Limits, signal_limits: Limits, acq_limits: storage::Limits,
276) -> Result<QacMixedEntry<'a>, BridgeError> {
277 if view.family() != Family::QacV1Candidate { return Err(BridgeError::UnsupportedFamily); }
278 if selected == 0 || selected > view.entry_count() { return Err(BridgeError::Index); }
279 if view.entry_count() > signal_limits.entries || view.entry_count() > acq_limits.entries {
280 return Err(BridgeError::Limit);
281 }
282 let registry = QacAcquisitionRegistry { acquisition_limits: acq_limits };
283 let admission = sem::admit_shared(view, ®istry, scratch, shared_limits)?;
284 let ctx = &admission.context;
285 let e = ctx.entry(selected)?;
286 match e.mode() {
287 0x100 | 0x101 => {
288 let sig_view = inspect_signal_entry(selected, e, ctx, view)?;
289 let d = ctx.require_schema(e.descriptor_id(), 3)?;
290 if sem::field(d, 17).is_some() {
291 let _ = verify_source_lineage(selected, d, ctx, view, acq_limits)?;
292 }
293 Ok(QacMixedEntry::Signal(sig_view))
294 }
295 0x104 => {
296 let d = ctx.require_schema(e.descriptor_id(), 3)?;
297 let is_acq = meta::get(d, 18).map_or(false, |ext| {
298 ext.value().chunks_exact(4).any(|raw| {
299 ctx.block(u32::from_le_bytes(raw.try_into().unwrap()))
300 .map_or(false, |b| b.schema_type() == storage::ACQUISITION_SCHEMA)
301 })
302 });
303 if is_acq {
304 let acq = inspect_acquisition_entry(selected, e, ctx, view, acq_limits)?;
305 Ok(QacMixedEntry::Acquisition(acq))
306 } else {
307 let sig = inspect_signal_entry(selected, e, ctx, view)?;
308 Ok(QacMixedEntry::Signal(sig))
309 }
310 }
311 _ => Err(BridgeError::InvalidSourceMode),
312 }
313}
314
315pub fn admit_qac_signal_with_acquisition_source<'a>(
316 view: &StructuralView<'a>, signal_entry_idx: u32, scratch: &mut sem::Scratch<'_>,
317 shared_limits: sem::Limits, signal_limits: Limits, acq_limits: storage::Limits,
318) -> Result<QacSignalWithAcquisitionSource<'a>, BridgeError> {
319 if view.family() != Family::QacV1Candidate { return Err(BridgeError::UnsupportedFamily); }
320 if signal_entry_idx == 0 || signal_entry_idx > view.entry_count() { return Err(BridgeError::Index); }
321 if view.entry_count() > signal_limits.entries || view.entry_count() > acq_limits.entries {
322 return Err(BridgeError::Limit);
323 }
324 let registry = QacAcquisitionRegistry { acquisition_limits: acq_limits };
325 let admission = sem::admit_shared(view, ®istry, scratch, shared_limits)?;
326 let ctx = &admission.context;
327 let e = ctx.entry(signal_entry_idx)?;
328 if ![0x100, 0x101].contains(&e.mode()) { return Err(BridgeError::InvalidSourceMode); }
329 let sig_view = inspect_signal_entry(signal_entry_idx, e, ctx, view)?;
330 let d = ctx.require_schema(e.descriptor_id(), 3)?;
331 let acq_source = verify_source_lineage(signal_entry_idx, d, ctx, view, acq_limits)?;
332 Ok(QacSignalWithAcquisitionSource { signal: sig_view, acquisition_source: acq_source })
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use super::super::test_support::*;
339 use crate::q42::field_envelope::{EntryInput, EnvelopeInput};
340
341 const RAW_BYTES: &[u8] = b"RAW_ACQ_SENSOR_STREAM_01";
342 const PCM_BYTES: &[u8] = &[0, 0, 128, 63, 0, 0, 0, 64];
343
344 fn build_fixture(
345 family: Family, corrupt_digest: bool, corrupt_schema6: bool, include_schema7: bool, corrupt_schema7: bool,
346 ) -> Vec<u8> {
347 let raw_hash = *blake3::hash(RAW_BYTES).as_bytes();
348 let prov_hash = if corrupt_digest { [0xee; 32] } else { raw_hash };
349 let s6_hash = if corrupt_schema6 { [0xff; 32] } else { raw_hash };
350
351 let mut bs = vec![
352 block(1, 1, vec![u32f(1, 0), f(2, 3, 0i64.to_le_bytes().to_vec()), u32f(3, 0), u64f(4, 48000), u64f(5, 1)]),
353 block(2, 4, vec![u32f(1, 2), f(2, 7, prov_hash.to_vec()), strf(3, "test-pcm-decoder"), strf(7, "raw-acquisition-derive")]),
354 block(3, 205, vec![
355 strf(1, "urn:qualia:qac:pcm-preservation:1"), strf(2, "1"),
356 f(14, 2, [2u64, 1u64].iter().flat_map(|x| x.to_le_bytes()).collect()), strf(15, "sample"),
357 ]),
358 block(4, 210, vec![
359 strf(1, "channel-0"), f(2, 5, 1.0f64.to_le_bytes().to_vec()), f(3, 5, 0.0f64.to_le_bytes().to_vec()),
360 strf(4, "audio"), strf(5, "digital-unrelated-to-pressure"),
361 ]),
362 block(5, 3, vec![
363 ref_f(1, 1), ref_f(3, 2), strf(7, "digital_sample"), strf(8, "1"), u32f(9, 1),
364 strf(10, "time-channel"), u32f(11, 1), strf(12, "urn:qualia:qac:pcm-preservation:1"),
365 u64f(13, 48000), u64f(14, 1), f(17, 9, 1u32.to_le_bytes().to_vec()),
366 f(18, 8, [3u32.to_le_bytes(), 4u32.to_le_bytes()].concat()),
367 ]),
368 block(11, 4, vec![u32f(1, 4)]),
369 block(12, 6, vec![
370 u32f(1, 1), f(2, 9, 1u32.to_le_bytes().to_vec()), f(3, 7, s6_hash.to_vec()),
371 u64f(4, 0), u64f(5, 24), u32f(8, 0), u32f(10, 7), u32f(11, 1), u32f(12, 0), u32f(13, 1),
372 f(14, 1, 24u32.to_le_bytes().to_vec()), f(15, 2, 1u64.to_le_bytes().to_vec()),
373 f(16, 1, 0u32.to_le_bytes().to_vec()), f(17, 2, 0u64.to_le_bytes().to_vec()),
374 u32f(32, 0),
375 ]),
376 ];
377
378 let mut desc10_ext = vec![12u32.to_le_bytes()];
379 if include_schema7 {
380 let s7_out = if corrupt_schema7 { 99u32 } else { 1u32 };
381 bs.push(block(13, 7, vec![
382 f(1, 9, s7_out.to_le_bytes().to_vec()), f(2, 7, raw_hash.to_vec()),
383 f(3, 7, [1u8; 32].to_vec()), u64f(4, 10), f(5, 7, [2u8; 32].to_vec()), u64f(6, 20),
384 f(7, 9, 1u32.to_le_bytes().to_vec()), f(8, 7, raw_hash.to_vec()), f(9, 1, 0u32.to_le_bytes().to_vec()),
385 ]));
386 desc10_ext.push(13u32.to_le_bytes());
387 }
388
389 bs.push(block(10, 3, vec![
390 ref_f(3, 11), strf(7, "original_bytes"), strf(8, "1"), u32f(9, 1), strf(10, "byte"),
391 u32f(11, 7), strf(12, storage::ORIGINAL_MODEL), f(18, 8, desc10_ext.concat()),
392 ]));
393
394 bs.sort_by_key(|b| b.id);
395 for b in &mut bs {
396 b.fields.sort_by_key(|f| f.key);
397 for fld in &mut b.fields {
398 let width = match fld.tag { 1 | 4 | 8 | 9 | 11 => 4, 2 | 3 | 5 => 8, 10 => 2, _ => 1 };
399 fld.count = (fld.bytes.len() / width) as u32;
400 }
401 }
402
403 let meta_bytes = metadata(&bs);
404 let entries = [
405 EntryInput {
406 mode: 0x104, revision: 1, flags: 0, stream_id: 0, frame_id: 0, start_tick: 0,
407 time_count: 0, spatial_key: 0, record_count: RAW_BYTES.len() as u64, stride: 1,
408 codec: 0, descriptor_id: 10, payload: RAW_BYTES,
409 },
410 EntryInput {
411 mode: 0x100, revision: 1, flags: 2, stream_id: 1, frame_id: 0, start_tick: 0,
412 time_count: 2, spatial_key: 0, record_count: 2, stride: 4, codec: 0,
413 descriptor_id: 5, payload: PCM_BYTES,
414 },
415 ];
416
417 let env_input = EnvelopeInput { family, flags: 0, metadata: &meta_bytes, entries: &entries };
418 let mut buf = vec![0u8; 16384];
419 let n = env_input.encode_into(&mut buf, env::Limits::default()).unwrap().len();
420 buf.truncate(n);
421 buf
422 }
423
424 #[test]
425 fn mixed_qac_admission_and_lineage_binding_succeeds() {
426 let data = build_fixture(Family::QacV1Candidate, false, false, false, false);
427 let view = StructuralView::open(&data, Family::QacV1Candidate, env::Limits::default()).unwrap();
428 let (mut m, mut e) = ([sem::NodeState::default(); 64], [sem::NodeState::default(); 16]);
429 let mut scratch = sem::Scratch { metadata: &mut m, entries: &mut e };
430 let result = admit_qac_signal_with_acquisition_source(
431 &view, 2, &mut scratch, sem::Limits::default(), Limits::default(), storage::Limits::default(),
432 ).unwrap();
433 assert_eq!(result.signal.mode(), 0x100);
434 assert_eq!(result.signal.records(), 2);
435 assert_eq!(result.acquisition_source.entry_index, 1);
436 assert_eq!(result.acquisition_source.original_bytes(), RAW_BYTES);
437 assert_eq!(result.acquisition_source.digest(), *blake3::hash(RAW_BYTES).as_bytes());
438 let mut scratch2 = sem::Scratch { metadata: &mut m, entries: &mut e };
439 let entry1 = admit_qac_mixed_entry(
440 &view, 1, &mut scratch2, sem::Limits::default(), Limits::default(), storage::Limits::default(),
441 ).unwrap();
442 let QacMixedEntry::Acquisition(acq) = entry1 else { panic!() };
443 assert_eq!(acq.bytes(), RAW_BYTES);
444 let mut scratch3 = sem::Scratch { metadata: &mut m, entries: &mut e };
445 let entry2 = admit_qac_mixed_entry(
446 &view, 2, &mut scratch3, sem::Limits::default(), Limits::default(), storage::Limits::default(),
447 ).unwrap();
448 let QacMixedEntry::Signal(sig) = entry2 else { panic!() };
449 assert_eq!(sig.records(), 2);
450 }
451
452 #[test]
453 fn reject_wrong_family() {
454 let data = build_fixture(Family::EmfV4Candidate, false, false, false, false);
455 let view = StructuralView::open(&data, Family::EmfV4Candidate, env::Limits::default()).unwrap();
456 let (mut m, mut e) = ([sem::NodeState::default(); 64], [sem::NodeState::default(); 16]);
457 let mut scratch = sem::Scratch { metadata: &mut m, entries: &mut e };
458 let err = admit_qac_signal_with_acquisition_source(
459 &view, 2, &mut scratch, sem::Limits::default(), Limits::default(), storage::Limits::default(),
460 ).unwrap_err();
461 assert_eq!(err, BridgeError::UnsupportedFamily);
462 }
463
464 #[test]
465 fn reject_mismatched_source_digest() {
466 let data = build_fixture(Family::QacV1Candidate, true, false, false, false);
467 let view = StructuralView::open(&data, Family::QacV1Candidate, env::Limits::default()).unwrap();
468 let (mut m, mut e) = ([sem::NodeState::default(); 64], [sem::NodeState::default(); 16]);
469 let mut scratch = sem::Scratch { metadata: &mut m, entries: &mut e };
470 let err = admit_qac_signal_with_acquisition_source(
471 &view, 2, &mut scratch, sem::Limits::default(), Limits::default(), storage::Limits::default(),
472 ).unwrap_err();
473 assert_eq!(err, BridgeError::MismatchedSourceDigest);
474 }
475
476 #[test]
477 fn reject_malformed_schema6_payload() {
478 let data = build_fixture(Family::QacV1Candidate, false, true, false, false);
479 let view = StructuralView::open(&data, Family::QacV1Candidate, env::Limits::default()).unwrap();
480 let (mut m, mut e) = ([sem::NodeState::default(); 64], [sem::NodeState::default(); 16]);
481 let mut scratch = sem::Scratch { metadata: &mut m, entries: &mut e };
482 let res = admit_qac_signal_with_acquisition_source(
483 &view, 2, &mut scratch, sem::Limits::default(), Limits::default(), storage::Limits::default(),
484 );
485 assert!(res.is_err());
486 }
487
488 #[test]
489 fn reject_malformed_schema7_payload() {
490 let data = build_fixture(Family::QacV1Candidate, false, false, true, true);
491 let view = StructuralView::open(&data, Family::QacV1Candidate, env::Limits::default()).unwrap();
492 let (mut m, mut e) = ([sem::NodeState::default(); 64], [sem::NodeState::default(); 16]);
493 let mut scratch = sem::Scratch { metadata: &mut m, entries: &mut e };
494 let res = admit_qac_signal_with_acquisition_source(
495 &view, 2, &mut scratch, sem::Limits::default(), Limits::default(), storage::Limits::default(),
496 );
497 assert!(res.is_err());
498 }
499}