1use std::collections::{BTreeMap, BTreeSet};
21use std::fmt;
22use std::fs::{self, OpenOptions};
23use std::io::{self, Write};
24use std::path::{Path, PathBuf};
25use std::sync::atomic::{AtomicU64, Ordering};
26
27use rsjs_ir::abi::{
28 canonical_bytes, AbiValidationError, CanonicalEncode, CanonicalEncoder, ComponentBindingSource,
29 ComponentCallbackShape, ComponentDescriptor, ComponentEdgeId, ComponentFieldId,
30 ComponentFieldRole, ComponentLifecycleBranch, ComponentLifecycleControl, ComponentSemanticKey,
31 CrossingHookId, DescriptorBody, DescriptorEnvelope, DescriptorKind, HelperCallEdgeId,
32 HelperDescriptor, HelperEffectClass, HelperSemanticKey, LinkUnitId, LocalValueId, OriginKind,
33 PlanId, ProviderSiteId, SemanticHash, SharedStateRefId, TemporalPropMode, WitnessRecordId,
34};
35use rsjs_ir::build::LinkPlanMaterial;
36use rsjs_ir::link::{
37 link_resolved_component_graph, link_shared_state_schemas, partition_owners,
38 ComponentGraphLinkError, LinkedCallbackDispatch, LinkedComponentInputs,
39 LinkedSharedStateSchema, OwnerActivationStrategy, OwnerCandidateId, OwnerCouplingKind,
40 OwnerPartitionPlan, OwnerRelation, OwnerRelationKind, ResolvedComponentEdge,
41 ResolvedComponentGraph, ResolvedComponentInstance, SharedStateSchemaConflict,
42};
43use rsjs_transport::TransportRecordId;
44use serde_json::Value;
45use thiserror::Error;
46
47use crate::rsjs::abi_adapter::{
48 validate_component_codegen_bridge, validate_helper_codegen_bridge, AbiBridgeResult,
49 AdaptedTransportAbi, CanonicalDescriptorBridge, ComponentCodegenBridge, ComponentFragmentRoot,
50 ComponentNodeRefBindTarget, HelperCodegenBody, HelperCodegenBridge, ResolvedTransportWitness,
51 UnsupportedDescriptor,
52};
53use crate::rsjs::link::TransportDefinitionId;
54
55pub const SEMANTIC_LINK_SCHEMA_VERSION: u16 = 15;
57pub const SEMANTIC_PLAN_FORMAT: &str = "proa.rsjs.semantic_link_plan";
59pub const SEMANTIC_PLAN_FILE_SUFFIX: &str = "semantic-plan.json";
61
62static SEMANTIC_PLAN_WRITE_NONCE: AtomicU64 = AtomicU64::new(0);
63
64#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct SemanticComponentEdge {
67 pub edge: ComponentEdgeId,
69 pub witness: WitnessRecordId,
71 pub source_edge: TransportRecordId,
73 pub target_definition: TransportDefinitionId,
75 pub target: ComponentSemanticKey,
77 pub lifecycle_control: Option<ComponentLifecycleControl>,
79}
80
81#[derive(Clone, Debug, PartialEq, Eq)]
83pub struct SemanticHelperEdge {
84 pub call: HelperCallEdgeId,
86 pub witness: WitnessRecordId,
88 pub source_edge: TransportRecordId,
90 pub target_definition: TransportDefinitionId,
92 pub target: HelperSemanticKey,
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct LinkedSemanticComponent {
99 pub definition: TransportDefinitionId,
101 pub semantic_key: ComponentSemanticKey,
103 pub descriptor: DescriptorEnvelope,
105 pub codegen: ComponentCodegenBridge,
107 pub component_edges: Vec<SemanticComponentEdge>,
109 pub helper_edges: Vec<SemanticHelperEdge>,
111 pub helper_closure: Vec<HelperSemanticKey>,
113}
114
115#[derive(Clone, Debug, PartialEq, Eq)]
121pub struct LinkedSemanticComponentSite {
122 pub candidate: OwnerCandidateId,
124 pub root: ComponentSemanticKey,
126 pub component: ComponentSemanticKey,
128 pub definition: TransportDefinitionId,
130 pub parent: Option<OwnerCandidateId>,
132 pub incoming_edge: Option<ComponentEdgeId>,
134 pub structural_path: Vec<ComponentEdgeId>,
136 pub incoming_lifecycle: Option<ComponentLifecycleControl>,
140 pub reactive_lifecycle_root: Option<OwnerCandidateId>,
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
155pub struct LinkedSharedStateProviderOccurrence {
156 pub host: OwnerCandidateId,
158 pub provider_site: ProviderSiteId,
160 pub child: OwnerCandidateId,
162 pub type_key: String,
164 pub schema_abi: SemanticHash,
166}
167
168#[derive(Clone, Debug, PartialEq, Eq)]
171pub struct LinkedSharedStateProviderRequirement {
172 pub consumer: OwnerCandidateId,
174 pub reference: SharedStateRefId,
176 pub provider_host: OwnerCandidateId,
178 pub provider_site: ProviderSiteId,
180 pub type_key: String,
182 pub schema_abi: SemanticHash,
184}
185
186#[derive(Clone, Debug, PartialEq, Eq)]
189pub struct StandaloneSharedStateRequirement {
190 pub consumer: ComponentSemanticKey,
192 pub structural_path: Vec<ComponentEdgeId>,
194 pub reference: SharedStateRefId,
196 pub type_key: String,
198 pub schema_abi: SemanticHash,
200}
201
202#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct StandaloneNodeRefRequirement {
206 pub consumer: ComponentSemanticKey,
208 pub structural_path: Vec<ComponentEdgeId>,
210 pub field: ComponentFieldId,
212 pub crossing_hook: CrossingHookId,
214 pub node_ref: u32,
216 pub bind_target: Option<ComponentNodeRefBindTarget>,
221}
222
223#[derive(Clone, Debug, PartialEq, Eq)]
226pub struct StandaloneCallbackRequirement {
227 pub consumer: ComponentSemanticKey,
229 pub structural_path: Vec<ComponentEdgeId>,
232 pub field: ComponentFieldId,
234 pub crossing_hook: CrossingHookId,
236 pub shape: ComponentCallbackShape,
238}
239
240#[derive(Clone, Debug, PartialEq, Eq)]
242pub enum StandaloneContextRequirement {
243 SharedState(StandaloneSharedStateRequirement),
245 NodeRef(StandaloneNodeRefRequirement),
247 Callback(StandaloneCallbackRequirement),
249}
250
251#[derive(Clone, Debug, PartialEq, Eq)]
257pub struct LinkedNodeRefHandleAlias {
258 pub parent: OwnerCandidateId,
260 pub edge: ComponentEdgeId,
262 pub parent_node_ref: u32,
264 pub parent_value: LocalValueId,
266 pub child: OwnerCandidateId,
268 pub field: ComponentFieldId,
270 pub crossing_hook: CrossingHookId,
272 pub child_node_ref: u32,
274 pub child_value: LocalValueId,
276 pub bind_target: Option<ComponentNodeRefBindTarget>,
278}
279
280#[derive(Clone, Debug, PartialEq, Eq)]
283pub enum StandaloneRootDisposition {
284 StructuralIncomingOnly,
287 Admitted {
289 candidate: OwnerCandidateId,
291 },
292 ContextRequired {
295 missing: Vec<StandaloneContextRequirement>,
297 },
298}
299
300#[derive(Clone, Debug, PartialEq, Eq)]
302pub struct StandaloneRootDecision {
303 pub definition: TransportDefinitionId,
305 pub component: ComponentSemanticKey,
307 pub disposition: StandaloneRootDisposition,
309}
310
311#[derive(Clone, Debug, PartialEq, Eq)]
313pub struct LinkedSemanticHelper {
314 pub definition: TransportDefinitionId,
316 pub semantic_key: HelperSemanticKey,
318 pub descriptor: DescriptorEnvelope,
320 pub codegen: HelperCodegenBridge,
322 pub helper_edges: Vec<SemanticHelperEdge>,
324 pub transitive_closure: Vec<HelperSemanticKey>,
326}
327
328#[derive(Clone, Debug, PartialEq, Eq)]
330pub struct SemanticLinkPlan {
331 pub link_unit: LinkUnitId,
333 pub plan_id: PlanId,
335 pub material: LinkPlanMaterial,
337 pub components: Vec<LinkedSemanticComponent>,
339 pub sites: Vec<LinkedSemanticComponentSite>,
341 pub root_decisions: Vec<StandaloneRootDecision>,
343 pub shared_state_providers: Vec<LinkedSharedStateProviderOccurrence>,
345 pub shared_state_requirements: Vec<LinkedSharedStateProviderRequirement>,
347 pub node_ref_aliases: Vec<LinkedNodeRefHandleAlias>,
349 pub helpers: Vec<LinkedSemanticHelper>,
351 pub reachable_helpers: Vec<HelperSemanticKey>,
353 pub owners: OwnerPartitionPlan,
355 pub component_inputs: LinkedComponentInputs,
357 pub shared_state: Vec<LinkedSharedStateSchema>,
359}
360
361#[derive(Clone, Debug, PartialEq, Eq)]
362struct SemanticComponentEdgeMaterial {
363 edge: ComponentEdgeId,
364 target: ComponentSemanticKey,
365 lifecycle_control: Option<ComponentLifecycleControl>,
366}
367
368impl CanonicalEncode for SemanticComponentEdgeMaterial {
369 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
370 encoder.record("SemanticComponentEdgeMaterial", 3);
371 encoder.field(1, &self.edge);
372 encoder.field(2, &self.target);
373 encoder.field(3, &self.lifecycle_control);
374 }
375}
376
377#[derive(Clone, Debug, PartialEq, Eq)]
378struct SemanticHelperEdgeMaterial {
379 call: HelperCallEdgeId,
380 target: HelperSemanticKey,
381 source_edge: TransportRecordId,
382 target_definition: TransportDefinitionId,
383}
384
385impl From<&SemanticHelperEdge> for SemanticHelperEdgeMaterial {
386 fn from(edge: &SemanticHelperEdge) -> Self {
387 Self {
388 call: edge.call,
389 target: edge.target.clone(),
390 source_edge: edge.source_edge,
391 target_definition: edge.target_definition,
392 }
393 }
394}
395
396impl CanonicalEncode for SemanticHelperEdgeMaterial {
397 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
398 encoder.record("SemanticHelperEdgeMaterial", 4);
399 encoder.field(1, &self.call);
400 encoder.field(2, &self.target);
404 encoder.field(3, &self.source_edge);
405 encoder.field(4, &self.target_definition);
406 }
407}
408
409#[derive(Clone, Debug, PartialEq, Eq)]
410struct SemanticComponentMaterial {
411 semantic_key: ComponentSemanticKey,
412 descriptor_hash: SemanticHash,
413 codegen: ComponentCodegenBridge,
414 component_edges: Vec<SemanticComponentEdgeMaterial>,
415 helper_edges: Vec<SemanticHelperEdgeMaterial>,
416 helper_closure: Vec<HelperSemanticKey>,
417}
418
419impl CanonicalEncode for SemanticComponentMaterial {
420 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
421 encoder.record("SemanticComponentMaterial", 6);
422 encoder.field(1, &self.semantic_key);
423 encoder.field(2, &self.descriptor_hash);
424 encoder.field(3, &self.codegen);
425 encoder.field(4, &self.component_edges);
426 encoder.field(5, &self.helper_edges);
427 encoder.field(6, &self.helper_closure);
428 }
429}
430
431#[derive(Clone, Debug, PartialEq, Eq)]
432struct SemanticComponentSiteMaterial {
433 candidate: OwnerCandidateId,
434 root: ComponentSemanticKey,
435 component: ComponentSemanticKey,
436 parent: Option<OwnerCandidateId>,
437 incoming_edge: Option<ComponentEdgeId>,
438 structural_path: Vec<ComponentEdgeId>,
439 incoming_lifecycle: Option<ComponentLifecycleControl>,
440 reactive_lifecycle_root: Option<OwnerCandidateId>,
441}
442
443impl CanonicalEncode for SemanticComponentSiteMaterial {
444 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
445 encoder.record("SemanticComponentSiteMaterial", 8);
446 encoder.field(1, &self.candidate);
447 encoder.field(2, &self.root);
448 encoder.field(3, &self.component);
449 encoder.field(4, &self.parent);
450 encoder.field(5, &self.incoming_edge);
451 encoder.field(6, &self.structural_path);
452 encoder.field(7, &self.incoming_lifecycle);
453 encoder.field(8, &self.reactive_lifecycle_root);
454 }
455}
456
457impl CanonicalEncode for LinkedSharedStateProviderOccurrence {
458 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
459 encoder.record("LinkedSharedStateProviderOccurrence", 5);
460 encoder.field(1, &self.host);
461 encoder.field(2, &self.provider_site);
462 encoder.field(3, &self.child);
463 encoder.field(4, &self.type_key);
464 encoder.field(5, &self.schema_abi);
465 }
466}
467
468impl CanonicalEncode for LinkedSharedStateProviderRequirement {
469 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
470 encoder.record("LinkedSharedStateProviderRequirement", 6);
471 encoder.field(1, &self.consumer);
472 encoder.field(2, &self.reference);
473 encoder.field(3, &self.provider_host);
474 encoder.field(4, &self.provider_site);
475 encoder.field(5, &self.type_key);
476 encoder.field(6, &self.schema_abi);
477 }
478}
479
480impl CanonicalEncode for StandaloneSharedStateRequirement {
481 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
482 encoder.record("StandaloneSharedStateRequirement", 5);
483 encoder.field(1, &self.consumer);
484 encoder.field(2, &self.structural_path);
485 encoder.field(3, &self.reference);
486 encoder.field(4, &self.type_key);
487 encoder.field(5, &self.schema_abi);
488 }
489}
490
491impl CanonicalEncode for StandaloneNodeRefRequirement {
492 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
493 encoder.record("StandaloneNodeRefRequirement", 6);
494 encoder.field(1, &self.consumer);
495 encoder.field(2, &self.structural_path);
496 encoder.field(3, &self.field);
497 encoder.field(4, &self.crossing_hook);
498 encoder.field(5, &self.node_ref);
499 encoder.field(6, &self.bind_target);
500 }
501}
502
503impl CanonicalEncode for StandaloneCallbackRequirement {
504 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
505 encoder.record("StandaloneCallbackRequirement", 5);
506 encoder.field(1, &self.consumer);
507 encoder.field(2, &self.structural_path);
508 encoder.field(3, &self.field);
509 encoder.field(4, &self.crossing_hook);
510 encoder.field(5, &self.shape);
511 }
512}
513
514impl CanonicalEncode for StandaloneContextRequirement {
515 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
516 match self {
517 Self::SharedState(requirement) => {
518 encoder.variant("StandaloneContextRequirement", 0, 1);
519 encoder.field(1, requirement);
520 }
521 Self::NodeRef(requirement) => {
522 encoder.variant("StandaloneContextRequirement", 1, 1);
523 encoder.field(1, requirement);
524 }
525 Self::Callback(requirement) => {
526 encoder.variant("StandaloneContextRequirement", 2, 1);
527 encoder.field(1, requirement);
528 }
529 }
530 }
531}
532
533impl CanonicalEncode for LinkedNodeRefHandleAlias {
534 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
535 encoder.record("LinkedNodeRefHandleAlias", 10);
536 encoder.field(1, &self.parent);
537 encoder.field(2, &self.edge);
538 encoder.field(3, &self.parent_node_ref);
539 encoder.field(4, &self.parent_value);
540 encoder.field(5, &self.child);
541 encoder.field(6, &self.field);
542 encoder.field(7, &self.crossing_hook);
543 encoder.field(8, &self.child_node_ref);
544 encoder.field(9, &self.child_value);
545 encoder.field(10, &self.bind_target);
546 }
547}
548
549impl CanonicalEncode for StandaloneRootDisposition {
550 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
551 match self {
552 Self::StructuralIncomingOnly => {
553 encoder.variant("StandaloneRootDisposition", 0, 0);
554 }
555 Self::Admitted { candidate } => {
556 encoder.variant("StandaloneRootDisposition", 1, 1);
557 encoder.field(1, candidate);
558 }
559 Self::ContextRequired { missing } => {
560 encoder.variant("StandaloneRootDisposition", 2, 1);
561 encoder.field(1, missing);
562 }
563 }
564 }
565}
566
567impl CanonicalEncode for StandaloneRootDecision {
568 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
569 encoder.record("StandaloneRootDecision", 2);
573 encoder.field(1, &self.component);
574 encoder.field(2, &self.disposition);
575 }
576}
577
578#[derive(Clone, Debug, PartialEq, Eq)]
579struct SemanticHelperMaterial {
580 semantic_key: HelperSemanticKey,
581 descriptor_hash: SemanticHash,
582 signature_hash: SemanticHash,
583 codegen: HelperCodegenBridge,
584 helper_edges: Vec<SemanticHelperEdgeMaterial>,
585 transitive_closure: Vec<HelperSemanticKey>,
586}
587
588impl CanonicalEncode for SemanticHelperMaterial {
589 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
590 encoder.record("SemanticHelperMaterial", 6);
591 encoder.field(1, &self.semantic_key);
592 encoder.field(2, &self.descriptor_hash);
593 encoder.field(3, &self.signature_hash);
594 encoder.field(4, &self.helper_edges);
599 encoder.field(5, &self.transitive_closure);
600 encoder.field(6, &self.codegen);
601 }
602}
603
604#[derive(Clone, Debug, PartialEq, Eq)]
605struct SemanticPlanPayload {
606 schema_version: u16,
607 components: Vec<SemanticComponentMaterial>,
608 sites: Vec<SemanticComponentSiteMaterial>,
609 helpers: Vec<SemanticHelperMaterial>,
610 reachable_helpers: Vec<HelperSemanticKey>,
611 owners: OwnerPartitionPlan,
612 component_inputs: LinkedComponentInputs,
613 shared_state: Vec<LinkedSharedStateSchema>,
614 root_decisions: Vec<StandaloneRootDecision>,
615 shared_state_providers: Vec<LinkedSharedStateProviderOccurrence>,
616 shared_state_requirements: Vec<LinkedSharedStateProviderRequirement>,
617 node_ref_aliases: Vec<LinkedNodeRefHandleAlias>,
618}
619
620impl CanonicalEncode for SemanticPlanPayload {
621 fn encode_canonical(&self, encoder: &mut CanonicalEncoder) {
622 encoder.record("SemanticPlanPayload", 12);
623 encoder.field(1, &self.schema_version);
624 encoder.field(2, &self.components);
625 encoder.field(3, &self.sites);
626 encoder.field(4, &self.helpers);
627 encoder.field(5, &self.reachable_helpers);
628 encoder.field(6, &self.owners);
629 encoder.field(7, &self.component_inputs);
630 encoder.field(8, &self.shared_state);
631 encoder.field(9, &self.root_decisions);
632 encoder.field(10, &self.shared_state_providers);
633 encoder.field(11, &self.shared_state_requirements);
634 encoder.field(12, &self.node_ref_aliases);
635 }
636}
637
638#[derive(Clone)]
639struct PendingComponent {
640 definition: TransportDefinitionId,
641 bridge: CanonicalDescriptorBridge,
642}
643
644impl PendingComponent {
645 fn body(&self) -> &ComponentDescriptor {
646 match &self.bridge.envelope.body {
647 DescriptorBody::Component(component) => component,
648 _ => unreachable!("component collection was classified"),
649 }
650 }
651}
652
653#[derive(Clone)]
654struct PendingHelper {
655 definition: TransportDefinitionId,
656 bridge: CanonicalDescriptorBridge,
657}
658
659impl PendingHelper {
660 fn body(&self) -> &HelperDescriptor {
661 match &self.bridge.envelope.body {
662 DescriptorBody::Helper(helper) => helper,
663 _ => unreachable!("helper collection was classified"),
664 }
665 }
666}
667
668#[derive(Clone, Copy, Debug, PartialEq, Eq)]
670pub enum SemanticWitnessKind {
671 Definition,
673 ComponentEdge,
675 ComponentField,
677 HelperEdge,
679}
680
681impl fmt::Display for SemanticWitnessKind {
682 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
683 match self {
684 Self::Definition => formatter.write_str("definition"),
685 Self::ComponentEdge => formatter.write_str("component edge"),
686 Self::ComponentField => formatter.write_str("component field"),
687 Self::HelperEdge => formatter.write_str("helper edge"),
688 }
689 }
690}
691
692fn witness_kind(witness: &ResolvedTransportWitness) -> SemanticWitnessKind {
693 match witness {
694 ResolvedTransportWitness::Definition(_) => SemanticWitnessKind::Definition,
695 ResolvedTransportWitness::ComponentEdge { .. } => SemanticWitnessKind::ComponentEdge,
696 ResolvedTransportWitness::ComponentField { .. } => SemanticWitnessKind::ComponentField,
697 ResolvedTransportWitness::HelperEdge { .. } => SemanticWitnessKind::HelperEdge,
698 }
699}
700
701#[derive(Debug, Error)]
703#[non_exhaustive]
704pub enum SemanticLinkError {
705 #[error("unsupported descriptor: {0}")]
707 Unsupported(UnsupportedDescriptor),
708 #[error(
711 "component {definition:?} uses runtime features unsupported by linked-owner codegen: {features:?}"
712 )]
713 UnsupportedLinkedOwnerRuntimeFeatures {
714 definition: TransportDefinitionId,
716 features: Vec<&'static str>,
718 },
719 #[error(
721 "{collection} adapter collection contains a canonical {actual:?} descriptor; expected {expected:?}"
722 )]
723 UnexpectedDescriptorKind {
724 collection: &'static str,
726 expected: DescriptorKind,
728 actual: DescriptorKind,
730 },
731 #[error(
733 "canonical {descriptor_kind} descriptor {definition:?} carries {codegen_kind} codegen"
734 )]
735 DescriptorCodegenKindMismatch {
736 descriptor_kind: &'static str,
738 definition: TransportDefinitionId,
740 codegen_kind: &'static str,
742 },
743 #[error("component {definition:?} has invalid codegen bridge: {reason}")]
746 InvalidComponentCodegen {
747 definition: TransportDefinitionId,
749 reason: String,
751 },
752 #[error("helper {definition:?} has invalid codegen bridge: {reason}")]
755 InvalidHelperCodegen {
756 definition: TransportDefinitionId,
758 reason: String,
760 },
761 #[error("linked helper codegen graph is invalid: {reason}")]
763 InvalidHelperProgram {
764 reason: String,
766 },
767 #[error("canonical {kind} descriptor {definition:?} is invalid: {source}")]
770 InvalidCanonicalDescriptor {
771 kind: &'static str,
773 definition: TransportDefinitionId,
775 #[source]
777 source: AbiValidationError,
778 },
779 #[error(
781 "canonical {kind} descriptor {definition:?} has a stale semantic hash: stored {stored}, recomputed {recomputed}"
782 )]
783 DescriptorHashMismatch {
784 kind: &'static str,
786 definition: TransportDefinitionId,
788 stored: SemanticHash,
790 recomputed: SemanticHash,
792 },
793 #[error("{kind} descriptor {definition:?} is missing {expected} witness {witness:?}")]
795 MissingWitness {
796 kind: &'static str,
798 definition: TransportDefinitionId,
800 witness: WitnessRecordId,
802 expected: SemanticWitnessKind,
804 },
805 #[error(
807 "{kind} descriptor {definition:?} witness {witness:?} is {actual}, expected {expected}"
808 )]
809 WitnessKindMismatch {
810 kind: &'static str,
812 definition: TransportDefinitionId,
814 witness: WitnessRecordId,
816 expected: SemanticWitnessKind,
818 actual: SemanticWitnessKind,
820 },
821 #[error(
823 "canonical {kind} descriptor has no exact defining witness {witness:?}; descriptor adaptation must preserve its TransportDefinitionId"
824 )]
825 MissingDefiningWitness {
826 kind: &'static str,
828 witness: WitnessRecordId,
830 },
831 #[error(
833 "canonical {kind} defining witness {witness:?} is {actual}, expected a definition; no descriptor identity can be inferred from an edge target"
834 )]
835 DefiningWitnessKindMismatch {
836 kind: &'static str,
838 witness: WitnessRecordId,
840 actual: SemanticWitnessKind,
842 },
843 #[error(
845 "exact transport definition {definition:?} is claimed by both {first_kind} and {second_kind} descriptors"
846 )]
847 DuplicateDefinition {
848 definition: TransportDefinitionId,
850 first_kind: &'static str,
852 second_kind: &'static str,
854 },
855 #[error(
857 "duplicate component semantic key {key:?} for exact definitions {first:?} and {second:?}"
858 )]
859 DuplicateComponentKey {
860 key: ComponentSemanticKey,
862 first: TransportDefinitionId,
864 second: TransportDefinitionId,
866 },
867 #[error(
869 "duplicate helper semantic key {key:?} for exact definitions {first:?} and {second:?}"
870 )]
871 DuplicateHelperKey {
872 key: HelperSemanticKey,
874 first: TransportDefinitionId,
876 second: TransportDefinitionId,
878 },
879 #[error(
881 "component {parent:?} edge {edge:?} resolved to unknown component definition {target:?}"
882 )]
883 UnknownComponentTarget {
884 parent: TransportDefinitionId,
886 edge: ComponentEdgeId,
888 target: TransportDefinitionId,
890 },
891 #[error(
893 "component {component:?} field {field:?} resolved to foreign component definition {target:?}"
894 )]
895 ForeignComponentFieldTarget {
896 component: TransportDefinitionId,
898 field: rsjs_ir::abi::ComponentFieldId,
900 target: TransportDefinitionId,
902 },
903 #[error("component {component:?} has duplicate rustc-backed field record {field_record:?}")]
905 DuplicateComponentFieldRecord {
906 component: TransportDefinitionId,
908 field_record: TransportRecordId,
910 },
911 #[error(
913 "{caller_kind} {caller:?} helper edge {call:?} resolved to unknown helper definition {target:?}"
914 )]
915 UnknownHelperTarget {
916 caller_kind: &'static str,
918 caller: TransportDefinitionId,
920 call: HelperCallEdgeId,
922 target: TransportDefinitionId,
924 },
925 #[error(
927 "recursive static component graph under root {root:?}: component {parent:?} edge {edge:?} reaches ancestor {target:?} at structural path {path:?}; recursive component sites cannot form a finite owner plan"
928 )]
929 RecursiveStaticComponentGraph {
930 root: ComponentSemanticKey,
932 parent: ComponentSemanticKey,
934 edge: ComponentEdgeId,
936 target: ComponentSemanticKey,
938 path: Vec<ComponentEdgeId>,
940 },
941 #[error(
944 "nested conditional component site under root {root:?}: component {parent:?} edge {edge:?} is conditional-single on control {control:?} branch {branch:?} at structural path {path:?}, inside lifecycle root candidate {reactive_lifecycle_root:?}; nested component mount/dispose identity is not implemented"
945 )]
946 UnsupportedNestedConditionalComponentSite {
947 root: ComponentSemanticKey,
949 parent: ComponentSemanticKey,
951 edge: ComponentEdgeId,
953 control: rsjs_ir::abi::LocalControlRegionId,
955 branch: ComponentLifecycleBranch,
957 path: Vec<ComponentEdgeId>,
959 reactive_lifecycle_root: OwnerCandidateId,
961 },
962 #[error(
965 "dynamic SharedState provider under root {root:?}: component {host:?} provider site {provider_site:?} at structural path {path:?} inherits lifecycle root {reactive_lifecycle_root:?}; move the provider into the static shell above the conditional component edge"
966 )]
967 DynamicSharedStateProviderHostUnsupported {
968 root: ComponentSemanticKey,
970 host: ComponentSemanticKey,
972 provider_site: ProviderSiteId,
974 path: Vec<ComponentEdgeId>,
976 reactive_lifecycle_root: OwnerCandidateId,
978 },
979 #[error(
982 "SharedState type_key {type_key:?} has incompatible schema ABIs {first_schema} in component {first_component:?} and {second_schema} in component {second_component:?}; one type_key must name exactly one wire schema before any owner activates"
983 )]
984 SharedStateDeclarationConflict {
985 type_key: String,
987 first_schema: SemanticHash,
989 first_component: ComponentSemanticKey,
991 second_schema: SemanticHash,
993 second_component: ComponentSemanticKey,
995 },
996 #[error(
999 "invalid NodeRef handle alias from component {parent:?} edge {edge:?} to {child:?}: {reason}"
1000 )]
1001 InvalidNodeRefHandleAlias {
1002 parent: ComponentSemanticKey,
1004 edge: ComponentEdgeId,
1006 child: ComponentSemanticKey,
1008 reason: String,
1010 },
1011 #[error(
1013 "NodeRef handle alias on edge {edge:?} crosses final owners between candidates {parent:?} and {child:?}"
1014 )]
1015 NodeRefAliasOwnerMismatch {
1016 parent: OwnerCandidateId,
1018 edge: ComponentEdgeId,
1020 child: OwnerCandidateId,
1022 },
1023 #[error(
1025 "{kind} descriptor {definition:?} reuses witness {witness:?} for multiple semantic records"
1026 )]
1027 WitnessClaimedMultipleTimes {
1028 kind: &'static str,
1030 definition: TransportDefinitionId,
1032 witness: WitnessRecordId,
1034 },
1035 #[error(
1037 "{kind} descriptor {definition:?} has duplicate {edge_kind} source-edge record {source_edge:?}"
1038 )]
1039 DuplicateSourceEdge {
1040 kind: &'static str,
1042 definition: TransportDefinitionId,
1044 edge_kind: &'static str,
1046 source_edge: TransportRecordId,
1048 },
1049 #[error("{kind} descriptor {definition:?} contains unclaimed {actual} witness {witness:?}")]
1051 UnclaimedWitness {
1052 kind: &'static str,
1054 definition: TransportDefinitionId,
1056 witness: WitnessRecordId,
1058 actual: SemanticWitnessKind,
1060 },
1061 #[error("reachable helper {helper:?} is not OriginFree")]
1063 ReachableOriginatingHelper {
1064 helper: HelperSemanticKey,
1066 },
1067 #[error("component graph linking failed: {0}")]
1069 ComponentGraph(#[from] ComponentGraphLinkError),
1070 #[error("SharedState schema linking failed: {0}")]
1072 SharedState(#[from] SharedStateSchemaConflict),
1073}
1074
1075#[derive(Debug, Error)]
1077#[non_exhaustive]
1078pub enum SemanticPlanValidationError {
1079 #[error("semantic plan material has LinkUnitId {actual}, but the plan declares {expected}")]
1081 LinkUnitMismatch {
1082 expected: LinkUnitId,
1084 actual: LinkUnitId,
1086 },
1087 #[error(
1089 "semantic plan definition {definition:?} contains a {actual:?} descriptor; expected {expected:?}"
1090 )]
1091 UnexpectedDescriptorKind {
1092 definition: TransportDefinitionId,
1094 expected: DescriptorKind,
1096 actual: DescriptorKind,
1098 },
1099 #[error("semantic plan component {definition:?} has invalid codegen bridge: {reason}")]
1102 InvalidComponentCodegen {
1103 definition: TransportDefinitionId,
1105 reason: String,
1107 },
1108 #[error("semantic plan helper {definition:?} has invalid codegen bridge: {reason}")]
1111 InvalidHelperCodegen {
1112 definition: TransportDefinitionId,
1114 reason: String,
1116 },
1117 #[error("semantic plan helper codegen graph is invalid: {reason}")]
1119 InvalidHelperProgram {
1120 reason: String,
1122 },
1123 #[error("semantic plan descriptor {definition:?} is invalid: {source}")]
1125 InvalidCanonicalDescriptor {
1126 definition: TransportDefinitionId,
1128 #[source]
1130 source: AbiValidationError,
1131 },
1132 #[error(
1135 "semantic plan component site {candidate:?} introduces a nested conditional lifetime beneath lifecycle root {reactive_lifecycle_root:?}"
1136 )]
1137 NestedConditionalComponentSite {
1138 candidate: OwnerCandidateId,
1140 reactive_lifecycle_root: OwnerCandidateId,
1142 },
1143 #[error(
1146 "semantic plan component {definition:?} uses runtime features unsupported by linked-owner codegen: {features:?}"
1147 )]
1148 UnsupportedLinkedOwnerRuntimeFeatures {
1149 definition: TransportDefinitionId,
1151 features: Vec<&'static str>,
1153 },
1154 #[error(
1156 "semantic plan component {definition:?} has a copied semantic key that disagrees with its descriptor"
1157 )]
1158 ComponentKeyMismatch {
1159 definition: TransportDefinitionId,
1161 },
1162 #[error(
1164 "semantic plan helper {definition:?} has a copied semantic key that disagrees with its descriptor"
1165 )]
1166 HelperKeyMismatch {
1167 definition: TransportDefinitionId,
1169 },
1170 #[error(
1172 "semantic plan descriptor {definition:?} has stale hash {stored}; recomputed {recomputed}"
1173 )]
1174 DescriptorHashMismatch {
1175 definition: TransportDefinitionId,
1177 stored: SemanticHash,
1179 recomputed: SemanticHash,
1181 },
1182 #[error(
1184 "semantic plan component-site IDs must be dense; expected {expected:?}, found {actual:?}"
1185 )]
1186 NonDenseComponentSite {
1187 expected: OwnerCandidateId,
1189 actual: OwnerCandidateId,
1191 },
1192 #[error(
1194 "semantic plan component site {candidate:?} names definition {definition:?} as {component:?}, but no matching component definition exists"
1195 )]
1196 UnknownComponentSiteDefinition {
1197 candidate: OwnerCandidateId,
1199 definition: TransportDefinitionId,
1201 component: ComponentSemanticKey,
1203 },
1204 #[error("semantic plan root component site {candidate:?} has inconsistent root metadata")]
1206 InvalidRootComponentSite {
1207 candidate: OwnerCandidateId,
1209 },
1210 #[error(
1212 "semantic plan component site {candidate:?} does not match its parent, incoming edge, structural path, or resolved target"
1213 )]
1214 InvalidChildComponentSite {
1215 candidate: OwnerCandidateId,
1217 },
1218 #[error("semantic plan component input graph is invalid: {0}")]
1220 InvalidComponentInputGraph(#[source] ComponentGraphLinkError),
1221 #[error(
1223 "semantic plan component timing/callback records do not match its descriptors and concrete sites"
1224 )]
1225 ComponentInputsMismatch,
1226 #[error("semantic plan owners do not match its descriptor-derived component coupling graph")]
1228 OwnerPlanMismatch,
1229 #[error(
1232 "semantic plan SharedState schemas or consumers do not match its descriptors and concrete sites"
1233 )]
1234 SharedStatePlanMismatch,
1235 #[error(
1238 "semantic plan standalone-root or SharedState provider topology does not match its canonical component descriptors"
1239 )]
1240 SharedStateProviderTopologyMismatch,
1241 #[error(
1244 "semantic plan NodeRef aliases do not match its canonical component descriptors and concrete sites"
1245 )]
1246 NodeRefAliasTopologyMismatch,
1247 #[error(
1249 "semantic plan NodeRef alias on edge {edge:?} crosses final owners between candidates {parent:?} and {child:?}"
1250 )]
1251 NodeRefAliasOwnerMismatch {
1252 parent: OwnerCandidateId,
1254 edge: ComponentEdgeId,
1256 child: OwnerCandidateId,
1258 },
1259 #[error("semantic plan SharedState provider topology is invalid: {reason}")]
1262 InvalidSharedStateProviderTopology {
1263 reason: String,
1265 },
1266 #[error("semantic plan component descriptor hash list does not match its canonical records")]
1268 ComponentDescriptorHashesMismatch,
1269 #[error("semantic plan helper descriptor hash list does not match its canonical records")]
1271 HelperDescriptorHashesMismatch,
1272 #[error("semantic plan payload hash mismatch: material {stored}, recomputed {recomputed}")]
1274 PayloadHashMismatch {
1275 stored: SemanticHash,
1277 recomputed: SemanticHash,
1279 },
1280 #[error("semantic plan ID mismatch: stored {stored}, recomputed {recomputed}")]
1282 PlanIdMismatch {
1283 stored: PlanId,
1285 recomputed: PlanId,
1287 },
1288}
1289
1290#[derive(Debug, Error)]
1292#[non_exhaustive]
1293pub enum SemanticPlanSerializationError {
1294 #[error(transparent)]
1296 InvalidPlan(#[from] SemanticPlanValidationError),
1297 #[error("owner {owner} uses an unsupported activation strategy")]
1299 UnsupportedOwnerStrategy {
1300 owner: u32,
1302 },
1303 #[error(
1305 "component input from candidate {parent} edge {edge} at prop-use site {site} uses an unsupported temporal mode"
1306 )]
1307 UnsupportedTemporalMode {
1308 parent: u32,
1310 edge: u32,
1312 site: u32,
1314 },
1315 #[error(
1317 "component callback from candidate {parent} edge {edge} uses an unsupported dispatch mode"
1318 )]
1319 UnsupportedCallbackDispatch {
1320 parent: u32,
1322 edge: u32,
1324 },
1325}
1326
1327#[derive(Debug, Error)]
1329#[non_exhaustive]
1330pub enum SemanticPlanWriteError {
1331 #[error("semantic plan directory must be absolute: {0}")]
1333 RelativeDirectory(PathBuf),
1334 #[error(transparent)]
1336 SerializePlan(#[from] SemanticPlanSerializationError),
1337 #[error("failed to encode semantic plan JSON: {0}")]
1339 EncodeJson(#[from] serde_json::Error),
1340 #[error("failed to create semantic plan directory {path}: {source}")]
1342 CreateDirectory {
1343 path: PathBuf,
1345 #[source]
1347 source: io::Error,
1348 },
1349 #[error("failed to read existing semantic plan {path}: {source}")]
1351 ReadExisting {
1352 path: PathBuf,
1354 #[source]
1356 source: io::Error,
1357 },
1358 #[error("failed to create temporary semantic plan {path}: {source}")]
1360 CreateTemporary {
1361 path: PathBuf,
1363 #[source]
1365 source: io::Error,
1366 },
1367 #[error("failed to write temporary semantic plan {path}: {source}")]
1369 WriteTemporary {
1370 path: PathBuf,
1372 #[source]
1374 source: io::Error,
1375 },
1376 #[error("failed to atomically commit semantic plan {from} to {to}: {source}")]
1378 Commit {
1379 from: PathBuf,
1381 to: PathBuf,
1383 #[source]
1385 source: io::Error,
1386 },
1387 #[error("semantic plan ID {plan_id} already exists with different content at {path}")]
1389 ContentCollision {
1390 plan_id: PlanId,
1392 path: PathBuf,
1394 },
1395}
1396
1397pub fn link_semantic_plan(
1403 link_unit: LinkUnitId,
1404 adapted: &AdaptedTransportAbi,
1405) -> Result<SemanticLinkPlan, SemanticLinkError> {
1406 let mut components = collect_components(&adapted.components)?;
1407 let mut helpers = collect_helpers(&adapted.helpers)?;
1408
1409 components.sort_by(|left, right| left.body().semantic_key.cmp(&right.body().semantic_key));
1410 helpers.sort_by(|left, right| left.body().semantic_key.cmp(&right.body().semantic_key));
1411
1412 let component_by_definition = index_component_definitions(&components)?;
1413 let helper_by_definition = index_helper_definitions(&helpers)?;
1414 validate_definition_kinds(&component_by_definition, &helper_by_definition)?;
1415 validate_component_keys(&components)?;
1416 validate_helper_keys(&helpers)?;
1417
1418 let helper_keys = helpers
1419 .iter()
1420 .map(|helper| helper.body().semantic_key.clone())
1421 .collect::<Vec<_>>();
1422 let mut helper_adjacency = vec![Vec::<usize>::new(); helpers.len()];
1423 let mut linked_helpers = Vec::with_capacity(helpers.len());
1424
1425 for (index, helper) in helpers.iter().enumerate() {
1426 let body = helper.body();
1427 let mut claimed = BTreeSet::from([body.defining_witness]);
1428 let mut source_edges = BTreeSet::new();
1429 let mut resolved = Vec::with_capacity(body.direct_helpers.len());
1430 for (&call, &witness) in &body.direct_helpers {
1431 claim_witness("helper", helper.definition, witness, &mut claimed)?;
1432 let (source_edge, target_definition) =
1433 expect_helper_edge("helper", helper.definition, witness, &helper.bridge)?;
1434 if !source_edges.insert(source_edge) {
1435 return Err(SemanticLinkError::DuplicateSourceEdge {
1436 kind: "helper",
1437 definition: helper.definition,
1438 edge_kind: "helper",
1439 source_edge,
1440 });
1441 }
1442 let Some(&target_index) = helper_by_definition.get(&target_definition) else {
1443 return Err(SemanticLinkError::UnknownHelperTarget {
1444 caller_kind: "helper",
1445 caller: helper.definition,
1446 call,
1447 target: target_definition,
1448 });
1449 };
1450 helper_adjacency[index].push(target_index);
1451 resolved.push(SemanticHelperEdge {
1452 call,
1453 witness,
1454 source_edge,
1455 target_definition,
1456 target: helper_keys[target_index].clone(),
1457 });
1458 }
1459 helper_adjacency[index].sort_by(|&left, &right| helper_keys[left].cmp(&helper_keys[right]));
1460 helper_adjacency[index].dedup();
1461 ensure_complete_witness_coverage("helper", helper, &claimed)?;
1462 linked_helpers.push(LinkedSemanticHelper {
1463 definition: helper.definition,
1464 semantic_key: body.semantic_key.clone(),
1465 descriptor: helper.bridge.envelope.clone(),
1466 codegen: helper
1467 .bridge
1468 .helper_codegen()
1469 .cloned()
1470 .expect("helper collection validates the codegen kind"),
1471 helper_edges: resolved,
1472 transitive_closure: Vec::new(),
1473 });
1474 }
1475
1476 validate_linked_helper_codegen_graph(&linked_helpers)
1477 .map_err(|reason| SemanticLinkError::InvalidHelperProgram { reason })?;
1478
1479 for (index, helper) in linked_helpers.iter_mut().enumerate() {
1480 let closure = helper_closure_order(&[index], &helper_adjacency, &helpers, &helper_keys)?;
1481 helper.transitive_closure = closure
1482 .into_iter()
1483 .map(|helper| helper_keys[helper].clone())
1484 .collect();
1485 }
1486
1487 let mut linked_components = Vec::with_capacity(components.len());
1488 let partition_descriptors = components
1489 .iter()
1490 .map(|component| component.body().clone())
1491 .collect::<Vec<_>>();
1492 let mut global_helper_roots = BTreeSet::new();
1493
1494 for component in &components {
1495 let body = component.body();
1496 let mut claimed = BTreeSet::from([body.defining_witness]);
1497 let mut component_sources = BTreeSet::new();
1498 let mut component_field_records = BTreeSet::new();
1499 let mut helper_sources = BTreeSet::new();
1500 let mut direct_components = Vec::with_capacity(body.direct_components.len());
1501 let mut direct_helpers = Vec::with_capacity(body.direct_helpers.len());
1502 let mut helper_roots = BTreeSet::new();
1503
1504 for (&edge, direct) in &body.direct_components {
1505 claim_witness(
1506 "component",
1507 component.definition,
1508 direct.witness,
1509 &mut claimed,
1510 )?;
1511 let (source_edge, target_definition) =
1512 expect_component_edge(component.definition, direct.witness, &component.bridge)?;
1513 if !component_sources.insert(source_edge) {
1514 return Err(SemanticLinkError::DuplicateSourceEdge {
1515 kind: "component",
1516 definition: component.definition,
1517 edge_kind: "component",
1518 source_edge,
1519 });
1520 }
1521 let Some(&target_index) = component_by_definition.get(&target_definition) else {
1522 return Err(SemanticLinkError::UnknownComponentTarget {
1523 parent: component.definition,
1524 edge,
1525 target: target_definition,
1526 });
1527 };
1528
1529 direct_components.push(SemanticComponentEdge {
1530 edge,
1531 witness: direct.witness,
1532 source_edge,
1533 target_definition,
1534 target: components[target_index].body().semantic_key.clone(),
1535 lifecycle_control: direct.lifecycle_control,
1536 });
1537 }
1538
1539 for (&field, schema) in &body.fields {
1540 let Some(witness) = schema.type_witness else {
1541 continue;
1542 };
1543 claim_witness("component", component.definition, witness, &mut claimed)?;
1544 let (field_record, target) =
1545 expect_component_field(component.definition, witness, &component.bridge)?;
1546 if target != component.definition {
1547 return Err(SemanticLinkError::ForeignComponentFieldTarget {
1548 component: component.definition,
1549 field,
1550 target,
1551 });
1552 }
1553 if !component_field_records.insert(field_record) {
1554 return Err(SemanticLinkError::DuplicateComponentFieldRecord {
1555 component: component.definition,
1556 field_record,
1557 });
1558 }
1559 }
1560
1561 for (&call, &witness) in &body.direct_helpers {
1562 claim_witness("component", component.definition, witness, &mut claimed)?;
1563 let (source_edge, target_definition) = expect_helper_edge(
1564 "component",
1565 component.definition,
1566 witness,
1567 &component.bridge,
1568 )?;
1569 if !helper_sources.insert(source_edge) {
1570 return Err(SemanticLinkError::DuplicateSourceEdge {
1571 kind: "component",
1572 definition: component.definition,
1573 edge_kind: "helper",
1574 source_edge,
1575 });
1576 }
1577 let Some(&target_index) = helper_by_definition.get(&target_definition) else {
1578 return Err(SemanticLinkError::UnknownHelperTarget {
1579 caller_kind: "component",
1580 caller: component.definition,
1581 call,
1582 target: target_definition,
1583 });
1584 };
1585 helper_roots.insert(target_index);
1586 global_helper_roots.insert(target_index);
1587 direct_helpers.push(SemanticHelperEdge {
1588 call,
1589 witness,
1590 source_edge,
1591 target_definition,
1592 target: helper_keys[target_index].clone(),
1593 });
1594 }
1595 ensure_complete_witness_coverage("component", component, &claimed)?;
1596
1597 let helper_closure = helper_closure_order(
1598 &helper_roots.into_iter().collect::<Vec<_>>(),
1599 &helper_adjacency,
1600 &helpers,
1601 &helper_keys,
1602 )?
1603 .into_iter()
1604 .map(|helper| helper_keys[helper].clone())
1605 .collect();
1606 linked_components.push(LinkedSemanticComponent {
1607 definition: component.definition,
1608 semantic_key: body.semantic_key.clone(),
1609 descriptor: component.bridge.envelope.clone(),
1610 codegen: component
1611 .bridge
1612 .component_codegen()
1613 .cloned()
1614 .expect("component collection validates the codegen kind"),
1615 component_edges: direct_components,
1616 helper_edges: direct_helpers,
1617 helper_closure,
1618 });
1619 }
1620
1621 let site_plan = instantiate_component_sites(&linked_components, &component_by_definition)?;
1622 let sites = site_plan.sites;
1623 let resolved_component_edges = site_plan.resolved_edges;
1624 let instances = sites
1625 .iter()
1626 .map(|site| {
1627 let definition_index = component_by_definition[&site.definition];
1628 let descriptor = &partition_descriptors[definition_index];
1629 ResolvedComponentInstance {
1630 id: site.candidate,
1631 descriptor,
1632 has_browser_obligation: has_local_browser_obligation(descriptor),
1636 }
1637 })
1638 .collect::<Vec<_>>();
1639 let component_graph =
1640 link_component_graph_with_lifecycle(&instances, &resolved_component_edges, &sites)?;
1641 let owners = partition_owners(
1642 &component_graph.owner_input.candidates,
1643 &component_graph.owner_input.relations,
1644 )
1645 .map_err(ComponentGraphLinkError::from)?;
1646 validate_node_ref_alias_owners(&site_plan.node_ref_aliases, &owners).map_err(
1647 |(parent, edge, child)| SemanticLinkError::NodeRefAliasOwnerMismatch {
1648 parent,
1649 edge,
1650 child,
1651 },
1652 )?;
1653 let shared_state = link_shared_state_schemas(&instances)?;
1654
1655 let reachable_helpers = helper_closure_order(
1656 &global_helper_roots.into_iter().collect::<Vec<_>>(),
1657 &helper_adjacency,
1658 &helpers,
1659 &helper_keys,
1660 )?
1661 .into_iter()
1662 .map(|helper| helper_keys[helper].clone())
1663 .collect::<Vec<_>>();
1664
1665 let payload = semantic_plan_payload(
1666 &linked_components,
1667 &sites,
1668 &linked_helpers,
1669 &reachable_helpers,
1670 &owners,
1671 &component_graph.inputs,
1672 &shared_state,
1673 &site_plan.root_decisions,
1674 &site_plan.shared_state_providers,
1675 &site_plan.shared_state_requirements,
1676 &site_plan.node_ref_aliases,
1677 )
1678 .expect("semantic linker constructs helper records from helper descriptors");
1679 let material = LinkPlanMaterial {
1680 link_unit,
1681 component_descriptors: linked_components
1682 .iter()
1683 .map(|component| component.descriptor.semantic_hash)
1684 .collect(),
1685 helper_descriptors: linked_helpers
1686 .iter()
1687 .map(|helper| helper.descriptor.semantic_hash)
1688 .collect(),
1689 payload: SemanticHash::derive(&payload),
1690 };
1691 let plan_id = material.plan_id();
1692
1693 Ok(SemanticLinkPlan {
1694 link_unit,
1695 plan_id,
1696 material,
1697 components: linked_components,
1698 sites,
1699 root_decisions: site_plan.root_decisions,
1700 shared_state_providers: site_plan.shared_state_providers,
1701 shared_state_requirements: site_plan.shared_state_requirements,
1702 node_ref_aliases: site_plan.node_ref_aliases,
1703 helpers: linked_helpers,
1704 reachable_helpers,
1705 owners,
1706 component_inputs: component_graph.inputs,
1707 shared_state,
1708 })
1709}
1710
1711struct ComponentSiteInstantiation {
1712 sites: Vec<LinkedSemanticComponentSite>,
1713 resolved_edges: Vec<ResolvedComponentEdge>,
1714 root_decisions: Vec<StandaloneRootDecision>,
1715 shared_state_providers: Vec<LinkedSharedStateProviderOccurrence>,
1716 shared_state_requirements: Vec<LinkedSharedStateProviderRequirement>,
1717 node_ref_aliases: Vec<LinkedNodeRefHandleAlias>,
1718}
1719
1720#[derive(Clone)]
1721struct ActiveSharedStateProvider {
1722 host: OwnerCandidateId,
1723 provider_site: ProviderSiteId,
1724 type_key: String,
1725 schema_abi: SemanticHash,
1726}
1727
1728fn instantiate_component_sites(
1729 components: &[LinkedSemanticComponent],
1730 component_by_definition: &BTreeMap<TransportDefinitionId, usize>,
1731) -> Result<ComponentSiteInstantiation, SemanticLinkError> {
1732 struct ExpansionFrame {
1733 component_index: usize,
1734 site: OwnerCandidateId,
1735 next_edge: usize,
1736 provider_depth_before_entry: usize,
1737 }
1738
1739 validate_global_shared_state_schemas(components)?;
1740
1741 let mut sites = Vec::new();
1746 let mut resolved_edges = Vec::new();
1747 let mut root_decisions = Vec::with_capacity(components.len());
1748 let mut shared_state_providers = Vec::new();
1749 let mut shared_state_requirements = Vec::new();
1750 let mut node_ref_aliases = Vec::new();
1751 for (root_index, root_component) in components.iter().enumerate() {
1752 let DescriptorBody::Component(root_body) = &root_component.descriptor.body else {
1753 unreachable!("linked component collection contains component descriptors")
1754 };
1755 if !root_body.root_eligible {
1756 root_decisions.push(StandaloneRootDecision {
1757 definition: root_component.definition,
1758 component: root_component.semantic_key.clone(),
1759 disposition: StandaloneRootDisposition::StructuralIncomingOnly,
1760 });
1761 continue;
1762 }
1763
1764 let candidate_base = sites.len() as u32;
1765 let root_candidate = OwnerCandidateId::new(candidate_base);
1766 let mut provisional_sites = vec![LinkedSemanticComponentSite {
1767 candidate: root_candidate,
1768 root: root_component.semantic_key.clone(),
1769 component: root_component.semantic_key.clone(),
1770 definition: root_component.definition,
1771 parent: None,
1772 incoming_edge: None,
1773 structural_path: Vec::new(),
1774 incoming_lifecycle: None,
1775 reactive_lifecycle_root: None,
1776 }];
1777 let mut provisional_edges = Vec::new();
1778 let mut provisional_providers = Vec::new();
1779 let mut provisional_requirements = Vec::new();
1780 let mut provisional_node_ref_aliases = Vec::new();
1781 let mut missing = Vec::new();
1782 let mut active_providers = Vec::<ActiveSharedStateProvider>::new();
1783 record_shared_state_requirements(
1784 root_component,
1785 root_candidate,
1786 &[],
1787 &active_providers,
1788 &mut provisional_requirements,
1789 &mut missing,
1790 );
1791 record_standalone_callback_requirements(root_component, &[], &mut missing);
1792 record_standalone_node_ref_requirements(root_component, &[], &mut missing);
1793
1794 let mut stack = vec![ExpansionFrame {
1795 component_index: root_index,
1796 site: root_candidate,
1797 next_edge: 0,
1798 provider_depth_before_entry: 0,
1799 }];
1800 while !stack.is_empty() {
1801 let frame_index = stack.len() - 1;
1802 let component_index = stack[frame_index].component_index;
1803 let next_edge = stack[frame_index].next_edge;
1804 let component = &components[component_index];
1805 let Some(edge) = component.component_edges.get(next_edge).cloned() else {
1806 let frame = stack.pop().expect("stack was checked non-empty");
1807 active_providers.truncate(frame.provider_depth_before_entry);
1808 continue;
1809 };
1810 stack[frame_index].next_edge += 1;
1811 let parent_site = stack[frame_index].site;
1812 let parent_index = usize::try_from(parent_site.index() - candidate_base)
1813 .expect("provisional candidate offset fits usize");
1814
1815 let DescriptorBody::Component(body) = &component.descriptor.body else {
1816 unreachable!("linked component collection contains component descriptors")
1817 };
1818 let direct = body
1819 .direct_components
1820 .get(&edge.edge)
1821 .expect("resolved component edge remains present in its descriptor");
1822 let mut structural_path = provisional_sites[parent_index].structural_path.clone();
1823 structural_path.push(edge.edge);
1824 let parent_lifecycle_root = provisional_sites[parent_index].reactive_lifecycle_root;
1825 if let (Some(lifecycle), Some(reactive_lifecycle_root)) =
1826 (direct.lifecycle_control, parent_lifecycle_root)
1827 {
1828 return Err(
1829 SemanticLinkError::UnsupportedNestedConditionalComponentSite {
1830 root: root_component.semantic_key.clone(),
1831 parent: component.semantic_key.clone(),
1832 edge: edge.edge,
1833 control: lifecycle.control,
1834 branch: lifecycle.branch,
1835 path: structural_path,
1836 reactive_lifecycle_root,
1837 },
1838 );
1839 }
1840
1841 let target_index = component_by_definition[&edge.target_definition];
1842 if stack
1843 .iter()
1844 .any(|ancestor| ancestor.component_index == target_index)
1845 {
1846 return Err(SemanticLinkError::RecursiveStaticComponentGraph {
1847 root: root_component.semantic_key.clone(),
1848 parent: component.semantic_key.clone(),
1849 edge: edge.edge,
1850 target: components[target_index].semantic_key.clone(),
1851 path: structural_path,
1852 });
1853 }
1854
1855 let provider = body
1856 .shared_state_providers
1857 .iter()
1858 .find(|(_, provider)| provider.child_edge == edge.edge);
1859 if let (Some((&provider_site, _)), Some(reactive_lifecycle_root)) =
1860 (provider, parent_lifecycle_root)
1861 {
1862 return Err(
1863 SemanticLinkError::DynamicSharedStateProviderHostUnsupported {
1864 root: root_component.semantic_key.clone(),
1865 host: component.semantic_key.clone(),
1866 provider_site,
1867 path: provisional_sites[parent_index].structural_path.clone(),
1868 reactive_lifecycle_root,
1869 },
1870 );
1871 }
1872
1873 let child_candidate =
1874 OwnerCandidateId::new(candidate_base + provisional_sites.len() as u32);
1875 let reactive_lifecycle_root = if direct.lifecycle_control.is_some() {
1876 Some(child_candidate)
1877 } else {
1878 parent_lifecycle_root
1879 };
1880 provisional_sites.push(LinkedSemanticComponentSite {
1881 candidate: child_candidate,
1882 root: root_component.semantic_key.clone(),
1883 component: components[target_index].semantic_key.clone(),
1884 definition: edge.target_definition,
1885 parent: Some(parent_site),
1886 incoming_edge: Some(edge.edge),
1887 structural_path: structural_path.clone(),
1888 incoming_lifecycle: direct.lifecycle_control,
1889 reactive_lifecycle_root,
1890 });
1891 provisional_edges.push(ResolvedComponentEdge {
1892 parent: parent_site,
1893 edge: edge.edge,
1894 child: child_candidate,
1895 });
1896 provisional_node_ref_aliases.extend(resolve_node_ref_aliases(
1897 component,
1898 parent_site,
1899 edge.edge,
1900 &components[target_index],
1901 child_candidate,
1902 )?);
1903
1904 let provider_depth_before_entry = active_providers.len();
1905 if let Some((&provider_site, provider)) = provider {
1906 provisional_providers.push(LinkedSharedStateProviderOccurrence {
1907 host: parent_site,
1908 provider_site,
1909 child: child_candidate,
1910 type_key: provider.type_key.clone(),
1911 schema_abi: provider.schema_abi,
1912 });
1913 active_providers.push(ActiveSharedStateProvider {
1914 host: parent_site,
1915 provider_site,
1916 type_key: provider.type_key.clone(),
1917 schema_abi: provider.schema_abi,
1918 });
1919 }
1920 record_shared_state_requirements(
1921 &components[target_index],
1922 child_candidate,
1923 &structural_path,
1924 &active_providers,
1925 &mut provisional_requirements,
1926 &mut missing,
1927 );
1928 stack.push(ExpansionFrame {
1929 component_index: target_index,
1930 site: child_candidate,
1931 next_edge: 0,
1932 provider_depth_before_entry,
1933 });
1934 }
1935
1936 if missing.is_empty() {
1937 root_decisions.push(StandaloneRootDecision {
1938 definition: root_component.definition,
1939 component: root_component.semantic_key.clone(),
1940 disposition: StandaloneRootDisposition::Admitted {
1941 candidate: root_candidate,
1942 },
1943 });
1944 sites.extend(provisional_sites);
1945 resolved_edges.extend(provisional_edges);
1946 shared_state_providers.extend(provisional_providers);
1947 shared_state_requirements.extend(provisional_requirements);
1948 node_ref_aliases.extend(provisional_node_ref_aliases);
1949 } else {
1950 root_decisions.push(StandaloneRootDecision {
1951 definition: root_component.definition,
1952 component: root_component.semantic_key.clone(),
1953 disposition: StandaloneRootDisposition::ContextRequired { missing },
1954 });
1955 }
1956 }
1957
1958 Ok(ComponentSiteInstantiation {
1959 sites,
1960 resolved_edges,
1961 root_decisions,
1962 shared_state_providers,
1963 shared_state_requirements,
1964 node_ref_aliases,
1965 })
1966}
1967
1968fn record_shared_state_requirements(
1969 component: &LinkedSemanticComponent,
1970 consumer: OwnerCandidateId,
1971 structural_path: &[ComponentEdgeId],
1972 active_providers: &[ActiveSharedStateProvider],
1973 requirements: &mut Vec<LinkedSharedStateProviderRequirement>,
1974 missing: &mut Vec<StandaloneContextRequirement>,
1975) {
1976 let DescriptorBody::Component(body) = &component.descriptor.body else {
1977 unreachable!("linked component collection contains component descriptors")
1978 };
1979 for (&reference, shared) in &body.shared_state {
1980 let provider = active_providers
1981 .iter()
1982 .rev()
1983 .find(|provider| provider.type_key == shared.type_key);
1984 match provider {
1985 Some(provider) if provider.schema_abi == shared.schema_abi => {
1986 requirements.push(LinkedSharedStateProviderRequirement {
1987 consumer,
1988 reference,
1989 provider_host: provider.host,
1990 provider_site: provider.provider_site,
1991 type_key: shared.type_key.clone(),
1992 schema_abi: shared.schema_abi,
1993 });
1994 }
1995 Some(_) => unreachable!("global SharedState schema validation precedes expansion"),
1998 None => missing.push(StandaloneContextRequirement::SharedState(
1999 StandaloneSharedStateRequirement {
2000 consumer: component.semantic_key.clone(),
2001 structural_path: structural_path.to_vec(),
2002 reference,
2003 type_key: shared.type_key.clone(),
2004 schema_abi: shared.schema_abi,
2005 },
2006 )),
2007 }
2008 }
2009}
2010
2011fn record_standalone_node_ref_requirements(
2012 component: &LinkedSemanticComponent,
2013 structural_path: &[ComponentEdgeId],
2014 missing: &mut Vec<StandaloneContextRequirement>,
2015) {
2016 let DescriptorBody::Component(body) = &component.descriptor.body else {
2017 unreachable!("linked component collection contains component descriptors")
2018 };
2019 for node_ref in &component.codegen.inbound_node_refs {
2020 let field = &body.fields[&node_ref.field_id];
2021 missing.push(StandaloneContextRequirement::NodeRef(
2022 StandaloneNodeRefRequirement {
2023 consumer: component.semantic_key.clone(),
2024 structural_path: structural_path.to_vec(),
2025 field: node_ref.field_id,
2026 crossing_hook: field
2027 .crossing_hook
2028 .expect("validated inbound NodeRef has a crossing hook"),
2029 node_ref: node_ref.producer_node_ref_id,
2030 bind_target: node_ref.bind_target,
2031 },
2032 ));
2033 }
2034}
2035
2036fn record_standalone_callback_requirements(
2037 component: &LinkedSemanticComponent,
2038 structural_path: &[ComponentEdgeId],
2039 missing: &mut Vec<StandaloneContextRequirement>,
2040) {
2041 let DescriptorBody::Component(body) = &component.descriptor.body else {
2042 unreachable!("linked component collection contains component descriptors")
2043 };
2044 for (&field_id, field) in &body.fields {
2045 if field.role != ComponentFieldRole::Callback {
2046 continue;
2047 }
2048 let shape = field
2049 .callback_shape
2050 .expect("validated inbound callback has a callback shape");
2051 if matches!(shape, ComponentCallbackShape::Optional) {
2052 continue;
2056 }
2057 missing.push(StandaloneContextRequirement::Callback(
2058 StandaloneCallbackRequirement {
2059 consumer: component.semantic_key.clone(),
2060 structural_path: structural_path.to_vec(),
2061 field: field_id,
2062 crossing_hook: field
2063 .crossing_hook
2064 .expect("validated inbound callback has a crossing hook"),
2065 shape,
2066 },
2067 ));
2068 }
2069}
2070
2071fn resolve_node_ref_aliases(
2072 parent: &LinkedSemanticComponent,
2073 parent_candidate: OwnerCandidateId,
2074 edge_id: ComponentEdgeId,
2075 child: &LinkedSemanticComponent,
2076 child_candidate: OwnerCandidateId,
2077) -> Result<Vec<LinkedNodeRefHandleAlias>, SemanticLinkError> {
2078 let DescriptorBody::Component(parent_body) = &parent.descriptor.body else {
2079 unreachable!("linked component collection contains component descriptors")
2080 };
2081 let DescriptorBody::Component(child_body) = &child.descriptor.body else {
2082 unreachable!("linked component collection contains component descriptors")
2083 };
2084 let direct = &parent_body.direct_components[&edge_id];
2085 let parent_aliases = parent
2086 .codegen
2087 .direct_node_ref_aliases
2088 .iter()
2089 .filter(|alias| alias.edge_id == edge_id)
2090 .collect::<Vec<_>>();
2091
2092 let mut resolved_by_field = BTreeMap::<ComponentFieldId, LinkedNodeRefHandleAlias>::new();
2093 for alias in parent_aliases {
2094 let Some(binding) = direct.bindings.get(&alias.field_name) else {
2095 return Err(invalid_node_ref_alias(
2096 parent,
2097 edge_id,
2098 child,
2099 format!(
2100 "parent codegen names absent child field `{}`",
2101 alias.field_name
2102 ),
2103 ));
2104 };
2105 if binding.source
2106 != (ComponentBindingSource::ClientHandle {
2107 value: alias.canonical_value,
2108 })
2109 {
2110 return Err(invalid_node_ref_alias(
2111 parent,
2112 edge_id,
2113 child,
2114 format!(
2115 "field `{}` is not the authenticated ClientHandle value {}",
2116 alias.field_name,
2117 alias.canonical_value.index()
2118 ),
2119 ));
2120 }
2121
2122 let Some((&field_id, field)) = child_body
2123 .fields
2124 .iter()
2125 .find(|(_, field)| field.source_name == alias.field_name)
2126 else {
2127 return Err(invalid_node_ref_alias(
2128 parent,
2129 edge_id,
2130 child,
2131 format!(
2132 "resolved child has no NodeRef field named `{}`",
2133 alias.field_name
2134 ),
2135 ));
2136 };
2137 if field.role != ComponentFieldRole::ClientHandle {
2138 return Err(invalid_node_ref_alias(
2139 parent,
2140 edge_id,
2141 child,
2142 format!(
2143 "resolved child field `{}` is {:?}, expected ClientHandle",
2144 alias.field_name, field.role
2145 ),
2146 ));
2147 }
2148 let Some(child_codegen) = child
2149 .codegen
2150 .inbound_node_refs
2151 .iter()
2152 .find(|mapping| mapping.field_id == field_id)
2153 else {
2154 return Err(invalid_node_ref_alias(
2155 parent,
2156 edge_id,
2157 child,
2158 format!(
2159 "resolved child field `{}` has no authenticated inbound NodeRef mapping",
2160 alias.field_name
2161 ),
2162 ));
2163 };
2164 let crossing_hook = field
2165 .crossing_hook
2166 .expect("validated ClientHandle field has a crossing hook");
2167 let child_value = field
2168 .client_value
2169 .expect("validated ClientHandle field has a client value");
2170 let linked = LinkedNodeRefHandleAlias {
2171 parent: parent_candidate,
2172 edge: edge_id,
2173 parent_node_ref: alias.producer_node_ref_id,
2174 parent_value: alias.canonical_value,
2175 child: child_candidate,
2176 field: field_id,
2177 crossing_hook,
2178 child_node_ref: child_codegen.producer_node_ref_id,
2179 child_value,
2180 bind_target: child_codegen.bind_target,
2181 };
2182 if resolved_by_field.insert(field_id, linked).is_some() {
2183 return Err(invalid_node_ref_alias(
2184 parent,
2185 edge_id,
2186 child,
2187 format!(
2188 "child NodeRef field `{}` is supplied more than once",
2189 alias.field_name
2190 ),
2191 ));
2192 }
2193 }
2194
2195 for required in &child.codegen.inbound_node_refs {
2196 if !resolved_by_field.contains_key(&required.field_id) {
2197 let field = &child_body.fields[&required.field_id];
2198 return Err(invalid_node_ref_alias(
2199 parent,
2200 edge_id,
2201 child,
2202 format!(
2203 "required child NodeRef field `{}` has no exact parent handle binding",
2204 field.source_name
2205 ),
2206 ));
2207 }
2208 }
2209
2210 Ok(resolved_by_field.into_values().collect())
2211}
2212
2213fn invalid_node_ref_alias(
2214 parent: &LinkedSemanticComponent,
2215 edge: ComponentEdgeId,
2216 child: &LinkedSemanticComponent,
2217 reason: String,
2218) -> SemanticLinkError {
2219 SemanticLinkError::InvalidNodeRefHandleAlias {
2220 parent: parent.semantic_key.clone(),
2221 edge,
2222 child: child.semantic_key.clone(),
2223 reason,
2224 }
2225}
2226
2227fn validate_global_shared_state_schemas(
2228 components: &[LinkedSemanticComponent],
2229) -> Result<(), SemanticLinkError> {
2230 let mut schemas = BTreeMap::<String, (SemanticHash, ComponentSemanticKey)>::new();
2231 for component in components {
2232 let DescriptorBody::Component(body) = &component.descriptor.body else {
2233 unreachable!("linked component collection contains component descriptors")
2234 };
2235 let declarations = body
2236 .shared_state
2237 .values()
2238 .map(|shared| (&shared.type_key, shared.schema_abi))
2239 .chain(
2240 body.shared_state_providers
2241 .values()
2242 .map(|provider| (&provider.type_key, provider.schema_abi)),
2243 );
2244 for (type_key, schema_abi) in declarations {
2245 if let Some((first_schema, first_component)) = schemas.get(type_key) {
2246 if *first_schema != schema_abi {
2247 return Err(SemanticLinkError::SharedStateDeclarationConflict {
2248 type_key: type_key.clone(),
2249 first_schema: *first_schema,
2250 first_component: first_component.clone(),
2251 second_schema: schema_abi,
2252 second_component: component.semantic_key.clone(),
2253 });
2254 }
2255 } else {
2256 schemas.insert(
2257 type_key.clone(),
2258 (schema_abi, component.semantic_key.clone()),
2259 );
2260 }
2261 }
2262 }
2263 Ok(())
2264}
2265
2266fn link_component_graph_with_lifecycle<'a>(
2267 instances: &[ResolvedComponentInstance<'a>],
2268 edges: &[ResolvedComponentEdge],
2269 sites: &[LinkedSemanticComponentSite],
2270) -> Result<ResolvedComponentGraph, ComponentGraphLinkError> {
2271 let mut graph = link_resolved_component_graph(instances, edges)?;
2272 let mut relations = graph
2273 .owner_input
2274 .relations
2275 .iter()
2276 .copied()
2277 .collect::<BTreeSet<_>>();
2278 for site in sites {
2279 if site.reactive_lifecycle_root.is_none() {
2280 continue;
2281 }
2282 let Some(parent) = site.parent else {
2283 continue;
2284 };
2285 relations.insert(OwnerRelation::new(
2286 parent,
2287 site.candidate,
2288 OwnerRelationKind::Coupling(OwnerCouplingKind::ReactiveLifecycle),
2289 ));
2290 }
2291 graph.owner_input.relations = relations.into_iter().collect();
2292 Ok(graph)
2293}
2294
2295fn validate_node_ref_alias_owners(
2296 aliases: &[LinkedNodeRefHandleAlias],
2297 owners: &OwnerPartitionPlan,
2298) -> Result<(), (OwnerCandidateId, ComponentEdgeId, OwnerCandidateId)> {
2299 for alias in aliases {
2300 let parent_owner = owners.candidate_to_owner.get(&alias.parent);
2301 let child_owner = owners.candidate_to_owner.get(&alias.child);
2302 if parent_owner.is_none() || parent_owner != child_owner {
2303 return Err((alias.parent, alias.edge, alias.child));
2304 }
2305 }
2306 Ok(())
2307}
2308
2309fn semantic_plan_payload(
2310 components: &[LinkedSemanticComponent],
2311 sites: &[LinkedSemanticComponentSite],
2312 helpers: &[LinkedSemanticHelper],
2313 reachable_helpers: &[HelperSemanticKey],
2314 owners: &OwnerPartitionPlan,
2315 component_inputs: &LinkedComponentInputs,
2316 shared_state: &[LinkedSharedStateSchema],
2317 root_decisions: &[StandaloneRootDecision],
2318 shared_state_providers: &[LinkedSharedStateProviderOccurrence],
2319 shared_state_requirements: &[LinkedSharedStateProviderRequirement],
2320 node_ref_aliases: &[LinkedNodeRefHandleAlias],
2321) -> Result<SemanticPlanPayload, SemanticPlanValidationError> {
2322 let components = components
2323 .iter()
2324 .map(|component| SemanticComponentMaterial {
2325 semantic_key: component.semantic_key.clone(),
2326 descriptor_hash: component.descriptor.semantic_hash,
2327 codegen: component.codegen.clone(),
2328 component_edges: component
2329 .component_edges
2330 .iter()
2331 .map(|edge| SemanticComponentEdgeMaterial {
2332 edge: edge.edge,
2333 target: edge.target.clone(),
2334 lifecycle_control: edge.lifecycle_control,
2335 })
2336 .collect(),
2337 helper_edges: component
2338 .helper_edges
2339 .iter()
2340 .map(SemanticHelperEdgeMaterial::from)
2341 .collect(),
2342 helper_closure: component.helper_closure.clone(),
2343 })
2344 .collect();
2345 let sites = sites
2346 .iter()
2347 .map(|site| SemanticComponentSiteMaterial {
2348 candidate: site.candidate,
2349 root: site.root.clone(),
2350 component: site.component.clone(),
2351 parent: site.parent,
2352 incoming_edge: site.incoming_edge,
2353 structural_path: site.structural_path.clone(),
2354 incoming_lifecycle: site.incoming_lifecycle,
2355 reactive_lifecycle_root: site.reactive_lifecycle_root,
2356 })
2357 .collect();
2358 let helpers = helpers
2359 .iter()
2360 .map(|helper| {
2361 let DescriptorBody::Helper(body) = &helper.descriptor.body else {
2362 return Err(SemanticPlanValidationError::UnexpectedDescriptorKind {
2363 definition: helper.definition,
2364 expected: DescriptorKind::Helper,
2365 actual: helper.descriptor.body.kind(),
2366 });
2367 };
2368 Ok(SemanticHelperMaterial {
2369 semantic_key: helper.semantic_key.clone(),
2370 descriptor_hash: helper.descriptor.semantic_hash,
2371 signature_hash: body.signature_hash,
2372 codegen: helper.codegen.clone(),
2373 helper_edges: helper
2374 .helper_edges
2375 .iter()
2376 .map(SemanticHelperEdgeMaterial::from)
2377 .collect(),
2378 transitive_closure: helper.transitive_closure.clone(),
2379 })
2380 })
2381 .collect::<Result<Vec<_>, _>>()?;
2382 Ok(SemanticPlanPayload {
2383 schema_version: SEMANTIC_LINK_SCHEMA_VERSION,
2384 components,
2385 sites,
2386 helpers,
2387 reachable_helpers: reachable_helpers.to_vec(),
2388 owners: owners.clone(),
2389 component_inputs: component_inputs.clone(),
2390 shared_state: shared_state.to_vec(),
2391 root_decisions: root_decisions.to_vec(),
2392 shared_state_providers: shared_state_providers.to_vec(),
2393 shared_state_requirements: shared_state_requirements.to_vec(),
2394 node_ref_aliases: node_ref_aliases.to_vec(),
2395 })
2396}
2397
2398fn linked_helper_key(key: &HelperSemanticKey) -> Result<rsjs_ir::LinkedHelperKey, String> {
2399 rsjs_ir::LinkedHelperKey::from_canonical_bytes(canonical_bytes(key))
2400 .map_err(|error| format!("invalid canonical helper identity: {error}"))
2401}
2402
2403fn validate_linked_helper_codegen_graph(helpers: &[LinkedSemanticHelper]) -> Result<(), String> {
2404 let mut roots = Vec::with_capacity(helpers.len());
2405 let mut definitions = Vec::with_capacity(helpers.len());
2406
2407 for helper in helpers {
2408 let key = linked_helper_key(&helper.semantic_key)?;
2409
2410 let mut params = Vec::with_capacity(helper.codegen.signature().params.len());
2411 for (param_index, param) in helper.codegen.signature().params.iter().enumerate() {
2412 let ty = rsjs_ir::parse_client_helper_type(
2413 ¶m.rust_type,
2414 rsjs_ir::ClientHelperTypePosition::Parameter,
2415 )
2416 .map_err(|error| {
2417 format!(
2418 "helper {:?} parameter {param_index} has invalid type: {error}",
2419 helper.semantic_key,
2420 )
2421 })?;
2422 params.push(rsjs_ir::ClientParam::new(
2423 format!("__rsjs_arg_{param_index}"),
2424 ty,
2425 ));
2426 }
2427 let return_ty = rsjs_ir::parse_client_helper_type(
2428 &helper.codegen.signature().return_type,
2429 rsjs_ir::ClientHelperTypePosition::Return,
2430 )
2431 .map_err(|error| {
2432 format!(
2433 "helper {:?} has invalid return type: {error}",
2434 helper.semantic_key,
2435 )
2436 })?;
2437 let deployable_signature = params
2438 .iter()
2439 .all(|param| !client_type_contains_value_object(¶m.ty))
2440 && !client_type_contains_value_object(&return_ty);
2441 if deployable_signature {
2442 let root_edge = u32::try_from(roots.len())
2443 .map_err(|_| "linked helper graph exceeds the canonical u32 ID space".to_owned())?;
2444 roots.push(rsjs_ir::LinkedHelperCallBinding::new(
2445 HelperCallEdgeId::new(root_edge),
2446 key.clone(),
2447 ));
2448 }
2449 let body = match helper.codegen.body() {
2450 HelperCodegenBody::Expr(expression) => {
2451 rsjs_ir::ClientBlock::from_stmts(vec![rsjs_ir::ClientStmt::Return(Some(
2452 expression.clone(),
2453 ))])
2454 }
2455 HelperCodegenBody::Block(block) => block.clone(),
2456 };
2457 let calls = helper
2458 .helper_edges
2459 .iter()
2460 .map(|edge| {
2461 linked_helper_key(&edge.target)
2462 .map(|target| rsjs_ir::LinkedHelperCallBinding::new(edge.call, target))
2463 })
2464 .collect::<Result<Vec<_>, String>>()?;
2465 definitions.push(rsjs_ir::LinkedHelperDefinition::new(
2466 key, params, return_ty, body, calls,
2467 ));
2468 }
2469
2470 if !helpers.is_empty() && roots.is_empty() {
2471 return Err(
2472 "linked helper graph has no transport-safe deployable root; helper-internal value objects must be reachable from a scalar public helper"
2473 .to_owned(),
2474 );
2475 }
2476
2477 let mut reachable = roots
2482 .iter()
2483 .map(|root| root.target.clone())
2484 .collect::<BTreeSet<_>>();
2485 let mut pending = reachable.iter().cloned().collect::<Vec<_>>();
2486 while let Some(key) = pending.pop() {
2487 let Some(definition) = definitions.iter().find(|definition| definition.key == key) else {
2488 continue;
2489 };
2490 for call in &definition.calls {
2491 if reachable.insert(call.target.clone()) {
2492 pending.push(call.target.clone());
2493 }
2494 }
2495 }
2496 definitions.retain(|definition| reachable.contains(&definition.key));
2497
2498 rsjs_ir::LinkedHelperProgram::new(roots, definitions)
2499 .map(|_| ())
2500 .map_err(|error| error.to_string())
2501}
2502
2503fn client_type_contains_value_object(ty: &rsjs_ir::ClientType) -> bool {
2504 match ty {
2505 rsjs_ir::ClientType::ValueObject { .. } => true,
2506 rsjs_ir::ClientType::Option(inner) | rsjs_ir::ClientType::Vec(inner) => {
2507 client_type_contains_value_object(inner)
2508 }
2509 _ => false,
2510 }
2511}
2512
2513pub fn validate_semantic_plan(plan: &SemanticLinkPlan) -> Result<(), SemanticPlanValidationError> {
2515 if plan.material.link_unit != plan.link_unit {
2516 return Err(SemanticPlanValidationError::LinkUnitMismatch {
2517 expected: plan.link_unit,
2518 actual: plan.material.link_unit,
2519 });
2520 }
2521
2522 for component in &plan.components {
2523 let DescriptorBody::Component(body) = &component.descriptor.body else {
2524 return Err(SemanticPlanValidationError::UnexpectedDescriptorKind {
2525 definition: component.definition,
2526 expected: DescriptorKind::Component,
2527 actual: component.descriptor.body.kind(),
2528 });
2529 };
2530 if body.semantic_key != component.semantic_key {
2531 return Err(SemanticPlanValidationError::ComponentKeyMismatch {
2532 definition: component.definition,
2533 });
2534 }
2535 validate_component_codegen_bridge(&component.codegen, body).map_err(|reason| {
2536 SemanticPlanValidationError::InvalidComponentCodegen {
2537 definition: component.definition,
2538 reason,
2539 }
2540 })?;
2541 validate_plan_descriptor_hash(component.definition, &component.descriptor)?;
2542 }
2543 for helper in &plan.helpers {
2544 let DescriptorBody::Helper(body) = &helper.descriptor.body else {
2545 return Err(SemanticPlanValidationError::UnexpectedDescriptorKind {
2546 definition: helper.definition,
2547 expected: DescriptorKind::Helper,
2548 actual: helper.descriptor.body.kind(),
2549 });
2550 };
2551 if body.semantic_key != helper.semantic_key {
2552 return Err(SemanticPlanValidationError::HelperKeyMismatch {
2553 definition: helper.definition,
2554 });
2555 }
2556 validate_helper_codegen_bridge(helper.definition, &helper.codegen, body).map_err(
2557 |reason| SemanticPlanValidationError::InvalidHelperCodegen {
2558 definition: helper.definition,
2559 reason,
2560 },
2561 )?;
2562 validate_plan_descriptor_hash(helper.definition, &helper.descriptor)?;
2563 }
2564 validate_linked_helper_codegen_graph(&plan.helpers)
2565 .map_err(|reason| SemanticPlanValidationError::InvalidHelperProgram { reason })?;
2566 let component_by_definition = plan
2567 .components
2568 .iter()
2569 .enumerate()
2570 .map(|(index, component)| (component.definition, index))
2571 .collect::<BTreeMap<_, _>>();
2572 validate_component_sites(&plan.components, &plan.sites)?;
2578 let rebuilt_sites = instantiate_component_sites(&plan.components, &component_by_definition)
2579 .map_err(
2580 |error| SemanticPlanValidationError::InvalidSharedStateProviderTopology {
2581 reason: error.to_string(),
2582 },
2583 )?;
2584 if rebuilt_sites.sites != plan.sites
2585 || rebuilt_sites.root_decisions != plan.root_decisions
2586 || rebuilt_sites.shared_state_providers != plan.shared_state_providers
2587 || rebuilt_sites.shared_state_requirements != plan.shared_state_requirements
2588 {
2589 return Err(SemanticPlanValidationError::SharedStateProviderTopologyMismatch);
2590 }
2591 if rebuilt_sites.node_ref_aliases != plan.node_ref_aliases {
2592 return Err(SemanticPlanValidationError::NodeRefAliasTopologyMismatch);
2593 }
2594 let (component_inputs, owners, shared_state) =
2595 relink_plan_graphs(&plan.components, &plan.sites)?;
2596 if component_inputs != plan.component_inputs {
2597 return Err(SemanticPlanValidationError::ComponentInputsMismatch);
2598 }
2599 if owners != plan.owners {
2600 return Err(SemanticPlanValidationError::OwnerPlanMismatch);
2601 }
2602 validate_node_ref_alias_owners(&plan.node_ref_aliases, &plan.owners).map_err(
2603 |(parent, edge, child)| SemanticPlanValidationError::NodeRefAliasOwnerMismatch {
2604 parent,
2605 edge,
2606 child,
2607 },
2608 )?;
2609 if shared_state != plan.shared_state {
2610 return Err(SemanticPlanValidationError::SharedStatePlanMismatch);
2611 }
2612
2613 let component_hashes = plan
2614 .components
2615 .iter()
2616 .map(|component| component.descriptor.semantic_hash)
2617 .collect::<Vec<_>>();
2618 if component_hashes != plan.material.component_descriptors {
2619 return Err(SemanticPlanValidationError::ComponentDescriptorHashesMismatch);
2620 }
2621 let helper_hashes = plan
2622 .helpers
2623 .iter()
2624 .map(|helper| helper.descriptor.semantic_hash)
2625 .collect::<Vec<_>>();
2626 if helper_hashes != plan.material.helper_descriptors {
2627 return Err(SemanticPlanValidationError::HelperDescriptorHashesMismatch);
2628 }
2629
2630 let payload = semantic_plan_payload(
2631 &plan.components,
2632 &plan.sites,
2633 &plan.helpers,
2634 &plan.reachable_helpers,
2635 &plan.owners,
2636 &plan.component_inputs,
2637 &plan.shared_state,
2638 &plan.root_decisions,
2639 &plan.shared_state_providers,
2640 &plan.shared_state_requirements,
2641 &plan.node_ref_aliases,
2642 )?;
2643 let payload_hash = SemanticHash::derive(&payload);
2644 if payload_hash != plan.material.payload {
2645 return Err(SemanticPlanValidationError::PayloadHashMismatch {
2646 stored: plan.material.payload,
2647 recomputed: payload_hash,
2648 });
2649 }
2650 let plan_id = plan.material.plan_id();
2651 if plan_id != plan.plan_id {
2652 return Err(SemanticPlanValidationError::PlanIdMismatch {
2653 stored: plan.plan_id,
2654 recomputed: plan_id,
2655 });
2656 }
2657 Ok(())
2658}
2659
2660fn has_local_browser_obligation(descriptor: &ComponentDescriptor) -> bool {
2661 !descriptor.effects.is_empty()
2662 && descriptor
2663 .origins
2664 .values()
2665 .copied()
2666 .any(OriginKind::requires_client_permission)
2667}
2668
2669fn relink_plan_graphs(
2670 components: &[LinkedSemanticComponent],
2671 sites: &[LinkedSemanticComponentSite],
2672) -> Result<
2673 (
2674 LinkedComponentInputs,
2675 OwnerPartitionPlan,
2676 Vec<LinkedSharedStateSchema>,
2677 ),
2678 SemanticPlanValidationError,
2679> {
2680 let components_by_definition = components
2681 .iter()
2682 .map(|component| (component.definition, component))
2683 .collect::<BTreeMap<_, _>>();
2684 let instances = sites
2685 .iter()
2686 .map(|site| {
2687 let component = components_by_definition
2688 .get(&site.definition)
2689 .expect("component sites are validated before graph relinking");
2690 let DescriptorBody::Component(descriptor) = &component.descriptor.body else {
2691 unreachable!("component collection contains component descriptors")
2692 };
2693 ResolvedComponentInstance {
2694 id: site.candidate,
2695 descriptor,
2696 has_browser_obligation: has_local_browser_obligation(descriptor),
2697 }
2698 })
2699 .collect::<Vec<_>>();
2700 let edges = sites
2701 .iter()
2702 .filter_map(|site| match (site.parent, site.incoming_edge) {
2703 (Some(parent), Some(edge)) => Some(ResolvedComponentEdge {
2704 parent,
2705 edge,
2706 child: site.candidate,
2707 }),
2708 _ => None,
2709 })
2710 .collect::<Vec<_>>();
2711 let graph = link_component_graph_with_lifecycle(&instances, &edges, sites)
2712 .map_err(SemanticPlanValidationError::InvalidComponentInputGraph)?;
2713 let owners = partition_owners(&graph.owner_input.candidates, &graph.owner_input.relations)
2714 .map_err(ComponentGraphLinkError::from)
2715 .map_err(SemanticPlanValidationError::InvalidComponentInputGraph)?;
2716 let shared_state = link_shared_state_schemas(&instances)
2717 .map_err(|_| SemanticPlanValidationError::SharedStatePlanMismatch)?;
2718 Ok((graph.inputs, owners, shared_state))
2719}
2720
2721fn validate_component_sites(
2722 components: &[LinkedSemanticComponent],
2723 sites: &[LinkedSemanticComponentSite],
2724) -> Result<(), SemanticPlanValidationError> {
2725 let components_by_definition = components
2726 .iter()
2727 .map(|component| (component.definition, component))
2728 .collect::<BTreeMap<_, _>>();
2729
2730 for (index, site) in sites.iter().enumerate() {
2731 let expected = OwnerCandidateId::new(index as u32);
2732 if site.candidate != expected {
2733 return Err(SemanticPlanValidationError::NonDenseComponentSite {
2734 expected,
2735 actual: site.candidate,
2736 });
2737 }
2738 let Some(component) = components_by_definition.get(&site.definition) else {
2739 return Err(
2740 SemanticPlanValidationError::UnknownComponentSiteDefinition {
2741 candidate: site.candidate,
2742 definition: site.definition,
2743 component: site.component.clone(),
2744 },
2745 );
2746 };
2747 if component.semantic_key != site.component {
2748 return Err(
2749 SemanticPlanValidationError::UnknownComponentSiteDefinition {
2750 candidate: site.candidate,
2751 definition: site.definition,
2752 component: site.component.clone(),
2753 },
2754 );
2755 }
2756
2757 match (site.parent, site.incoming_edge) {
2758 (None, None) => {
2759 let DescriptorBody::Component(body) = &component.descriptor.body else {
2760 unreachable!("linked component collection contains component descriptors")
2761 };
2762 if !body.root_eligible
2763 || site.root != site.component
2764 || !site.structural_path.is_empty()
2765 || site.incoming_lifecycle.is_some()
2766 || site.reactive_lifecycle_root.is_some()
2767 {
2768 return Err(SemanticPlanValidationError::InvalidRootComponentSite {
2769 candidate: site.candidate,
2770 });
2771 }
2772 }
2773 (Some(parent), Some(incoming_edge)) => {
2774 let Some(parent_site) = sites.get(parent.index() as usize) else {
2775 return Err(SemanticPlanValidationError::InvalidChildComponentSite {
2776 candidate: site.candidate,
2777 });
2778 };
2779 let Some(parent_component) = components_by_definition.get(&parent_site.definition)
2780 else {
2781 return Err(SemanticPlanValidationError::InvalidChildComponentSite {
2782 candidate: site.candidate,
2783 });
2784 };
2785 let expected_path = parent_site
2786 .structural_path
2787 .iter()
2788 .copied()
2789 .chain(std::iter::once(incoming_edge))
2790 .collect::<Vec<_>>();
2791 let resolved_edge = parent_component
2792 .component_edges
2793 .iter()
2794 .find(|edge| edge.edge == incoming_edge);
2795 let resolved_target = resolved_edge.map(|edge| edge.target_definition);
2796 let incoming_lifecycle = resolved_edge.and_then(|edge| edge.lifecycle_control);
2797 let DescriptorBody::Component(parent_body) = &parent_component.descriptor.body
2798 else {
2799 unreachable!("linked component collection contains component descriptors")
2800 };
2801 let descriptor_lifecycle = parent_body
2802 .direct_components
2803 .get(&incoming_edge)
2804 .and_then(|edge| edge.lifecycle_control);
2805 if let (Some(_), Some(reactive_lifecycle_root)) =
2806 (incoming_lifecycle, parent_site.reactive_lifecycle_root)
2807 {
2808 return Err(
2809 SemanticPlanValidationError::NestedConditionalComponentSite {
2810 candidate: site.candidate,
2811 reactive_lifecycle_root,
2812 },
2813 );
2814 }
2815 let expected_lifecycle_root = if incoming_lifecycle.is_some() {
2816 Some(site.candidate)
2817 } else {
2818 parent_site.reactive_lifecycle_root
2819 };
2820 if parent >= site.candidate
2821 || parent_site.root != site.root
2822 || expected_path != site.structural_path
2823 || resolved_target != Some(site.definition)
2824 || incoming_lifecycle != descriptor_lifecycle
2825 || site.incoming_lifecycle != incoming_lifecycle
2826 || site.reactive_lifecycle_root != expected_lifecycle_root
2827 {
2828 return Err(SemanticPlanValidationError::InvalidChildComponentSite {
2829 candidate: site.candidate,
2830 });
2831 }
2832 }
2833 _ => {
2834 return Err(SemanticPlanValidationError::InvalidChildComponentSite {
2835 candidate: site.candidate,
2836 });
2837 }
2838 }
2839 }
2840 Ok(())
2841}
2842
2843fn validate_plan_descriptor_hash(
2844 definition: TransportDefinitionId,
2845 descriptor: &DescriptorEnvelope,
2846) -> Result<(), SemanticPlanValidationError> {
2847 let refreshed = DescriptorEnvelope::new(
2848 descriptor.header.clone(),
2849 descriptor.body.clone(),
2850 descriptor.debug.clone(),
2851 )
2852 .map_err(
2853 |source| SemanticPlanValidationError::InvalidCanonicalDescriptor { definition, source },
2854 )?;
2855 if refreshed.semantic_hash != descriptor.semantic_hash {
2856 return Err(SemanticPlanValidationError::DescriptorHashMismatch {
2857 definition,
2858 stored: descriptor.semantic_hash,
2859 recomputed: refreshed.semantic_hash,
2860 });
2861 }
2862 Ok(())
2863}
2864
2865pub fn semantic_plan_json(
2871 plan: &SemanticLinkPlan,
2872) -> Result<Value, SemanticPlanSerializationError> {
2873 validate_semantic_plan(plan)?;
2874
2875 let components = plan
2876 .components
2877 .iter()
2878 .map(|component| {
2879 let DescriptorBody::Component(body) = &component.descriptor.body else {
2880 unreachable!("linked component collection contains component descriptors")
2881 };
2882 serde_json::json!({
2883 "definition": definition_json(component.definition),
2884 "semantic_key_canonical": canonical_hex(&component.semantic_key),
2885 "root_eligible": body.root_eligible,
2886 "descriptor_hash": hash_json(component.descriptor.semantic_hash),
2887 "descriptor_semantic_abi": hex_bytes(&component.descriptor.semantic_bytes()),
2888 "component_edges": component.component_edges.iter().map(|edge| {
2889 serde_json::json!({
2890 "edge_id": edge.edge.index(),
2891 "witness_id": edge.witness.index(),
2892 "source_edge_id": hex_bytes(&edge.source_edge),
2893 "target_definition": definition_json(edge.target_definition),
2894 "target_semantic_key_canonical": canonical_hex(&edge.target),
2895 "lifecycle": component_lifecycle_json(edge.lifecycle_control),
2896 })
2897 }).collect::<Vec<_>>(),
2898 "helper_edges": component.helper_edges.iter().map(helper_edge_json)
2899 .collect::<Vec<_>>(),
2900 "helper_closure": component.helper_closure.iter()
2901 .map(canonical_hex)
2902 .collect::<Vec<_>>(),
2903 })
2904 })
2905 .collect::<Vec<_>>();
2906 let component_codegen = plan
2907 .components
2908 .iter()
2909 .map(|component| component_codegen_json(component.definition, &component.codegen))
2910 .collect::<Vec<_>>();
2911 let helper_codegen = plan
2912 .helpers
2913 .iter()
2914 .map(|helper| helper_codegen_json(helper.definition, &helper.semantic_key, &helper.codegen))
2915 .collect::<Vec<_>>();
2916 let sites = plan
2917 .sites
2918 .iter()
2919 .map(|site| {
2920 serde_json::json!({
2921 "candidate_id": site.candidate.index(),
2922 "root_semantic_key_canonical": canonical_hex(&site.root),
2923 "component_semantic_key_canonical": canonical_hex(&site.component),
2924 "definition": definition_json(site.definition),
2925 "parent_candidate_id": site.parent.map(OwnerCandidateId::index),
2926 "incoming_edge_id": site.incoming_edge.map(ComponentEdgeId::index),
2927 "structural_path": site.structural_path.iter()
2928 .map(|edge| edge.index())
2929 .collect::<Vec<_>>(),
2930 "incoming_lifecycle": site.parent.map(|_| {
2931 component_lifecycle_json(site.incoming_lifecycle)
2932 }),
2933 "reactive_lifecycle_root_candidate_id": site.reactive_lifecycle_root
2934 .map(OwnerCandidateId::index),
2935 })
2936 })
2937 .collect::<Vec<_>>();
2938 let helpers = plan
2939 .helpers
2940 .iter()
2941 .map(|helper| {
2942 let DescriptorBody::Helper(body) = &helper.descriptor.body else {
2943 unreachable!("validated helper descriptor kind")
2944 };
2945 serde_json::json!({
2946 "definition": definition_json(helper.definition),
2947 "semantic_key_canonical": canonical_hex(&helper.semantic_key),
2948 "descriptor_hash": hash_json(helper.descriptor.semantic_hash),
2949 "descriptor_semantic_abi": hex_bytes(&helper.descriptor.semantic_bytes()),
2950 "signature_hash": hash_json(body.signature_hash),
2951 "client_ir_hash": hash_json(body.client_ir_hash),
2952 "helper_edges": helper.helper_edges.iter().map(helper_edge_json)
2953 .collect::<Vec<_>>(),
2954 "transitive_closure": helper.transitive_closure.iter()
2955 .map(canonical_hex)
2956 .collect::<Vec<_>>(),
2957 })
2958 })
2959 .collect::<Vec<_>>();
2960 let owners = plan
2961 .owners
2962 .owners
2963 .iter()
2964 .map(|owner| {
2965 Ok(serde_json::json!({
2966 "owner_id": owner.id.index(),
2967 "candidates": owner.candidates.iter()
2968 .map(|candidate| candidate.index())
2969 .collect::<Vec<_>>(),
2970 "strategy": owner_strategy_json(owner.id.index(), &owner.strategy)?,
2971 }))
2972 })
2973 .collect::<Result<Vec<_>, SemanticPlanSerializationError>>()?;
2974 let candidate_to_owner = plan
2975 .owners
2976 .candidate_to_owner
2977 .iter()
2978 .map(|(candidate, owner)| {
2979 serde_json::json!({
2980 "candidate_id": candidate.index(),
2981 "owner_id": owner.index(),
2982 })
2983 })
2984 .collect::<Vec<_>>();
2985 let component_inputs = component_inputs_json(&plan.component_inputs)?;
2986 let shared_state = plan
2987 .shared_state
2988 .iter()
2989 .map(|schema| {
2990 serde_json::json!({
2991 "type_key": schema.type_key,
2992 "schema_abi": hash_json(schema.schema_abi),
2993 "consumers": schema.consumers.iter().map(|consumer| {
2994 serde_json::json!({
2995 "candidate_id": consumer.component.index(),
2996 "reference_id": consumer.reference.index(),
2997 "origin_id": consumer.origin.index(),
2998 })
2999 }).collect::<Vec<_>>(),
3000 })
3001 })
3002 .collect::<Vec<_>>();
3003 let root_decisions = plan
3004 .root_decisions
3005 .iter()
3006 .map(|decision| {
3007 let disposition = match &decision.disposition {
3008 StandaloneRootDisposition::StructuralIncomingOnly => {
3009 serde_json::json!({ "kind": "structural_incoming_only" })
3010 }
3011 StandaloneRootDisposition::Admitted { candidate } => serde_json::json!({
3012 "kind": "admitted",
3013 "candidate_id": candidate.index(),
3014 }),
3015 StandaloneRootDisposition::ContextRequired { missing } => serde_json::json!({
3016 "kind": "context_required",
3017 "missing": missing.iter().map(|requirement| {
3018 standalone_context_requirement_json(requirement)
3019 }).collect::<Vec<_>>(),
3020 }),
3021 };
3022 serde_json::json!({
3023 "definition": definition_json(decision.definition),
3024 "component_semantic_key_canonical": canonical_hex(&decision.component),
3025 "disposition": disposition,
3026 })
3027 })
3028 .collect::<Vec<_>>();
3029 let shared_state_providers = plan
3030 .shared_state_providers
3031 .iter()
3032 .map(|provider| {
3033 serde_json::json!({
3034 "host_candidate_id": provider.host.index(),
3035 "provider_site_id": provider.provider_site.index(),
3036 "child_candidate_id": provider.child.index(),
3037 "type_key": provider.type_key,
3038 "schema_abi": hash_json(provider.schema_abi),
3039 })
3040 })
3041 .collect::<Vec<_>>();
3042 let shared_state_requirements = plan
3043 .shared_state_requirements
3044 .iter()
3045 .map(|requirement| {
3046 serde_json::json!({
3047 "consumer_candidate_id": requirement.consumer.index(),
3048 "reference_id": requirement.reference.index(),
3049 "provider_host_candidate_id": requirement.provider_host.index(),
3050 "provider_site_id": requirement.provider_site.index(),
3051 "type_key": requirement.type_key,
3052 "schema_abi": hash_json(requirement.schema_abi),
3053 })
3054 })
3055 .collect::<Vec<_>>();
3056 let node_ref_aliases = plan
3057 .node_ref_aliases
3058 .iter()
3059 .map(|alias| {
3060 serde_json::json!({
3061 "parent_candidate_id": alias.parent.index(),
3062 "edge_id": alias.edge.index(),
3063 "parent_node_ref_id": alias.parent_node_ref,
3064 "parent_value_id": alias.parent_value.index(),
3065 "child_candidate_id": alias.child.index(),
3066 "field_id": alias.field.index(),
3067 "crossing_hook_id": alias.crossing_hook.index(),
3068 "child_node_ref_id": alias.child_node_ref,
3069 "child_value_id": alias.child_value.index(),
3070 "bind_target": node_ref_bind_target_json(alias.bind_target),
3071 })
3072 })
3073 .collect::<Vec<_>>();
3074
3075 Ok(serde_json::json!({
3076 "format": SEMANTIC_PLAN_FORMAT,
3077 "schema_version": SEMANTIC_LINK_SCHEMA_VERSION,
3078 "link_unit_id": plan.link_unit.to_string(),
3079 "plan_id": plan.plan_id.to_string(),
3080 "payload_hash": hash_json(plan.material.payload),
3081 "component_descriptor_hashes": plan.material.component_descriptors.iter()
3082 .copied()
3083 .map(hash_json)
3084 .collect::<Vec<_>>(),
3085 "helper_descriptor_hashes": plan.material.helper_descriptors.iter()
3086 .copied()
3087 .map(hash_json)
3088 .collect::<Vec<_>>(),
3089 "components": components,
3090 "component_codegen": component_codegen,
3091 "component_sites": sites,
3092 "helpers": helpers,
3093 "helper_codegen": helper_codegen,
3094 "reachable_helpers": plan.reachable_helpers.iter()
3095 .map(canonical_hex)
3096 .collect::<Vec<_>>(),
3097 "owners": owners,
3098 "candidate_to_owner": candidate_to_owner,
3099 "component_inputs": component_inputs,
3100 "shared_state": shared_state,
3101 "standalone_roots": root_decisions,
3102 "shared_state_providers": shared_state_providers,
3103 "shared_state_requirements": shared_state_requirements,
3104 "node_ref_aliases": node_ref_aliases,
3105 }))
3106}
3107
3108fn standalone_context_requirement_json(requirement: &StandaloneContextRequirement) -> Value {
3109 match requirement {
3110 StandaloneContextRequirement::SharedState(requirement) => serde_json::json!({
3111 "kind": "shared_state",
3112 "consumer_semantic_key_canonical": canonical_hex(&requirement.consumer),
3113 "structural_path": requirement.structural_path.iter()
3114 .map(|edge| edge.index())
3115 .collect::<Vec<_>>(),
3116 "reference_id": requirement.reference.index(),
3117 "type_key": requirement.type_key,
3118 "schema_abi": hash_json(requirement.schema_abi),
3119 }),
3120 StandaloneContextRequirement::NodeRef(requirement) => serde_json::json!({
3121 "kind": "node_ref",
3122 "consumer_semantic_key_canonical": canonical_hex(&requirement.consumer),
3123 "structural_path": requirement.structural_path.iter()
3124 .map(|edge| edge.index())
3125 .collect::<Vec<_>>(),
3126 "field_id": requirement.field.index(),
3127 "crossing_hook_id": requirement.crossing_hook.index(),
3128 "node_ref_id": requirement.node_ref,
3129 "bind_target": node_ref_bind_target_json(requirement.bind_target),
3130 }),
3131 StandaloneContextRequirement::Callback(requirement) => serde_json::json!({
3132 "kind": "callback",
3133 "consumer_semantic_key_canonical": canonical_hex(&requirement.consumer),
3134 "structural_path": requirement.structural_path.iter()
3135 .map(|edge| edge.index())
3136 .collect::<Vec<_>>(),
3137 "field_id": requirement.field.index(),
3138 "crossing_hook_id": requirement.crossing_hook.index(),
3139 "callback_shape": match requirement.shape {
3140 ComponentCallbackShape::Required => "required",
3141 ComponentCallbackShape::Optional => "optional",
3142 },
3143 }),
3144 }
3145}
3146
3147fn node_ref_bind_target_json(target: Option<ComponentNodeRefBindTarget>) -> Value {
3148 match target {
3149 None => Value::Null,
3150 Some(ComponentNodeRefBindTarget::Element) => Value::String("element".to_owned()),
3151 Some(ComponentNodeRefBindTarget::HtmlElement) => Value::String("html_element".to_owned()),
3152 Some(ComponentNodeRefBindTarget::Input) => Value::String("input".to_owned()),
3153 Some(ComponentNodeRefBindTarget::TextArea) => Value::String("textarea".to_owned()),
3154 Some(ComponentNodeRefBindTarget::Select) => Value::String("select".to_owned()),
3155 Some(ComponentNodeRefBindTarget::Form) => Value::String("form".to_owned()),
3156 Some(ComponentNodeRefBindTarget::Dialog) => Value::String("dialog".to_owned()),
3157 }
3158}
3159
3160fn component_lifecycle_json(lifecycle: Option<ComponentLifecycleControl>) -> Value {
3161 match lifecycle {
3162 None => serde_json::json!({
3163 "kind": "static_single",
3164 }),
3165 Some(lifecycle) => serde_json::json!({
3166 "kind": "conditional_single",
3167 "control": lifecycle.control.index(),
3168 "predicate_value": lifecycle.predicate.index(),
3169 "predicate_origin": lifecycle.predicate_origin.index(),
3170 "branch": match lifecycle.branch {
3171 ComponentLifecycleBranch::Then => "then",
3172 ComponentLifecycleBranch::Else => "else",
3173 },
3174 }),
3175 }
3176}
3177
3178fn component_codegen_json(
3179 definition: TransportDefinitionId,
3180 codegen: &ComponentCodegenBridge,
3181) -> Value {
3182 let fragment_root = match codegen.fragment_root {
3183 ComponentFragmentRoot::ExactOneElement => {
3184 serde_json::json!({ "kind": "exact_one_element" })
3185 }
3186 ComponentFragmentRoot::Unsupported => {
3187 serde_json::json!({ "kind": "unsupported" })
3188 }
3189 };
3190 serde_json::json!({
3191 "definition": definition_json(definition),
3192 "asset_id": codegen.asset_id,
3193 "fragment_key": codegen.fragment_key,
3194 "fragment_root": fragment_root,
3195 "inbound_fields": codegen.inbound_fields.iter().map(|mapping| {
3196 serde_json::json!({
3197 "field_id": mapping.field_id.index(),
3198 "producer_value_id": mapping.producer_value_id,
3199 "canonical_value_id": mapping.canonical_value.index(),
3200 "crossing_hook_id": mapping.crossing_hook_id.index(),
3201 "callback_slot_id": mapping.callback_slot_id,
3202 })
3203 }).collect::<Vec<_>>(),
3204 "inbound_targets": codegen.inbound_targets.iter().map(|mapping| {
3205 serde_json::json!({
3206 "prop_site_id": mapping.prop_site_id.index(),
3207 "field_id": mapping.field_id.index(),
3208 "producer_signal_id": mapping.producer_signal_id,
3209 "canonical_signal_value_id": mapping.canonical_signal_value.index(),
3210 })
3211 }).collect::<Vec<_>>(),
3212 "signals": codegen.signals.iter().map(|mapping| {
3213 serde_json::json!({
3214 "producer_signal_id": mapping.producer_signal_id,
3215 "canonical_value_id": mapping.canonical_value.index(),
3216 })
3217 }).collect::<Vec<_>>(),
3218 "expressions": codegen.expressions.iter().map(|mapping| {
3219 serde_json::json!({
3220 "producer_expression_id": mapping.producer_expression_id,
3221 "canonical_value_id": mapping.canonical_value.index(),
3222 })
3223 }).collect::<Vec<_>>(),
3224 "payload_handlers": codegen.payload_handlers.iter().map(|mapping| {
3225 serde_json::json!({
3226 "prelude_local_index": mapping.prelude_local_index,
3227 "canonical_value_id": mapping.canonical_value.index(),
3228 })
3229 }).collect::<Vec<_>>(),
3230 "callback_slots": codegen.callback_slots.iter().map(|mapping| {
3231 serde_json::json!({
3232 "producer_callback_slot_id": mapping.producer_callback_slot_id,
3233 "canonical_value_id": mapping.canonical_value.index(),
3234 })
3235 }).collect::<Vec<_>>(),
3236 "inbound_node_refs": codegen.inbound_node_refs.iter().map(|mapping| {
3237 serde_json::json!({
3238 "field_id": mapping.field_id.index(),
3239 "producer_node_ref_id": mapping.producer_node_ref_id,
3240 "bind_target": node_ref_bind_target_json(mapping.bind_target),
3241 })
3242 }).collect::<Vec<_>>(),
3243 "direct_node_ref_aliases": codegen.direct_node_ref_aliases.iter().map(|mapping| {
3244 serde_json::json!({
3245 "edge_id": mapping.edge_id.index(),
3246 "field_name": mapping.field_name,
3247 "producer_node_ref_id": mapping.producer_node_ref_id,
3248 "canonical_value_id": mapping.canonical_value.index(),
3249 })
3250 }).collect::<Vec<_>>(),
3251 "uses_queries": codegen.uses_queries,
3252 "uses_mutations": codegen.uses_mutations,
3253 })
3254}
3255
3256fn helper_codegen_json(
3257 definition: TransportDefinitionId,
3258 semantic_key: &HelperSemanticKey,
3259 codegen: &HelperCodegenBridge,
3260) -> Value {
3261 serde_json::json!({
3262 "definition": definition_json(definition),
3263 "semantic_key_canonical": canonical_hex(semantic_key),
3264 "signature": codegen.signature().canonical_json(),
3265 "source_ir_hash": hash_json(codegen.source_ir_hash()),
3266 "body_ir_hash": hash_json(codegen.body_ir_hash()),
3267 "body_ir": codegen.body().canonical_json(),
3268 })
3269}
3270
3271fn component_inputs_json(
3272 inputs: &LinkedComponentInputs,
3273) -> Result<Value, SemanticPlanSerializationError> {
3274 let live_props = inputs
3275 .live_props
3276 .iter()
3277 .map(|input| {
3278 let temporal = match input.temporal {
3279 TemporalPropMode::LiveRead => serde_json::json!({
3280 "kind": "live_read",
3281 }),
3282 TemporalPropMode::SeedOnce(seed_site) => serde_json::json!({
3283 "kind": "seed_once",
3284 "seed_site_id": seed_site.index(),
3285 }),
3286 TemporalPropMode::EffectDependency => serde_json::json!({
3287 "kind": "effect_dependency",
3288 }),
3289 TemporalPropMode::QueryKeyDependency => serde_json::json!({
3290 "kind": "query_key_dependency",
3291 }),
3292 TemporalPropMode::ForbiddenProviderSeed
3293 | TemporalPropMode::ForbiddenBoundaryCrossing => {
3294 return Err(SemanticPlanSerializationError::UnsupportedTemporalMode {
3295 parent: input.parent.index(),
3296 edge: input.edge.index(),
3297 site: input.site.index(),
3298 });
3299 }
3300 _ => {
3301 return Err(SemanticPlanSerializationError::UnsupportedTemporalMode {
3302 parent: input.parent.index(),
3303 edge: input.edge.index(),
3304 site: input.site.index(),
3305 });
3306 }
3307 };
3308 Ok(serde_json::json!({
3309 "parent_candidate_id": input.parent.index(),
3310 "edge_id": input.edge.index(),
3311 "child_candidate_id": input.child.index(),
3312 "field_id": input.field.index(),
3313 "crossing_hook_id": input.crossing_hook.index(),
3314 "parent_value_id": input.parent_value.index(),
3315 "child_value_id": input.child_value.index(),
3316 "prop_site_id": input.site.index(),
3317 "temporal": temporal,
3318 }))
3319 })
3320 .collect::<Result<Vec<_>, SemanticPlanSerializationError>>()?;
3321 let live_callbacks = inputs
3322 .live_callbacks
3323 .iter()
3324 .map(|input| {
3325 let callback_shape = match input.shape {
3326 ComponentCallbackShape::Required => "required",
3327 ComponentCallbackShape::Optional => "optional",
3328 };
3329 let dispatch = match input.dispatch {
3330 LinkedCallbackDispatch::ResolveCurrent => "resolve_current",
3331 _ => {
3332 return Err(
3333 SemanticPlanSerializationError::UnsupportedCallbackDispatch {
3334 parent: input.parent.index(),
3335 edge: input.edge.index(),
3336 },
3337 );
3338 }
3339 };
3340 Ok(serde_json::json!({
3341 "parent_candidate_id": input.parent.index(),
3342 "edge_id": input.edge.index(),
3343 "child_candidate_id": input.child.index(),
3344 "field_id": input.field.index(),
3345 "crossing_hook_id": input.crossing_hook.index(),
3346 "parent_value_id": input.parent_value.index(),
3347 "child_value_id": input.child_value.index(),
3348 "callback_shape": callback_shape,
3349 "dispatch": dispatch,
3350 }))
3351 })
3352 .collect::<Result<Vec<_>, SemanticPlanSerializationError>>()?;
3353
3354 Ok(serde_json::json!({
3355 "live_props": live_props,
3356 "live_callbacks": live_callbacks,
3357 }))
3358}
3359
3360fn helper_edge_json(edge: &SemanticHelperEdge) -> Value {
3361 serde_json::json!({
3362 "call_id": edge.call.index(),
3363 "witness_id": edge.witness.index(),
3364 "source_edge_id": hex_bytes(&edge.source_edge),
3365 "target_definition": definition_json(edge.target_definition),
3366 "target_semantic_key_canonical": canonical_hex(&edge.target),
3367 })
3368}
3369
3370fn owner_strategy_json(
3371 owner: u32,
3372 strategy: &OwnerActivationStrategy,
3373) -> Result<Value, SemanticPlanSerializationError> {
3374 match strategy {
3375 OwnerActivationStrategy::Eager => Ok(serde_json::json!({ "kind": "eager" })),
3376 OwnerActivationStrategy::Visible => Ok(serde_json::json!({ "kind": "visible" })),
3377 OwnerActivationStrategy::Idle => Ok(serde_json::json!({ "kind": "idle" })),
3378 OwnerActivationStrategy::Interaction { event } => Ok(serde_json::json!({
3379 "kind": "interaction",
3380 "event": event,
3381 })),
3382 OwnerActivationStrategy::Media { query } => Ok(serde_json::json!({
3383 "kind": "media",
3384 "query": query,
3385 })),
3386 _ => Err(SemanticPlanSerializationError::UnsupportedOwnerStrategy { owner }),
3387 }
3388}
3389
3390fn definition_json(definition: TransportDefinitionId) -> Value {
3391 serde_json::json!({
3392 "cargo_unit_id": definition.unit.to_string(),
3393 "record_id": hex_bytes(&definition.record),
3394 })
3395}
3396
3397fn hash_json(hash: SemanticHash) -> String {
3398 format!("sha256:{hash}")
3399}
3400
3401fn canonical_hex<T: CanonicalEncode + ?Sized>(value: &T) -> String {
3402 hex_bytes(&canonical_bytes(value))
3403}
3404
3405fn hex_bytes(bytes: &[u8]) -> String {
3406 use std::fmt::Write as _;
3407
3408 let mut output = String::with_capacity(bytes.len() * 2);
3409 for byte in bytes {
3410 let _ = write!(output, "{byte:02x}");
3411 }
3412 output
3413}
3414
3415pub fn write_content_addressed_semantic_plan(
3420 directory: &Path,
3421 plan: &SemanticLinkPlan,
3422) -> Result<PathBuf, SemanticPlanWriteError> {
3423 if !directory.is_absolute() {
3424 return Err(SemanticPlanWriteError::RelativeDirectory(
3425 directory.to_path_buf(),
3426 ));
3427 }
3428 fs::create_dir_all(directory).map_err(|source| SemanticPlanWriteError::CreateDirectory {
3429 path: directory.to_path_buf(),
3430 source,
3431 })?;
3432
3433 let value = semantic_plan_json(plan)?;
3434 let bytes = serde_json::to_vec_pretty(&value)?;
3435 let path = directory.join(format!("{}.{}", plan.plan_id, SEMANTIC_PLAN_FILE_SUFFIX));
3436 if path.exists() {
3437 let existing = fs::read(&path).map_err(|source| SemanticPlanWriteError::ReadExisting {
3438 path: path.clone(),
3439 source,
3440 })?;
3441 if existing == bytes {
3442 return Ok(path);
3443 }
3444 return Err(SemanticPlanWriteError::ContentCollision {
3445 plan_id: plan.plan_id,
3446 path,
3447 });
3448 }
3449
3450 let nonce = SEMANTIC_PLAN_WRITE_NONCE.fetch_add(1, Ordering::Relaxed);
3451 let temporary = directory.join(format!(
3452 ".{}.{}.{}.tmp",
3453 plan.plan_id,
3454 std::process::id(),
3455 nonce
3456 ));
3457 let mut file = OpenOptions::new()
3458 .write(true)
3459 .create_new(true)
3460 .open(&temporary)
3461 .map_err(|source| SemanticPlanWriteError::CreateTemporary {
3462 path: temporary.clone(),
3463 source,
3464 })?;
3465 if let Err(source) = file.write_all(&bytes).and_then(|()| file.sync_all()) {
3466 let _ = fs::remove_file(&temporary);
3467 return Err(SemanticPlanWriteError::WriteTemporary {
3468 path: temporary,
3469 source,
3470 });
3471 }
3472 drop(file);
3473
3474 match fs::rename(&temporary, &path) {
3475 Ok(()) => Ok(path),
3476 Err(_source) if path.exists() => {
3477 let _ = fs::remove_file(&temporary);
3478 let existing =
3479 fs::read(&path).map_err(|source| SemanticPlanWriteError::ReadExisting {
3480 path: path.clone(),
3481 source,
3482 })?;
3483 if existing == bytes {
3484 Ok(path)
3485 } else {
3486 Err(SemanticPlanWriteError::ContentCollision {
3487 plan_id: plan.plan_id,
3488 path,
3489 })
3490 }
3491 }
3492 Err(source) => {
3493 let _ = fs::remove_file(&temporary);
3494 Err(SemanticPlanWriteError::Commit {
3495 from: temporary,
3496 to: path,
3497 source,
3498 })
3499 }
3500 }
3501}
3502
3503fn collect_components(
3504 results: &[AbiBridgeResult],
3505) -> Result<Vec<PendingComponent>, SemanticLinkError> {
3506 results
3507 .iter()
3508 .map(|result| {
3509 let bridge = require_canonical(result)?;
3510 let DescriptorBody::Component(component) = &bridge.envelope.body else {
3511 return Err(SemanticLinkError::UnexpectedDescriptorKind {
3512 collection: "component",
3513 expected: DescriptorKind::Component,
3514 actual: bridge.envelope.body.kind(),
3515 });
3516 };
3517 let definition =
3518 defining_transport_id("component", component.defining_witness, bridge)?;
3519 validate_descriptor_hash("component", definition, &bridge.envelope)?;
3520 let Some(codegen) = bridge.component_codegen() else {
3521 return Err(SemanticLinkError::DescriptorCodegenKindMismatch {
3522 descriptor_kind: "component",
3523 definition,
3524 codegen_kind: "helper",
3525 });
3526 };
3527 validate_component_codegen_bridge(codegen, component).map_err(|reason| {
3528 SemanticLinkError::InvalidComponentCodegen { definition, reason }
3529 })?;
3530 Ok(PendingComponent {
3531 definition,
3532 bridge: bridge.clone(),
3533 })
3534 })
3535 .collect()
3536}
3537
3538fn collect_helpers(results: &[AbiBridgeResult]) -> Result<Vec<PendingHelper>, SemanticLinkError> {
3539 results
3540 .iter()
3541 .map(|result| {
3542 let bridge = require_canonical(result)?;
3543 let DescriptorBody::Helper(helper) = &bridge.envelope.body else {
3544 return Err(SemanticLinkError::UnexpectedDescriptorKind {
3545 collection: "helper",
3546 expected: DescriptorKind::Helper,
3547 actual: bridge.envelope.body.kind(),
3548 });
3549 };
3550 let definition = defining_transport_id("helper", helper.defining_witness, bridge)?;
3551 validate_descriptor_hash("helper", definition, &bridge.envelope)?;
3552 let Some(codegen) = bridge.helper_codegen() else {
3553 return Err(SemanticLinkError::DescriptorCodegenKindMismatch {
3554 descriptor_kind: "helper",
3555 definition,
3556 codegen_kind: "component",
3557 });
3558 };
3559 validate_helper_codegen_bridge(definition, codegen, helper)
3560 .map_err(|reason| SemanticLinkError::InvalidHelperCodegen { definition, reason })?;
3561 Ok(PendingHelper {
3562 definition,
3563 bridge: bridge.clone(),
3564 })
3565 })
3566 .collect()
3567}
3568
3569fn require_canonical(
3570 result: &AbiBridgeResult,
3571) -> Result<&CanonicalDescriptorBridge, SemanticLinkError> {
3572 match result {
3573 AbiBridgeResult::Canonical(bridge) => Ok(bridge),
3574 AbiBridgeResult::Unsupported(descriptor) => {
3575 Err(SemanticLinkError::Unsupported(descriptor.clone()))
3576 }
3577 }
3578}
3579
3580fn defining_transport_id(
3581 kind: &'static str,
3582 witness: WitnessRecordId,
3583 bridge: &CanonicalDescriptorBridge,
3584) -> Result<TransportDefinitionId, SemanticLinkError> {
3585 match bridge.witnesses.get(&witness) {
3586 Some(ResolvedTransportWitness::Definition(definition)) => Ok(*definition),
3587 Some(actual) => Err(SemanticLinkError::DefiningWitnessKindMismatch {
3588 kind,
3589 witness,
3590 actual: witness_kind(actual),
3591 }),
3592 None => Err(SemanticLinkError::MissingDefiningWitness { kind, witness }),
3593 }
3594}
3595
3596fn validate_descriptor_hash(
3597 kind: &'static str,
3598 definition: TransportDefinitionId,
3599 envelope: &DescriptorEnvelope,
3600) -> Result<(), SemanticLinkError> {
3601 let refreshed = DescriptorEnvelope::new(
3602 envelope.header.clone(),
3603 envelope.body.clone(),
3604 envelope.debug.clone(),
3605 )
3606 .map_err(|source| SemanticLinkError::InvalidCanonicalDescriptor {
3607 kind,
3608 definition,
3609 source,
3610 })?;
3611 if refreshed.semantic_hash != envelope.semantic_hash {
3612 return Err(SemanticLinkError::DescriptorHashMismatch {
3613 kind,
3614 definition,
3615 stored: envelope.semantic_hash,
3616 recomputed: refreshed.semantic_hash,
3617 });
3618 }
3619 Ok(())
3620}
3621
3622fn index_component_definitions(
3623 components: &[PendingComponent],
3624) -> Result<BTreeMap<TransportDefinitionId, usize>, SemanticLinkError> {
3625 let mut definitions = BTreeMap::new();
3626 for (index, component) in components.iter().enumerate() {
3627 if definitions.insert(component.definition, index).is_some() {
3628 return Err(SemanticLinkError::DuplicateDefinition {
3629 definition: component.definition,
3630 first_kind: "component",
3631 second_kind: "component",
3632 });
3633 }
3634 }
3635 Ok(definitions)
3636}
3637
3638fn index_helper_definitions(
3639 helpers: &[PendingHelper],
3640) -> Result<BTreeMap<TransportDefinitionId, usize>, SemanticLinkError> {
3641 let mut definitions = BTreeMap::new();
3642 for (index, helper) in helpers.iter().enumerate() {
3643 if definitions.insert(helper.definition, index).is_some() {
3644 return Err(SemanticLinkError::DuplicateDefinition {
3645 definition: helper.definition,
3646 first_kind: "helper",
3647 second_kind: "helper",
3648 });
3649 }
3650 }
3651 Ok(definitions)
3652}
3653
3654fn validate_definition_kinds(
3655 components: &BTreeMap<TransportDefinitionId, usize>,
3656 helpers: &BTreeMap<TransportDefinitionId, usize>,
3657) -> Result<(), SemanticLinkError> {
3658 if let Some(definition) = components
3659 .keys()
3660 .find(|definition| helpers.contains_key(definition))
3661 {
3662 return Err(SemanticLinkError::DuplicateDefinition {
3663 definition: *definition,
3664 first_kind: "component",
3665 second_kind: "helper",
3666 });
3667 }
3668 Ok(())
3669}
3670
3671fn validate_component_keys(components: &[PendingComponent]) -> Result<(), SemanticLinkError> {
3672 for pair in components.windows(2) {
3673 if pair[0].body().semantic_key == pair[1].body().semantic_key {
3674 return Err(SemanticLinkError::DuplicateComponentKey {
3675 key: pair[0].body().semantic_key.clone(),
3676 first: pair[0].definition,
3677 second: pair[1].definition,
3678 });
3679 }
3680 }
3681 Ok(())
3682}
3683
3684fn validate_helper_keys(helpers: &[PendingHelper]) -> Result<(), SemanticLinkError> {
3685 for pair in helpers.windows(2) {
3686 if pair[0].body().semantic_key == pair[1].body().semantic_key {
3687 return Err(SemanticLinkError::DuplicateHelperKey {
3688 key: pair[0].body().semantic_key.clone(),
3689 first: pair[0].definition,
3690 second: pair[1].definition,
3691 });
3692 }
3693 }
3694 Ok(())
3695}
3696
3697fn claim_witness(
3698 kind: &'static str,
3699 definition: TransportDefinitionId,
3700 witness: WitnessRecordId,
3701 claimed: &mut BTreeSet<WitnessRecordId>,
3702) -> Result<(), SemanticLinkError> {
3703 if !claimed.insert(witness) {
3704 return Err(SemanticLinkError::WitnessClaimedMultipleTimes {
3705 kind,
3706 definition,
3707 witness,
3708 });
3709 }
3710 Ok(())
3711}
3712
3713fn expect_component_edge(
3714 definition: TransportDefinitionId,
3715 witness: WitnessRecordId,
3716 bridge: &CanonicalDescriptorBridge,
3717) -> Result<(TransportRecordId, TransportDefinitionId), SemanticLinkError> {
3718 match bridge.witnesses.get(&witness) {
3719 Some(ResolvedTransportWitness::ComponentEdge {
3720 source_edge,
3721 target,
3722 }) => Ok((*source_edge, *target)),
3723 Some(actual) => Err(SemanticLinkError::WitnessKindMismatch {
3724 kind: "component",
3725 definition,
3726 witness,
3727 expected: SemanticWitnessKind::ComponentEdge,
3728 actual: witness_kind(actual),
3729 }),
3730 None => Err(SemanticLinkError::MissingWitness {
3731 kind: "component",
3732 definition,
3733 witness,
3734 expected: SemanticWitnessKind::ComponentEdge,
3735 }),
3736 }
3737}
3738
3739fn expect_component_field(
3740 definition: TransportDefinitionId,
3741 witness: WitnessRecordId,
3742 bridge: &CanonicalDescriptorBridge,
3743) -> Result<(TransportRecordId, TransportDefinitionId), SemanticLinkError> {
3744 match bridge.witnesses.get(&witness) {
3745 Some(ResolvedTransportWitness::ComponentField {
3746 field_record,
3747 target,
3748 }) => Ok((*field_record, *target)),
3749 Some(actual) => Err(SemanticLinkError::WitnessKindMismatch {
3750 kind: "component",
3751 definition,
3752 witness,
3753 expected: SemanticWitnessKind::ComponentField,
3754 actual: witness_kind(actual),
3755 }),
3756 None => Err(SemanticLinkError::MissingWitness {
3757 kind: "component",
3758 definition,
3759 witness,
3760 expected: SemanticWitnessKind::ComponentField,
3761 }),
3762 }
3763}
3764
3765fn expect_helper_edge(
3766 kind: &'static str,
3767 definition: TransportDefinitionId,
3768 witness: WitnessRecordId,
3769 bridge: &CanonicalDescriptorBridge,
3770) -> Result<(TransportRecordId, TransportDefinitionId), SemanticLinkError> {
3771 match bridge.witnesses.get(&witness) {
3772 Some(ResolvedTransportWitness::HelperEdge {
3773 source_edge,
3774 target,
3775 }) => Ok((*source_edge, *target)),
3776 Some(actual) => Err(SemanticLinkError::WitnessKindMismatch {
3777 kind,
3778 definition,
3779 witness,
3780 expected: SemanticWitnessKind::HelperEdge,
3781 actual: witness_kind(actual),
3782 }),
3783 None => Err(SemanticLinkError::MissingWitness {
3784 kind,
3785 definition,
3786 witness,
3787 expected: SemanticWitnessKind::HelperEdge,
3788 }),
3789 }
3790}
3791
3792fn ensure_complete_witness_coverage<T>(
3793 kind: &'static str,
3794 descriptor: &T,
3795 claimed: &BTreeSet<WitnessRecordId>,
3796) -> Result<(), SemanticLinkError>
3797where
3798 T: SemanticBridgeRecord,
3799{
3800 for (&witness, resolved) in &descriptor.bridge().witnesses {
3801 if !claimed.contains(&witness) {
3802 return Err(SemanticLinkError::UnclaimedWitness {
3803 kind,
3804 definition: descriptor.definition(),
3805 witness,
3806 actual: witness_kind(resolved),
3807 });
3808 }
3809 }
3810 Ok(())
3811}
3812
3813trait SemanticBridgeRecord {
3814 fn definition(&self) -> TransportDefinitionId;
3815 fn bridge(&self) -> &CanonicalDescriptorBridge;
3816}
3817
3818impl SemanticBridgeRecord for PendingComponent {
3819 fn definition(&self) -> TransportDefinitionId {
3820 self.definition
3821 }
3822
3823 fn bridge(&self) -> &CanonicalDescriptorBridge {
3824 &self.bridge
3825 }
3826}
3827
3828impl SemanticBridgeRecord for PendingHelper {
3829 fn definition(&self) -> TransportDefinitionId {
3830 self.definition
3831 }
3832
3833 fn bridge(&self) -> &CanonicalDescriptorBridge {
3834 &self.bridge
3835 }
3836}
3837
3838fn helper_closure_order(
3839 roots: &[usize],
3840 adjacency: &[Vec<usize>],
3841 helpers: &[PendingHelper],
3842 keys: &[HelperSemanticKey],
3843) -> Result<Vec<usize>, SemanticLinkError> {
3844 let mut roots = roots.to_vec();
3845 roots.sort_by(|&left, &right| keys[left].cmp(&keys[right]));
3846 roots.dedup();
3847
3848 let mut state = vec![0_u8; helpers.len()];
3853 let mut order = Vec::new();
3854 for root in roots {
3855 if state[root] == 2 {
3856 continue;
3857 }
3858 validate_origin_free(root, helpers)?;
3859 state[root] = 1;
3860 let mut stack = vec![(root, 0_usize)];
3861 while let Some((node, next_dependency)) = stack.last_mut() {
3862 if *next_dependency < adjacency[*node].len() {
3863 let dependency = adjacency[*node][*next_dependency];
3864 *next_dependency += 1;
3865 match state[dependency] {
3866 0 => {
3867 validate_origin_free(dependency, helpers)?;
3868 state[dependency] = 1;
3869 stack.push((dependency, 0));
3870 }
3871 1 | 2 => {}
3872 _ => unreachable!("helper traversal state is three-valued"),
3873 }
3874 } else {
3875 let (finished, _) = stack.pop().expect("stack contains current helper");
3876 if state[finished] != 2 {
3877 state[finished] = 2;
3878 order.push(finished);
3879 }
3880 }
3881 }
3882 }
3883 Ok(order)
3884}
3885
3886fn validate_origin_free(helper: usize, helpers: &[PendingHelper]) -> Result<(), SemanticLinkError> {
3887 if helpers[helper].body().effect_class != HelperEffectClass::OriginFree {
3888 return Err(SemanticLinkError::ReachableOriginatingHelper {
3889 helper: helpers[helper].body().semantic_key.clone(),
3890 });
3891 }
3892 Ok(())
3893}
3894
3895#[cfg(test)]
3896mod tests;