1use crate::bundle::stream::descriptor::{
4 CandidateIdentity, ContextParameters, DescriptorError, EntryRecord, PageRef,
5 HASH_SCRATCH_BYTES, MAX_ENCODED, MAX_METADATA, MAX_PAGES,
6};
7use crate::bundle::stream::index::{AdmittedIndex, EntryScratch};
8use crate::bundle::stream::plan::{
9 DependencyEdge, DependencyReason, EntryFamily, Inventory, Obligation, PlanEntry, PlanEntrySpec,
10 PlanError, RepresentationClass, ResourceEstimate, MAX_PLAN_ENTRIES,
11};
12use crate::bundle::stream::policy::{
13 authenticate_closure, encode_manifest_into, BoundClosure, LocalGrantRequest, ManifestFields,
14 PolicyError, PublicationProof, CLOSURE_PURPOSE, MAX_MANIFEST_BYTES, PUBLICATION_PURPOSE,
15};
16use crate::bundle::stream::publish::{
17 EntryAssignment, PlainPublisher, PublicationClass, PublisherOptions,
18};
19use crate::bundle::stream::selection::{select_entry, SelectedPlainEntry, SelectionError};
20use crate::bundle::{BundleError, BundleReadLimits, BundleWriter};
21use crate::crypto::network::{
22 authority::{LocalBootstrap, PinAuthority, PinConfig, PinHandle},
23 cose,
24 digest::sha384,
25 types::{KeyEpoch, KeyPurpose},
26};
27use crate::net::qdnf::types::{OperationId, StrongDigest};
28use crate::semantic_instruments::resolve::{bounded_closure::*, DependencyKind};
29use ed25519_dalek::SigningKey;
30use fips204::{
31 ml_dsa_65,
32 traits::{KeyGen, SerDes},
33};
34
35pub const MIXED_ID_TEND_A: u32 = 1;
37pub const MIXED_ID_TEND_B: u32 = 2;
38pub const MIXED_ID_EMF_OPAQUE: u32 = 10;
39pub const MIXED_ID_EMF_ALIGN: u32 = 11;
40pub const MIXED_ID_QAC_OPAQUE: u32 = 20;
41pub const MIXED_ID_QAC_PCM: u32 = 21;
42pub const MIXED_ID_Q42: u32 = 30;
43pub const MIXED_ID_M64: u32 = 40;
44pub const MIXED_ID_P64: u32 = 41;
45pub const MIXED_ID_OPAQUE: u32 = 50;
46pub const MIXED_OPAQUE_BYTES: &[u8] = b"qbdl-mixed-opaque-v1";
48
49#[derive(Clone, Copy)]
51pub struct MixedEntry<'a> {
52 pub id: u32,
53 pub family: EntryFamily,
54 pub role: RepresentationClass,
55 pub obligation: Obligation,
56 pub bytes: &'a [u8],
57}
58
59pub struct MixedHmc {
61 source: Vec<u8>,
62 body: Vec<u8>,
63 entry_page: Vec<u8>,
64 identity: CandidateIdentity,
65 ids: [u32; MAX_PLAN_ENTRIES],
66 families: [EntryFamily; MAX_PLAN_ENTRIES],
67 roles: [RepresentationClass; MAX_PLAN_ENTRIES],
68 obligations: [Obligation; MAX_PLAN_ENTRIES],
69 payloads: Vec<Vec<u8>>,
70 len: usize,
71 nodes: [ClosureNode<'static>; 3],
72 edges: [ClosureEdge; 2],
73 fields: ManifestFields,
74 manifest: Vec<u8>,
75 ml_sk: ml_dsa_65::PrivateKey,
76 ml_pk: [u8; 1952],
77 ed_sk: SigningKey,
78 ed_pk: [u8; 32],
79}
80
81pub struct MixedPlan {
83 candidate: CandidateIdentity,
84 entries: Vec<PlanEntry>,
85 edges: Vec<DependencyEdge>,
86 geometry_id: Option<u32>,
87 calibration_id: Option<u32>,
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub enum MixedError {
92 DuplicateId,
93 Limit,
94 Identity,
95 Unsupported,
96}
97
98impl core::fmt::Display for MixedError {
99 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
100 write!(f, "mixed {:?}", self)
101 }
102}
103impl core::error::Error for MixedError {}
104
105impl From<DescriptorError> for MixedError {
106 fn from(e: DescriptorError) -> Self {
107 match e {
108 DescriptorError::DuplicateId => Self::DuplicateId,
109 DescriptorError::Capacity
110 | DescriptorError::Limit
111 | DescriptorError::Overflow
112 | DescriptorError::Length => Self::Limit,
113 DescriptorError::Unsupported => Self::Unsupported,
114 _ => Self::Identity,
115 }
116 }
117}
118
119impl From<PolicyError> for MixedError {
120 fn from(e: PolicyError) -> Self {
121 match e {
122 PolicyError::Capacity | PolicyError::Limit => Self::Limit,
123 PolicyError::Encoding => Self::Unsupported,
124 _ => Self::Identity,
125 }
126 }
127}
128
129impl From<PlanError> for MixedError {
130 fn from(e: PlanError) -> Self {
131 match e {
132 PlanError::DuplicateId => Self::DuplicateId,
133 PlanError::Capacity | PlanError::Limit => Self::Limit,
134 PlanError::Unsupported | PlanError::Field | PlanError::Refused => Self::Unsupported,
135 PlanError::Identity | PlanError::Cycle | PlanError::Graph => Self::Identity,
136 }
137 }
138}
139
140impl From<BundleError> for MixedError {
141 fn from(e: BundleError) -> Self {
142 match e {
143 BundleError::DuplicateKey(_) => Self::DuplicateId,
144 BundleError::EmptyKey
145 | BundleError::TooShort
146 | BundleError::LengthMismatch { .. }
147 | BundleError::BadIndexPointer { .. }
148 | BundleError::EntryOutOfBounds { .. }
149 | BundleError::UnpageAligned { .. }
150 | BundleError::Cbor(_)
151 | BundleError::Io(_) => Self::Limit,
152 BundleError::BadMagic
153 | BundleError::UnsupportedVersion(_)
154 | BundleError::CrcMismatch { .. } => Self::Unsupported,
155 }
156 }
157}
158
159impl From<SelectionError> for MixedError {
160 fn from(_: SelectionError) -> Self {
161 Self::Identity
162 }
163}
164
165fn kind_of(family: EntryFamily) -> &'static str {
166 match family {
167 EntryFamily::TenD => "10d",
168 EntryFamily::Q42 => "q42",
169 EntryFamily::Emf => "emf",
170 EntryFamily::Qac => "qac",
171 EntryFamily::M64 => "m64",
172 EntryFamily::P64 => "p64",
173 EntryFamily::Opaque => "blob",
174 }
175}
176
177pub fn publish_mixed(entries: &[MixedEntry<'_>]) -> Result<MixedHmc, MixedError> {
180 if entries.is_empty() || entries.len() > MAX_PLAN_ENTRIES {
181 return Err(MixedError::Limit);
182 }
183 for (i, entry) in entries.iter().enumerate() {
184 if entry.id == 0 {
185 return Err(MixedError::Identity);
186 }
187 if entry.bytes.is_empty() {
188 return Err(MixedError::Limit);
189 }
190 for prior in &entries[..i] {
191 if prior.id == entry.id {
192 return Err(MixedError::DuplicateId);
193 }
194 }
195 }
196 let nodes = [
197 ClosureNode {
198 digest: sha384(b"root"),
199 kind: DependencyKind::Instrument,
200 original_bytes: b"root",
201 },
202 ClosureNode {
203 digest: sha384(b"policy"),
204 kind: DependencyKind::LawPackage,
205 original_bytes: b"policy",
206 },
207 ClosureNode {
208 digest: sha384(b"consumer"),
209 kind: DependencyKind::NativeModule,
210 original_bytes: b"consumer",
211 },
212 ];
213 let edges = [
214 ClosureEdge {
215 dependent: nodes[0].digest,
216 dependency: nodes[1].digest,
217 },
218 ClosureEdge {
219 dependent: nodes[0].digest,
220 dependency: nodes[2].digest,
221 },
222 ];
223 let mut writer = BundleWriter::new();
224 let mut payloads = Vec::with_capacity(entries.len());
225 for entry in entries {
226 payloads.push(entry.bytes.to_vec());
227 let key = format!("entry-{}", entry.id);
228 writer.add_file(key, kind_of(entry.family), entry.bytes.to_vec(), None)?;
229 }
230 let source = writer.build()?;
231 let fields = ManifestFields {
232 source: sha384(&source),
233 source_length: source.len() as u64,
234 semantic_root: nodes[0].digest,
235 policy: nodes[1].digest,
236 consumer: nodes[2].digest,
237 issuer: StrongDigest([31; 48]),
238 };
239 let candidate = verify_closure(nodes[0].digest, &nodes, &edges).map_err(|_| MixedError::Identity)?;
240 let mut manifest = vec![0; MAX_MANIFEST_BYTES];
241 let n = encode_manifest_into(fields, &candidate, &mut manifest)?;
242 manifest.truncate(n);
243 let parameters = ContextParameters {
244 nonce: [1; 32],
245 generation: 0,
246 predecessor: None,
247 semantic_contract: sha384(&manifest),
248 policy: fields.policy,
249 consumer_profile: fields.consumer,
250 };
251 let n_entries = entries.len();
252 let mut assignments = [EntryAssignment {
253 id: 0,
254 inner_version: 1,
255 }; MAX_PLAN_ENTRIES];
256 for (i, entry) in entries.iter().enumerate() {
257 assignments[i] = EntryAssignment {
258 id: entry.id,
259 inner_version: 1,
260 };
261 }
262 let mut index = [EntryScratch::EMPTY; MAX_PLAN_ENTRIES];
263 let mut ids_scratch = [0u32; MAX_PLAN_ENTRIES];
264 let mut context_refs = [PageRef::EMPTY; MAX_PAGES];
265 let mut entry_refs = [PageRef::EMPTY; MAX_PAGES];
266 let mut publisher = PlainPublisher::prepare(
267 &source,
268 BundleReadLimits::default(),
269 &assignments[..n_entries],
270 PublisherOptions {
271 parameters,
272 class: PublicationClass::PlainCandidate,
273 metadata_limit: MAX_METADATA,
274 },
275 &mut index[..n_entries],
276 &mut ids_scratch[..n_entries],
277 &mut context_refs,
278 &mut entry_refs,
279 )?;
280 let mut output = vec![0; MAX_ENCODED];
281 let mut scratch = vec![0; HASH_SCRATCH_BYTES];
282 for page in 0..publisher.page_count() {
283 publisher.emit_context_page(page, &mut output, &mut scratch, |_, _| Ok(()))?;
284 }
285 let n = publisher.encode_context_root(&mut output, &mut scratch)?;
286 let context = output[..n].to_vec();
287 let mut entry_page = Vec::new();
288 for page in 0..publisher.page_count() {
289 publisher.emit_entry_page(
290 page,
291 &mut output,
292 &mut scratch,
293 |_, _| Ok(()),
294 |bytes, _| {
295 entry_page = bytes.to_vec();
296 Ok(())
297 },
298 )?;
299 }
300 let identity = publisher.finish(&context, &mut output, &mut scratch)?;
301 let n = publisher.body_encoded_length(&context)?;
302 let body = output[..n].to_vec();
303 drop(publisher);
304 let (ml_pk, ml_sk) = ml_dsa_65::KG::keygen_from_seed(&[71; 32]);
305 let ed_sk = SigningKey::from_bytes(&[72; 32]);
306 let ed_pk = ed_sk.verifying_key().to_bytes();
307 let mut ids = [0u32; MAX_PLAN_ENTRIES];
308 let mut families = [EntryFamily::Opaque; MAX_PLAN_ENTRIES];
309 let mut roles = [RepresentationClass::Enhancement; MAX_PLAN_ENTRIES];
310 let mut obligations = [Obligation::Optional; MAX_PLAN_ENTRIES];
311 for (i, entry) in entries.iter().enumerate() {
312 ids[i] = entry.id;
313 families[i] = entry.family;
314 roles[i] = entry.role;
315 obligations[i] = entry.obligation;
316 }
317 Ok(MixedHmc {
318 source,
319 body,
320 entry_page,
321 identity,
322 ids,
323 families,
324 roles,
325 obligations,
326 payloads,
327 len: n_entries,
328 nodes,
329 edges,
330 fields,
331 manifest,
332 ml_sk,
333 ml_pk: ml_pk.into_bytes(),
334 ed_sk,
335 ed_pk,
336 })
337}
338
339impl MixedHmc {
340 pub fn source(&self) -> &[u8] {
341 &self.source
342 }
343 pub fn body(&self) -> &[u8] {
344 &self.body
345 }
346 pub fn entry_page(&self) -> &[u8] {
347 &self.entry_page
348 }
349 pub fn identity(&self) -> CandidateIdentity {
350 self.identity
351 }
352 pub fn entry_id(&self, i: usize) -> u32 {
353 self.ids[..self.len][i]
354 }
355 pub fn family(&self, i: usize) -> EntryFamily {
356 self.families[..self.len][i]
357 }
358 pub fn role(&self, i: usize) -> RepresentationClass {
359 self.roles[..self.len][i]
360 }
361 pub fn obligation(&self, i: usize) -> Obligation {
362 self.obligations[..self.len][i]
363 }
364 pub fn payload(&self, i: usize) -> &[u8] {
366 &self.payloads[i]
367 }
368 pub fn len(&self) -> usize {
369 self.len
370 }
371 pub fn is_empty(&self) -> bool {
372 self.len == 0
373 }
374 pub fn index_of(&self, id: u32) -> Option<usize> {
375 self.ids[..self.len].iter().position(|x| *x == id)
376 }
377 fn keys(&self) -> cose::PairedPublicKeys<'_> {
378 cose::PairedPublicKeys {
379 ml_dsa_65: &self.ml_pk,
380 ed25519: &self.ed_pk,
381 }
382 }
383 pub fn installed(
385 &self,
386 purpose: &[u8],
387 ) -> Result<(PinAuthority, LocalBootstrap, PinHandle, PinHandle), MixedError> {
388 let (mut pins, admin) =
389 PinAuthority::new_local_bootstrap().map_err(|_| MixedError::Identity)?;
390 let handle = pins
391 .install_pin(
392 &admin,
393 PinConfig {
394 principal: self.fields.issuer,
395 provider_epoch: KeyEpoch {
396 controller: 7,
397 epoch: 1,
398 purpose: KeyPurpose::ControllerSign,
399 },
400 keys: self.keys(),
401 purpose,
402 audience: b"reader",
403 not_before_unix: 10,
404 expires_unix: 100,
405 },
406 10,
407 )
408 .map_err(|_| MixedError::Identity)?;
409 let publisher = pins
410 .install_pin(
411 &admin,
412 PinConfig {
413 principal: self.fields.issuer,
414 provider_epoch: KeyEpoch {
415 controller: 7,
416 epoch: 1,
417 purpose: KeyPurpose::ControllerSign,
418 },
419 keys: self.keys(),
420 purpose: PUBLICATION_PURPOSE,
421 audience: b"reader",
422 not_before_unix: 10,
423 expires_unix: 100,
424 },
425 10,
426 )
427 .map_err(|_| MixedError::Identity)?;
428 Ok((pins, admin, handle, publisher))
429 }
430 fn signed_digest(&self, digest: StrongDigest, purpose: &[u8]) -> Result<Vec<u8>, MixedError> {
431 let binding = cose::Binding {
432 descriptor_digest: &digest.0,
433 key_ids: self.keys().key_ids(),
434 controller_epoch: 1,
435 purpose,
436 audience: b"reader",
437 };
438 let keys = cose::SigningKeys {
439 ml_dsa_65: &self.ml_sk,
440 ed25519: &self.ed_sk,
441 };
442 let mut out = vec![0; cose::MAX_ENVELOPE_BYTES];
443 let n = cose::sign_pair_raw(&binding, &keys, &mut cose::Workspace::new(), &mut out)
444 .map_err(|_| MixedError::Identity)?;
445 out.truncate(n);
446 Ok(out)
447 }
448 fn authenticated<'a>(
449 &'a self,
450 pins: &PinAuthority,
451 pin: PinHandle,
452 now: u64,
453 ) -> Result<crate::bundle::stream::policy::AuthenticatedClosure<'a>, MixedError> {
454 let candidate = verify_closure(self.fields.semantic_root, &self.nodes, &self.edges)
455 .map_err(|_| MixedError::Identity)?;
456 let signed = self.signed_digest(sha384(&self.manifest), CLOSURE_PURPOSE)?;
457 Ok(authenticate_closure(
458 candidate,
459 &self.manifest,
460 pins,
461 pin,
462 self.keys().key_ids(),
463 1,
464 b"reader",
465 &signed,
466 now,
467 &mut cose::Workspace::new(),
468 )?)
469 }
470 pub fn bound<'a>(
472 &'a self,
473 pins: &PinAuthority,
474 pin: PinHandle,
475 publisher: PinHandle,
476 ) -> Result<BoundClosure<'a>, MixedError> {
477 let envelope = self.signed_digest(self.identity.descriptor_id(), PUBLICATION_PURPOSE)?;
478 Ok(self.authenticated(pins, pin, 10)?.bind_descriptor(
479 self.identity,
480 &self.body,
481 &mut vec![0; HASH_SCRATCH_BYTES],
482 pins,
483 self.publication(publisher, &envelope),
484 10,
485 &mut cose::Workspace::new(),
486 )?)
487 }
488 fn publication<'a>(&self, pin: PinHandle, envelope: &'a [u8]) -> PublicationProof<'a> {
489 PublicationProof {
490 pin,
491 key_ids: self.keys().key_ids(),
492 epoch: 1,
493 audience: b"reader",
494 envelope,
495 }
496 }
497 pub fn request(&self) -> LocalGrantRequest {
498 LocalGrantRequest {
499 principal: StrongDigest([41; 48]),
500 recipient: StrongDigest([42; 48]),
501 purpose: sha384(b"local-read"),
502 operation: OperationId([1; 16]),
503 not_before: 10,
504 expires: 90,
505 resource_ceiling: self.fields.source_length,
506 }
507 }
508 pub fn select<'p>(
510 &'p self,
511 bound: &BoundClosure<'_>,
512 ordinal: u32,
513 index: &AdmittedIndex<'_>,
514 rows: &mut [EntryRecord<'p>],
515 framing: &mut [u8],
516 ) -> Result<SelectedPlainEntry<'p>, MixedError> {
517 Ok(select_entry(
518 bound,
519 self.body(),
520 &self.source()[..64],
521 index,
522 self.entry_page(),
523 ordinal,
524 rows,
525 framing,
526 )?)
527 }
528}
529
530pub fn mixed_plan(hmc: &MixedHmc) -> Result<MixedPlan, MixedError> {
534 if hmc.is_empty() {
535 return Err(MixedError::Limit);
536 }
537 let candidate = hmc.identity();
538 let mut entries = Vec::with_capacity(hmc.len());
539 for i in 0..hmc.len() {
540 entries.push(PlanEntry::new(PlanEntrySpec {
541 candidate,
542 entry_id: hmc.entry_id(i),
543 family: hmc.family(i),
544 role: hmc.role(i),
545 interval: None,
546 timebase: None,
547 estimate: ResourceEstimate::new(hmc.payload(i).len() as u64, 1, 1),
548 obligation: hmc.obligation(i),
549 })?);
550 }
551 let geometry_id = entries
552 .iter()
553 .find(|e| e.family() == EntryFamily::TenD)
554 .map(|e| e.entry_id());
555 let calibration_id = entries
556 .iter()
557 .find(|e| e.family() == EntryFamily::Q42)
558 .map(|e| e.entry_id());
559 let mut edges = Vec::new();
560 if let Some(geo) = geometry_id {
561 let to = entries
562 .iter()
563 .find(|e| e.entry_id() == geo)
564 .ok_or(MixedError::Identity)?;
565 for from in &entries {
566 if from.entry_id() == geo {
567 continue;
568 }
569 if from.family() == EntryFamily::Emf || from.family() == EntryFamily::Qac {
570 edges.push(DependencyEdge::bind(
571 from,
572 to,
573 Obligation::Mandatory,
574 DependencyReason::Geometry,
575 )?);
576 }
577 }
578 }
579 if let Some(calib) = calibration_id {
580 let to = entries
581 .iter()
582 .find(|e| e.entry_id() == calib)
583 .ok_or(MixedError::Identity)?;
584 if let Some(from) = entries.iter().find(|e| e.family() == EntryFamily::Emf) {
585 edges.push(DependencyEdge::bind(
586 from,
587 to,
588 Obligation::Mandatory,
589 DependencyReason::Calibration,
590 )?);
591 }
592 }
593 Ok(MixedPlan {
594 candidate,
595 entries,
596 edges,
597 geometry_id,
598 calibration_id,
599 })
600}
601
602impl MixedPlan {
603 pub fn candidate(&self) -> CandidateIdentity {
604 self.candidate
605 }
606 pub fn entries(&self) -> &[PlanEntry] {
607 &self.entries
608 }
609 pub fn edges(&self) -> &[DependencyEdge] {
610 &self.edges
611 }
612 pub fn geometry_id(&self) -> Option<u32> {
613 self.geometry_id
614 }
615 pub fn calibration_id(&self) -> Option<u32> {
616 self.calibration_id
617 }
618 pub fn inventory(&self) -> Result<Inventory<'_>, MixedError> {
619 Ok(Inventory::compile(
620 self.candidate,
621 &self.entries,
622 &self.edges,
623 )?)
624 }
625}
626
627#[cfg(all(test, not(target_arch = "wasm32")))]
629fn m64_container_bytes(with_metric: bool, magic: [u8; 4], full_codec: bool) -> Vec<u8> {
630 use crate::q42::{
631 chunk_integrity::blake3_trailer,
632 m64_matter::{
633 M64ChunkDirectoryEntry, M64Header, M64LocalMetricHeader, M64StrataColumnRecord,
634 M64_CODEC_BLAKE3_FULL, M64_FLAG_LOCAL_METRIC_LRM3, M64_MODE_STRATA,
635 },
636 };
637 let header_size = 64usize;
638 let metric_len = if with_metric { 128 } else { 0 };
639 let dir = header_size + metric_len;
640 let payload_off = dir + 64;
641 let rec_end = payload_off + 64;
642 let total = rec_end + if full_codec { 64 } else { 0 };
643 let mut rec = M64StrataColumnRecord::default();
644 rec.surface_elevation_mm = 1234;
645 rec.update_crc();
646 let record = bytemuck::bytes_of(&rec);
647 let mut header = M64Header::default();
648 header.magic = magic;
649 header.total_file_size = total as u64;
650 header.chunk_count = 1;
651 header.chunk_table_offset = dir as u64;
652 header.container_flags = if with_metric {
653 M64_FLAG_LOCAL_METRIC_LRM3 as u32
654 } else {
655 0
656 };
657 header.update_crc();
658 let mut row = M64ChunkDirectoryEntry {
659 chunk_uuid: [0x31; 16],
660 spatial_hilbert_index: 7,
661 byte_offset: payload_off as u64,
662 byte_length: (64 + if full_codec { 64 } else { 0 }) as u32,
663 record_count: 1,
664 srid_geodetic_code: 4326,
665 lut_bank_epoch_id: 2,
666 chunk_record_mode: M64_MODE_STRATA,
667 compression_flags: if full_codec { M64_CODEC_BLAKE3_FULL } else { 2 },
668 bao_root_hash_prefix: [0; 12],
669 entry_crc32c: 0,
670 };
671 if !full_codec {
672 row.bao_root_hash_prefix
673 .copy_from_slice(&blake3::hash(record).as_bytes()[..12]);
674 }
675 row.update_crc();
676 let mut out = vec![0; total];
677 out[..64].copy_from_slice(bytemuck::bytes_of(&header));
678 if with_metric {
679 let mut metric = M64LocalMetricHeader::default();
680 metric.anchor_did_hash = 0x1122_3344_5566_7788;
681 metric.anisotropic_scale_um = [2.0, 3.0, 4.0];
682 metric.update_crc();
683 out[64..192].copy_from_slice(bytemuck::bytes_of(&metric));
684 }
685 out[dir..dir + 64].copy_from_slice(bytemuck::bytes_of(&row));
686 out[payload_off..rec_end].copy_from_slice(record);
687 if full_codec {
688 out[rec_end..].copy_from_slice(&blake3_trailer(record));
689 }
690 out
691}
692
693#[cfg(all(test, not(target_arch = "wasm32")))]
694fn p64_container_bytes() -> Result<Vec<u8>, MixedError> {
695 use crate::p64_weight::{align_up, compile_gguf_to_p64, has_p64_magic};
696 fn put_kv_u32(out: &mut Vec<u8>, key: &str, value: u32) {
697 out.extend_from_slice(&(key.len() as u64).to_le_bytes());
698 out.extend_from_slice(key.as_bytes());
699 out.extend_from_slice(&4u32.to_le_bytes());
700 out.extend_from_slice(&value.to_le_bytes());
701 }
702 fn put_tensor(out: &mut Vec<u8>, name: &str, dims: &[u64], offset: u64) {
703 out.extend_from_slice(&(name.len() as u64).to_le_bytes());
704 out.extend_from_slice(name.as_bytes());
705 out.extend_from_slice(&(dims.len() as u32).to_le_bytes());
706 for dimension in dims {
707 out.extend_from_slice(&dimension.to_le_bytes());
708 }
709 out.extend_from_slice(&0u32.to_le_bytes());
710 out.extend_from_slice(&offset.to_le_bytes());
711 }
712 let mut gguf = Vec::new();
713 gguf.extend_from_slice(b"GGUF");
714 gguf.extend_from_slice(&3u32.to_le_bytes());
715 gguf.extend_from_slice(&2u64.to_le_bytes());
716 gguf.extend_from_slice(&3u64.to_le_bytes());
717 put_kv_u32(&mut gguf, "llama.block_count", 1);
718 put_kv_u32(&mut gguf, "llama.embedding_length", 4);
719 put_kv_u32(&mut gguf, "llama.attention.head_count", 1);
720 put_tensor(&mut gguf, "blk.0.attn_q.weight", &[4, 4], 0);
721 put_tensor(&mut gguf, "token_embd.weight", &[4, 2], 64);
722 gguf.resize(align_up(gguf.len(), 32), 0);
723 for byte in 0u8..96 {
724 gguf.push(byte.wrapping_mul(17).wrapping_add(3));
725 }
726 let p64 = compile_gguf_to_p64(&gguf, 8).map_err(|_| MixedError::Unsupported)?;
727 if !has_p64_magic(&p64) || p64.is_empty() {
728 return Err(MixedError::Unsupported);
729 }
730 Ok(p64)
731}
732
733#[cfg(all(test, not(target_arch = "wasm32")))]
734fn q42_volume_bytes() -> Result<Vec<u8>, MixedError> {
735 use crate::mini_parser::hash_token;
736 use crate::q42::q42_volume::write_unified_volume;
737 use crate::NQuin;
738 use std::collections::HashMap;
739 use std::io::Read;
740 use tempfile::NamedTempFile;
741 let subject = hash_token("urn:q42:authenticated-subject");
742 let predicate = hash_token("urn:q42:authenticated-predicate");
743 let object = hash_token("urn:q42:authenticated-object");
744 let quin = NQuin {
745 subject,
746 predicate,
747 object,
748 context: 0,
749 metadata: 0,
750 parity: 0,
751 };
752 let mut lexicon = HashMap::new();
753 lexicon.insert(subject, "urn:q42:authenticated-subject".to_string());
754 lexicon.insert(predicate, "urn:q42:authenticated-predicate".to_string());
755 lexicon.insert(object, "urn:q42:authenticated-object".to_string());
756 let file = NamedTempFile::new().map_err(|_| MixedError::Limit)?;
757 write_unified_volume(file.path(), &lexicon, &[(object, object)], &[vec![quin]])
758 .map_err(|_| MixedError::Unsupported)?;
759 let mut q42 = Vec::new();
760 std::fs::File::open(file.path())
761 .map_err(|_| MixedError::Limit)?
762 .read_to_end(&mut q42)
763 .map_err(|_| MixedError::Limit)?;
764 if q42.is_empty() {
765 return Err(MixedError::Limit);
766 }
767 Ok(q42)
768}
769
770#[cfg(all(test, not(target_arch = "wasm32")))]
771fn mesh_triangle(positions: [[f32; 3]; 3]) -> crate::render::assets::Mesh {
772 let mut min = positions[0];
773 let mut max = positions[0];
774 for p in positions {
775 for i in 0..3 {
776 min[i] = min[i].min(p[i]);
777 max[i] = max[i].max(p[i]);
778 }
779 }
780 crate::render::assets::Mesh {
781 positions: positions.to_vec(),
782 triangles: vec![[0, 1, 2]],
783 min,
784 max,
785 }
786}
787
788#[cfg(all(test, not(target_arch = "wasm32")))]
789const QAC_OPAQUE: &[u8] =
790 include_bytes!("../../../q42/field_envelope/fixtures/candidate/qac_candidate-opaque.qac");
791#[cfg(all(test, not(target_arch = "wasm32")))]
792const QAC_PCM: &[u8] = include_bytes!(
793 "../../../q42/field_envelope/fixtures/candidate/qac_candidate-pcm-signed-zero.qac"
794);
795#[cfg(all(test, not(target_arch = "wasm32")))]
796const EMF_OPAQUE: &[u8] =
797 include_bytes!("../../../q42/field_envelope/fixtures/candidate/emf_candidate-opaque.emf");
798#[cfg(all(test, not(target_arch = "wasm32")))]
799const EMF_ALIGN: &[u8] = include_bytes!(
800 "../../../q42/field_envelope/fixtures/candidate/emf_candidate-aligned4096.emf"
801);
802
803#[cfg(all(test, not(target_arch = "wasm32")))]
805pub fn default_mixed_entries() -> Result<MixedHmc, MixedError> {
806 let tend_a = crate::render::compile_10d::compile_mesh_to_10d(&mesh_triangle([
807 [0.0, 0.0, 0.0],
808 [1.0, 0.0, 0.0],
809 [0.0, 1.0, 0.0],
810 ]))
811 .map_err(|_| MixedError::Unsupported)?;
812 let tend_b = crate::render::compile_10d::compile_mesh_to_10d(&mesh_triangle([
813 [2.0, 0.0, 0.0],
814 [3.0, 0.0, 0.0],
815 [2.0, 1.0, 0.0],
816 ]))
817 .map_err(|_| MixedError::Unsupported)?;
818 if tend_a == tend_b {
819 return Err(MixedError::Identity);
820 }
821 let m64 = m64_container_bytes(false, *b"m64\0", true);
822 let q42 = q42_volume_bytes()?;
823 let p64 = p64_container_bytes()?;
824 let entries = [
825 MixedEntry {
826 id: MIXED_ID_TEND_A,
827 family: EntryFamily::TenD,
828 role: RepresentationClass::Base,
829 obligation: Obligation::Mandatory,
830 bytes: &tend_a,
831 },
832 MixedEntry {
833 id: MIXED_ID_TEND_B,
834 family: EntryFamily::TenD,
835 role: RepresentationClass::Base,
836 obligation: Obligation::Mandatory,
837 bytes: &tend_b,
838 },
839 MixedEntry {
840 id: MIXED_ID_EMF_OPAQUE,
841 family: EntryFamily::Emf,
842 role: RepresentationClass::Base,
843 obligation: Obligation::Mandatory,
844 bytes: EMF_OPAQUE,
845 },
846 MixedEntry {
847 id: MIXED_ID_EMF_ALIGN,
848 family: EntryFamily::Emf,
849 role: RepresentationClass::Base,
850 obligation: Obligation::Mandatory,
851 bytes: EMF_ALIGN,
852 },
853 MixedEntry {
854 id: MIXED_ID_QAC_OPAQUE,
855 family: EntryFamily::Qac,
856 role: RepresentationClass::Base,
857 obligation: Obligation::Mandatory,
858 bytes: QAC_OPAQUE,
859 },
860 MixedEntry {
861 id: MIXED_ID_QAC_PCM,
862 family: EntryFamily::Qac,
863 role: RepresentationClass::Base,
864 obligation: Obligation::Mandatory,
865 bytes: QAC_PCM,
866 },
867 MixedEntry {
868 id: MIXED_ID_Q42,
869 family: EntryFamily::Q42,
870 role: RepresentationClass::Metadata,
871 obligation: Obligation::Mandatory,
872 bytes: &q42,
873 },
874 MixedEntry {
875 id: MIXED_ID_M64,
876 family: EntryFamily::M64,
877 role: RepresentationClass::Enhancement,
878 obligation: Obligation::Optional,
879 bytes: &m64,
880 },
881 MixedEntry {
882 id: MIXED_ID_P64,
883 family: EntryFamily::P64,
884 role: RepresentationClass::Enhancement,
885 obligation: Obligation::Optional,
886 bytes: &p64,
887 },
888 MixedEntry {
889 id: MIXED_ID_OPAQUE,
890 family: EntryFamily::Opaque,
891 role: RepresentationClass::Enhancement,
892 obligation: Obligation::Optional,
893 bytes: MIXED_OPAQUE_BYTES,
894 },
895 ];
896 publish_mixed(&entries)
897}