Skip to main content

qualia_core_db/q42/emf_profiles/
acquisition_bridge.rs

1//! Mixed-domain EMF v4 and raw acquisition storage composition & admission bridge.
2//!
3//! Composes `ProfileRegistry` (modes `0x0100..=0x0107`, companion schemas `100..=107`, `132..=137`)
4//! with `AcquisitionRegistry` (mode `0x0104` opaque-original chunks with Schemas 6/7), closing R03 Gap #2.
5
6use super::super::field_envelope::{Block, Entry, Family, StructuralView};
7use super::super::field_semantics::{self as semantics, Context, DomainRegistry, FieldRule, Scratch};
8use super::registry::ProfileRegistry;
9use super::{field, required, scalar32, scalar64, shared_error, text, u32_at, Error, Limits, ProfileChunk};
10use crate::sensing::acquisition::storage::AcquisitionRegistry;
11
12/// Mixed-domain registry composing EMF scientific profiles with raw acquisition storage.
13#[derive(Clone, Copy, Debug)]
14pub struct EmfAcquisitionRegistry {
15    pub profiles: ProfileRegistry,
16    pub acquisition: AcquisitionRegistry,
17}
18
19impl Default for EmfAcquisitionRegistry {
20    fn default() -> Self {
21        Self {
22            profiles: ProfileRegistry,
23            acquisition: AcquisitionRegistry {
24                limits: crate::sensing::acquisition::storage::Limits::default(),
25            },
26        }
27    }
28}
29
30impl EmfAcquisitionRegistry {
31    pub const fn new(limits: crate::sensing::acquisition::storage::Limits) -> Self {
32        Self {
33            profiles: ProfileRegistry,
34            acquisition: AcquisitionRegistry { limits },
35        }
36    }
37}
38
39impl DomainRegistry for EmfAcquisitionRegistry {
40    fn rules(&self, schema: u16, revision: u16) -> Option<&'static [FieldRule]> {
41        if schema == 6 || schema == 7 { self.acquisition.rules(schema, revision) } else { self.profiles.rules(schema, revision) }
42    }
43    fn descriptor_target_schema(&self, key: u16) -> Option<u16> { self.profiles.descriptor_target_schema(key) }
44    fn validate_block(&self, block: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), semantics::Error> {
45        if block.schema_type() == 6 || block.schema_type() == 7 { self.acquisition.validate_block(block, ctx) } else { self.profiles.validate_block(block, ctx) }
46    }
47    fn validate_units(&self, units: &str, ctx: &Context<'_, '_>) -> Result<(), semantics::Error> { self.profiles.validate_units(units, ctx) }
48    fn validate_grid_frame(&self, frame: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), semantics::Error> { self.profiles.validate_grid_frame(frame, ctx) }
49    fn validate_spatial_entry(&self, entry: Entry<'_>, frame: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), semantics::Error> { self.profiles.validate_spatial_entry(entry, frame, ctx) }
50    fn validate_frame_profile(&self, frame: Block<'_>, ctx: &Context<'_, '_>) -> Result<(), semantics::Error> { self.profiles.validate_frame_profile(frame, ctx) }
51}
52
53/// A verified raw acquisition original entry (Mode `0x0104`, Schemas 6/7).
54#[derive(Clone, Copy, Debug)]
55pub struct AcquisitionOriginalEntry<'a> {
56    pub entry_index: u32,
57    pub entry: Entry<'a>,
58    pub descriptor_id: u32,
59    pub view_block: Block<'a>,
60    pub lineage_block: Option<Block<'a>>,
61    pub payload: &'a [u8],
62}
63
64impl<'a> AcquisitionOriginalEntry<'a> {
65    pub fn entry_index(&self) -> u32 { self.entry_index }
66    pub fn payload(&self) -> &'a [u8] { self.payload }
67    pub fn view_block(&self) -> Block<'a> { self.view_block }
68    pub fn lineage_block(&self) -> Option<Block<'a>> { self.lineage_block }
69    pub fn view_kind(&self) -> Result<u32, Error> { scalar32(self.view_block, 1) }
70    pub fn payload_offset(&self) -> Result<u64, Error> { scalar64(self.view_block, 4) }
71    pub fn payload_bytes(&self) -> Result<u64, Error> { scalar64(self.view_block, 5) }
72    pub fn subrange(&self) -> Result<&'a [u8], Error> {
73        let offset = usize::try_from(self.payload_offset()?).map_err(|_| Error::Overflow)?;
74        let bytes = usize::try_from(self.payload_bytes()?).map_err(|_| Error::Overflow)?;
75        let end = offset.checked_add(bytes).ok_or(Error::Overflow)?;
76        if end > self.payload.len() { return Err(Error::Shape); }
77        Ok(&self.payload[offset..end])
78    }
79}
80
81/// Admitted entry from a mixed-domain container: either typed EMF or raw acquisition original.
82#[derive(Clone, Copy, Debug)]
83pub enum AdmittedMixedEntry<'a> {
84    Emf(ProfileChunk<'a>),
85    Acquisition(AcquisitionOriginalEntry<'a>),
86}
87
88impl<'a> AdmittedMixedEntry<'a> {
89    pub fn entry_index(&self) -> u32 {
90        match self { Self::Emf(c) => c.entry_index(), Self::Acquisition(a) => a.entry_index }
91    }
92    pub fn as_emf(&self) -> Option<&ProfileChunk<'a>> {
93        match self { Self::Emf(c) => Some(c), Self::Acquisition(_) => None }
94    }
95    pub fn as_acquisition(&self) -> Option<&AcquisitionOriginalEntry<'a>> {
96        match self { Self::Emf(_) => None, Self::Acquisition(a) => Some(a) }
97    }
98}
99
100/// Mixed-domain container reader admitting both EMF profiles and acquisition originals.
101pub struct EmfMixedReader<'v, 'a> {
102    view: &'v StructuralView<'a>,
103    admission: semantics::SharedAdmission<'v, 'a>,
104    registry: EmfAcquisitionRegistry,
105    limits: Limits,
106    payload_work: u64,
107}
108
109impl<'v, 'a> EmfMixedReader<'v, 'a> {
110    pub fn view(&self) -> &'v StructuralView<'a> { self.view }
111    pub fn entry_count(&self) -> u32 { self.view.entry_count() }
112    pub fn remaining_payload_work(&self) -> u64 { self.payload_work }
113    pub fn remaining_shared_work(&self) -> u64 { self.admission.context.remaining_work() }
114    pub fn context(&self) -> &Context<'v, 'a> { &self.admission.context }
115    pub fn registry(&self) -> &EmfAcquisitionRegistry { &self.registry }
116    pub fn chunk(&mut self, entry_index: u32) -> Result<AdmittedMixedEntry<'a>, Error> {
117        let entry = self.view.entry(entry_index).map_err(Error::Storage)?;
118        let cost = entry.stored_bytes().checked_mul(3).ok_or(Error::Overflow)?;
119        self.payload_work = self.payload_work.checked_sub(cost).ok_or(Error::Limit)?;
120        admit_emf_or_acquisition_entry(self.view, &self.admission.context, entry_index, self.limits)
121    }
122}
123
124/// Open an `.emf` v4 container using the default mixed-domain registry.
125pub fn open_emf_mixed_container<'v, 'a>(
126    view: &'v StructuralView<'a>,
127    scratch: &mut Scratch<'_>,
128    limits: Limits,
129    total_payload_work: u64,
130) -> Result<EmfMixedReader<'v, 'a>, Error> {
131    open_emf_mixed_container_with_registry(view, scratch, EmfAcquisitionRegistry::default(), limits, total_payload_work)
132}
133
134/// Open an `.emf` v4 container using an explicit mixed-domain registry.
135pub fn open_emf_mixed_container_with_registry<'v, 'a>(
136    view: &'v StructuralView<'a>,
137    scratch: &mut Scratch<'_>,
138    registry: EmfAcquisitionRegistry,
139    limits: Limits,
140    total_payload_work: u64,
141) -> Result<EmfMixedReader<'v, 'a>, Error> {
142    if view.family() != Family::EmfV4Candidate { return Err(Error::UnsupportedProfile); }
143    let admission = semantics::admit_shared(view, &registry, scratch, limits.shared).map_err(shared_error)?;
144    Ok(EmfMixedReader { view, admission, registry, limits, payload_work: total_payload_work })
145}
146
147/// Admit a single entry as either a typed EMF profile chunk or an acquisition original entry.
148pub fn admit_emf_or_acquisition_entry<'v, 'a>(
149    view: &'v StructuralView<'a>,
150    context: &Context<'v, 'a>,
151    entry_index: u32,
152    limits: Limits,
153) -> Result<AdmittedMixedEntry<'a>, Error> {
154    if view.family() != Family::EmfV4Candidate { return Err(Error::UnsupportedProfile); }
155    let entry = view.entry(entry_index).map_err(Error::Storage)?;
156    if entry.record_count() > limits.records { return Err(Error::Limit); }
157    let desc = context.require_schema(entry.descriptor_id(), 3).map_err(Error::Shared)?;
158    let is_acq = entry.mode() == 0x0104
159        && field(desc, 7).and_then(|f| text(f).ok()) == Some("original_bytes")
160        && field(desc, 12).and_then(|f| text(f).ok()) == Some("urn:qualia:acquisition:original:1");
161
162    if is_acq {
163        if entry.revision() != 1 || entry.flags() != 0 || entry.stride() != 1 || entry.frame_id() != 0 {
164            return Err(Error::UnsupportedProfile);
165        }
166        let att = field(desc, 18).ok_or(Error::Descriptor)?;
167        let (mut view_block, mut lineage_block) = (None, None);
168        for raw in att.value().chunks_exact(4) {
169            let b = context.block(u32_at(raw, 0)).map_err(Error::Shared)?;
170            match b.schema_type() { 6 => view_block = Some(b), 7 => lineage_block = Some(b), _ => {} }
171        }
172        let view_block = view_block.ok_or(Error::Descriptor)?;
173        let payload = view.verify_chunk(entry_index).map_err(Error::Storage)?;
174        Ok(AdmittedMixedEntry::Acquisition(AcquisitionOriginalEntry {
175            entry_index, entry, descriptor_id: desc.id(), view_block, lineage_block, payload,
176        }))
177    } else {
178        super::chunk::admit_with_context(view, context, entry_index, limits).map(AdmittedMixedEntry::Emf)
179    }
180}
181
182/// Verify that `derived_entry_index` declares `source_entry_index` in its provenance chain with matching BLAKE3 digest.
183pub fn verify_source_entry_lineage<'v, 'a>(
184    view: &'v StructuralView<'a>,
185    context: &Context<'v, 'a>,
186    derived_entry_index: u32,
187    source_entry_index: u32,
188) -> Result<(), Error> {
189    let derived = view.entry(derived_entry_index).map_err(Error::Storage)?;
190    let source = view.entry(source_entry_index).map_err(Error::Storage)?;
191    let desc = context.require_schema(derived.descriptor_id(), 3).map_err(Error::Shared)?;
192    let prov = context.require_schema(scalar32(desc, 3)?, 4).map_err(Error::Shared)?;
193    let sources = field(desc, 17).ok_or(Error::Descriptor)?.value();
194    let digests = field(prov, 2).ok_or(Error::Descriptor)?.value();
195    if digests.len() != (sources.len() / 4).checked_mul(32).ok_or(Error::Overflow)? {
196        return Err(Error::Descriptor);
197    }
198    for (src, dig) in sources.chunks_exact(4).zip(digests.chunks_exact(32)) {
199        if u32_at(src, 0) == source_entry_index {
200            return if dig == source.digest() { Ok(()) } else { Err(Error::Validity) };
201        }
202    }
203    Err(Error::Index)
204}
205
206/// Verify derivation input binding when Schema 7 is attached to an entry.
207pub fn verify_derivation_schema7_lineage<'v, 'a>(
208    context: &Context<'v, 'a>,
209    lineage_block: Block<'a>,
210    derived_entry_index: u32,
211    source_entry_index: u32,
212) -> Result<(), Error> {
213    if lineage_block.schema_type() != 7 || lineage_block.revision() != 1 { return Err(Error::Descriptor); }
214    if scalar32(lineage_block, 1)? != derived_entry_index { return Err(Error::Descriptor); }
215    let inputs = required(lineage_block, 7)?;
216    let digests = required(lineage_block, 8)?;
217    let n = inputs.element_count() as usize;
218    if digests.value().len() != n.checked_mul(32).ok_or(Error::Overflow)? { return Err(Error::Descriptor); }
219    for (src, dig) in inputs.value().chunks_exact(4).zip(digests.value().chunks_exact(32)) {
220        if u32_at(src, 0) == source_entry_index {
221            let source_entry = context.entry(source_entry_index).map_err(Error::Shared)?;
222            return if dig == source_entry.digest() { Ok(()) } else { Err(Error::Validity) };
223        }
224    }
225    Err(Error::Index)
226}
227
228/// Encode a calibrated RF I/Q acquisition packet (`0x0105`) into a self-admitted `.emf` v4 envelope.
229#[allow(clippy::too_many_arguments)]
230pub fn acquire_iq_to_emf<'out>(
231    clock: super::FieldClock, frame: super::FieldFrame, provenance: super::FieldProvenance<'_>,
232    header: &super::IqHeader, samples: &[(f64, f64)], acquisition: super::AcquisitionSpec<'_>,
233    calibration: super::CalibrationSpec<'_>, payload_buf: &mut [u8], meta_buf: &mut [u8],
234    staging: &mut [u8], output: &'out mut [u8], scratch: &mut Scratch<'_>, limits: super::FieldWriteLimits,
235) -> Result<&'out mut [u8], Error> {
236    let n = super::encode_iq_packet(header, samples, true, payload_buf)?;
237    let spec = super::ExtendedModeSpec::Iq { acquisition, calibration, samples_per_packet: header.sample_count };
238    super::write_extended_envelope(
239        clock, frame, provenance, 0x0105, Some(i64::from(header.sample_count)),
240        header.first_sample_tick, 1, None, 1, &payload_buf[..n], &spec, meta_buf, staging, output, scratch, limits,
241    )
242}
243
244/// Encode bioelectric current-dipole records (`0x0107`) into a self-admitted `.emf` v4 envelope.
245#[allow(clippy::too_many_arguments)]
246pub fn acquire_biofield_to_emf<'out>(
247    clock: super::FieldClock, frame: super::FieldFrame, provenance: super::FieldProvenance<'_>,
248    records: &[super::BiofieldRecord], temporal_step_ticks: Option<i64>, start_tick: i64,
249    bio: super::BioContextSpec<'_>, evidence: super::ModelEvidenceSpec<'_>, calibration: super::CalibrationSpec<'_>,
250    payload_buf: &mut [u8], meta_buf: &mut [u8], staging: &mut [u8], output: &'out mut [u8],
251    scratch: &mut Scratch<'_>, limits: super::FieldWriteLimits,
252) -> Result<&'out mut [u8], Error> {
253    let n = super::encode_biofield_records(records, None, payload_buf)?;
254    let spec = super::ExtendedModeSpec::Biofield { bio, evidence, calibration };
255    let count = records.len() as u64;
256    super::write_extended_envelope(
257        clock, frame, provenance, 0x0107, temporal_step_ticks, start_tick,
258        if temporal_step_ticks.is_some() { count } else { 0 }, None, count, &payload_buf[..n],
259        &spec, meta_buf, staging, output, scratch, limits,
260    )
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use super::super::{FIELD_MODEL_URI, FIELD_PROFILE};
267    use crate::q42::field_envelope::{EntryInput, EnvelopeInput, Limits as StoreLimits};
268
269    #[derive(Clone)]
270    struct TestBlock { id: u32, schema: u16, fields: Vec<Vec<u8>> }
271
272    fn f(key: u16, tag: u8, count: u32, bytes: &[u8]) -> Vec<u8> {
273        let mut v = Vec::with_capacity(16 + bytes.len() + 8);
274        v.extend_from_slice(&key.to_le_bytes());
275        v.push(tag);
276        v.push(1);
277        v.extend_from_slice(&count.to_le_bytes());
278        v.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
279        v.extend_from_slice(&0u32.to_le_bytes());
280        v.extend_from_slice(bytes);
281        while v.len() % 8 != 0 { v.push(0); }
282        v
283    }
284    fn n32(key: u16, n: u32) -> Vec<u8> { f(key, 1, 1, &n.to_le_bytes()) }
285    fn n64(key: u16, n: u64) -> Vec<u8> { f(key, 2, 1, &n.to_le_bytes()) }
286    fn s(key: u16, text: &str) -> Vec<u8> { f(key, 6, text.len() as u32, text.as_bytes()) }
287    fn numbers(key: u16, vals: &[f64]) -> Vec<u8> {
288        f(key, 5, vals.len() as u32, &vals.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>())
289    }
290
291    fn encode_test_container(blocks: &[TestBlock], entries: &[EntryInput<'_>]) -> Vec<u8> {
292        let mut sorted = blocks.to_vec();
293        sorted.sort_by_key(|b| b.id);
294        let mut bytes = Vec::new();
295        for m in &sorted {
296            let mut fields = m.fields.clone();
297            fields.sort_by_key(|v| u16::from_le_bytes(v[..2].try_into().unwrap()));
298            let body = fields.concat();
299            bytes.extend_from_slice(&m.id.to_le_bytes());
300            bytes.extend_from_slice(&m.schema.to_le_bytes());
301            bytes.extend_from_slice(&1u16.to_le_bytes());
302            bytes.extend_from_slice(&(body.len() as u32).to_le_bytes());
303            bytes.extend_from_slice(&1u32.to_le_bytes());
304            bytes.extend_from_slice(&body);
305        }
306        let input = EnvelopeInput { family: Family::EmfV4Candidate, flags: 0, metadata: &bytes, entries };
307        let mut out = vec![0; input.encoded_len(StoreLimits::default()).unwrap()];
308        input.encode_into(&mut out, StoreLimits::default()).unwrap();
309        out
310    }
311
312    fn base_mixed_fixture() -> (Vec<TestBlock>, Vec<u8>, Vec<u8>) {
313        let acq_payload = b"TEST-ACQUISITION-RAW-SENSOR-BYTES-PACKET-DATA-E01-BRIDGE-42-ABCD";
314        let acq_digest = *blake3::hash(acq_payload).as_bytes();
315        let mut emf_payload = vec![0u8; 128];
316        emf_payload[0..8].copy_from_slice(&1.0f64.to_le_bytes());
317        emf_payload[32..40].copy_from_slice(&(1.0f64 / 299_792_458.0).to_le_bytes());
318
319        let blocks = vec![
320            TestBlock { id: 1, schema: 1, fields: vec![n32(1, 0), f(2, 3, 1, &0i64.to_le_bytes()), n32(3, 0), n64(4, 1000), n64(5, 1)] },
321            TestBlock { id: 2, schema: 2, fields: vec![n32(1, 0), numbers(3, &[0.0; 3]), numbers(4, &[0.0, 0.0, 0.0, 1.0]), s(8, "right-handed-X-forward-Y-left-Z-up")] },
322            TestBlock { id: 11, schema: 4, fields: vec![n32(1, 4)] },
323            TestBlock { id: 20, schema: 6, fields: vec![
324                n32(1, 1), f(2, 9, 1, &1u32.to_le_bytes()), f(3, 7, 32, &acq_digest),
325                n64(4, 0), n64(5, 64), n32(8, 0), n32(10, 7), n32(11, 0), n32(12, 0), n32(13, 1),
326                f(14, 1, 1, &64u32.to_le_bytes()), f(15, 2, 1, &1u64.to_le_bytes()), f(16, 1, 1, &0u32.to_le_bytes()),
327                f(17, 2, 1, &0u64.to_le_bytes()), n32(32, 0),
328            ] },
329            TestBlock { id: 10, schema: 3, fields: vec![
330                f(3, 8, 1, &11u32.to_le_bytes()), s(7, "original_bytes"), s(8, "1"), n32(9, 1), s(10, "byte"),
331                n32(11, 7), s(12, "urn:qualia:acquisition:original:1"), f(18, 8, 1, &20u32.to_le_bytes()),
332            ] },
333            TestBlock { id: 31, schema: 4, fields: vec![n32(1, 2), f(2, 7, 32, &acq_digest)] },
334            TestBlock { id: 4, schema: 103, fields: vec![
335                n32(1, 0x0100), n32(2, 1), f(3, 8, 1, &1u32.to_le_bytes()), f(4, 8, 1, &2u32.to_le_bytes()),
336                f(5, 8, 1, &31u32.to_le_bytes()), s(6, FIELD_PROFILE), s(7, "linear"),
337                f(8, 2, 3, &[1u64, 1, 1].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()),
338                f(9, 1, 3, &[1u32, 1, 1].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>()),
339                n32(10, 0), f(11, 3, 1, &0i64.to_le_bytes()),
340            ] },
341            TestBlock { id: 30, schema: 3, fields: vec![
342                f(2, 8, 1, &2u32.to_le_bytes()), f(3, 8, 1, &31u32.to_le_bytes()), s(7, "electromagnetic_field_snapshot"),
343                s(8, "mixed:mode-registry"), s(12, FIELD_MODEL_URI), f(17, 9, 1, &1u32.to_le_bytes()), f(18, 8, 1, &4u32.to_le_bytes()),
344            ] },
345        ];
346        (blocks, acq_payload.to_vec(), emf_payload)
347    }
348
349    fn make_entries<'a>(acq: &'a [u8], emf: &'a [u8]) -> [EntryInput<'a>; 2] {
350        [
351            EntryInput { mode: 0x0104, revision: 1, flags: 0, stream_id: 1, frame_id: 0, start_tick: 0, time_count: 0, spatial_key: 0, record_count: acq.len() as u64, stride: 1, codec: 0, descriptor_id: 10, payload: acq },
352            EntryInput { mode: 0x0100, revision: 1, flags: 0, stream_id: 2, frame_id: 2, start_tick: 0, time_count: 0, spatial_key: 0, record_count: 1, stride: 128, codec: 0, descriptor_id: 30, payload: emf },
353        ]
354    }
355
356    #[test]
357    fn test_mixed_domain_positive_admission() {
358        let (blocks, acq, emf) = base_mixed_fixture();
359        let entries = make_entries(&acq, &emf);
360        let bytes = encode_test_container(&blocks, &entries);
361        let view = StructuralView::open(&bytes, Family::EmfV4Candidate, StoreLimits::default()).unwrap();
362        let mut m_nodes = [semantics::NodeState::default(); 64];
363        let mut e_nodes = [semantics::NodeState::default(); 16];
364        let mut scratch = Scratch { metadata: &mut m_nodes, entries: &mut e_nodes };
365        let mut reader = open_emf_mixed_container(&view, &mut scratch, Limits::default(), 10_000_000).unwrap();
366        assert_eq!(reader.entry_count(), 2);
367
368        let chunk1 = reader.chunk(1).unwrap();
369        let acq_entry = chunk1.as_acquisition().expect("expected acquisition original");
370        assert_eq!(acq_entry.entry_index(), 1);
371        assert_eq!(acq_entry.payload(), acq.as_slice());
372        assert_eq!(acq_entry.view_kind().unwrap(), 1);
373        assert_eq!(acq_entry.subrange().unwrap(), acq.as_slice());
374
375        let chunk2 = reader.chunk(2).unwrap();
376        let emf_chunk = chunk2.as_emf().expect("expected emf chunk");
377        assert_eq!(emf_chunk.entry_index(), 2);
378        assert_eq!(emf_chunk.canonical_mode(), 0x0100);
379        assert!(emf_chunk.field(0).unwrap().is_some());
380
381        verify_source_entry_lineage(&view, reader.context(), 2, 1).unwrap();
382    }
383
384    #[test]
385    fn test_mixed_domain_malformed_schema6_rejected() {
386        let (mut blocks, acq, emf) = base_mixed_fixture();
387        let entries = make_entries(&acq, &emf);
388        for b in &mut blocks {
389            if b.id == 20 {
390                for field in &mut b.fields {
391                    if u16::from_le_bytes(field[..2].try_into().unwrap()) == 5 { *field = n64(5, 9999); }
392                }
393            }
394        }
395        let bytes = encode_test_container(&blocks, &entries);
396        let view = StructuralView::open(&bytes, Family::EmfV4Candidate, StoreLimits::default()).unwrap();
397        let mut m = [semantics::NodeState::default(); 64];
398        let mut e = [semantics::NodeState::default(); 16];
399        let mut scratch = Scratch { metadata: &mut m, entries: &mut e };
400        assert!(open_emf_mixed_container(&view, &mut scratch, Limits::default(), 10_000_000).is_err());
401    }
402
403    #[test]
404    fn test_mixed_domain_malformed_schema7_rejected() {
405        let (mut blocks, acq, emf) = base_mixed_fixture();
406        blocks.push(TestBlock {
407            id: 25, schema: 7,
408            fields: vec![
409                f(1, 9, 1, &1u32.to_le_bytes()), f(2, 7, 32, &blake3::hash(&acq).as_bytes()[..]),
410                f(3, 7, 32, &[0u8; 32]), n64(4, 1), f(5, 7, 32, &[0u8; 32]), n64(6, 2),
411                f(7, 9, 1, &1u32.to_le_bytes()), f(8, 7, 32, &blake3::hash(&acq).as_bytes()[..]),
412                f(9, 1, 1, &0u32.to_le_bytes()),
413            ],
414        });
415        for b in &mut blocks {
416            if b.id == 10 {
417                for field in &mut b.fields {
418                    if u16::from_le_bytes(field[..2].try_into().unwrap()) == 18 {
419                        *field = f(18, 8, 2, &[20u32, 25].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
420                    }
421                }
422            }
423        }
424        let entries = make_entries(&acq, &emf);
425        let bytes = encode_test_container(&blocks, &entries);
426        let view = StructuralView::open(&bytes, Family::EmfV4Candidate, StoreLimits::default()).unwrap();
427        let mut m = [semantics::NodeState::default(); 64];
428        let mut e = [semantics::NodeState::default(); 16];
429        let mut scratch = Scratch { metadata: &mut m, entries: &mut e };
430        assert!(open_emf_mixed_container(&view, &mut scratch, Limits::default(), 10_000_000).is_err());
431    }
432
433    #[test]
434    fn test_mixed_domain_non_0104_claiming_schema6_rejected() {
435        let (mut blocks, acq, emf) = base_mixed_fixture();
436        for b in &mut blocks {
437            if b.id == 20 {
438                for field in &mut b.fields {
439                    if u16::from_le_bytes(field[..2].try_into().unwrap()) == 2 { *field = f(2, 9, 1, &2u32.to_le_bytes()); }
440                }
441            }
442        }
443        let entries = make_entries(&acq, &emf);
444        let bytes = encode_test_container(&blocks, &entries);
445        let view = StructuralView::open(&bytes, Family::EmfV4Candidate, StoreLimits::default()).unwrap();
446        let mut m = [semantics::NodeState::default(); 64];
447        let mut e = [semantics::NodeState::default(); 16];
448        let mut scratch = Scratch { metadata: &mut m, entries: &mut e };
449        assert!(open_emf_mixed_container(&view, &mut scratch, Limits::default(), 10_000_000).is_err());
450    }
451
452    #[test]
453    fn test_mixed_domain_mismatched_source_digest_rejected() {
454        let (mut blocks, acq, emf) = base_mixed_fixture();
455        let bad_digest = [0x55u8; 32];
456        for b in &mut blocks {
457            if b.id == 31 {
458                for field in &mut b.fields {
459                    if u16::from_le_bytes(field[..2].try_into().unwrap()) == 2 { *field = f(2, 7, 32, &bad_digest); }
460                }
461            }
462        }
463        let entries = make_entries(&acq, &emf);
464        let bytes = encode_test_container(&blocks, &entries);
465        let view = StructuralView::open(&bytes, Family::EmfV4Candidate, StoreLimits::default()).unwrap();
466        let mut m = [semantics::NodeState::default(); 64];
467        let mut e = [semantics::NodeState::default(); 16];
468        let mut scratch = Scratch { metadata: &mut m, entries: &mut e };
469        assert!(open_emf_mixed_container(&view, &mut scratch, Limits::default(), 10_000_000).is_err());
470    }
471}