Skip to main content

oa/runtime/graph/
semantic.rs

1//! Canonical backend-independent semantic operation graph.
2//!
3//! Port provenance: `oa/source/cpp/include/oa/runtime/semanticGraph.h` and
4//! `oa/source/cpp/lib/oa/runtime/semanticGraph.cpp`. Rust `Option` and typed IDs
5//! replace the C++ invalid-ID sentinels; graph meaning and validation are kept.
6
7use std::collections::BTreeSet;
8
9use crate::{
10	DType, Error, OpAttribute, OpDifferentiation, OpEffect, OpLowering, OpValueKind,
11	OperationContract, Result,
12};
13
14/// Canonical graph-local identity of one semantic value.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct SemanticValueId(u32);
17
18impl SemanticValueId {
19	/// Return the canonical zero-based graph index.
20	pub const fn index(self) -> u32 {
21		self.0
22	}
23
24	fn usize(self) -> usize {
25		self.0 as usize
26	}
27}
28
29/// Canonical graph-local identity of one semantic operation.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct SemanticOpId(u32);
32
33impl SemanticOpId {
34	pub(crate) const fn from_index(index: u32) -> Self {
35		Self(index)
36	}
37
38	/// Return the canonical zero-based graph index.
39	pub const fn index(self) -> u32 {
40		self.0
41	}
42
43	fn usize(self) -> usize {
44		self.0 as usize
45	}
46}
47
48/// Deterministic many-to-many provenance summary for semantic lowering.
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct SemanticLoweringAnalysis {
51	executable_node_counts: Vec<u32>,
52	schema_owned_node_count: u32,
53	compatibility_node_count: u32,
54	direct_op_count: u32,
55	decomposed_op_count: u32,
56	fused_op_count: u32,
57	fused_node_count: u32,
58	maximum_nodes_per_op: u32,
59	maximum_ops_per_node: u32,
60}
61
62impl SemanticLoweringAnalysis {
63	pub(crate) fn empty(operation_count: usize) -> Self {
64		Self {
65			executable_node_counts: vec![0; operation_count],
66			schema_owned_node_count: 0,
67			compatibility_node_count: 0,
68			direct_op_count: 0,
69			decomposed_op_count: 0,
70			fused_op_count: 0,
71			fused_node_count: 0,
72			maximum_nodes_per_op: 0,
73			maximum_ops_per_node: 0,
74		}
75	}
76
77	/// Return how many executable nodes lower one semantic operation.
78	pub fn executable_node_count(&self, operation: SemanticOpId) -> u32 {
79		self
80			.executable_node_counts
81			.get(operation.usize())
82			.copied()
83			.unwrap_or(0)
84	}
85
86	/// Return the number of executable nodes with semantic ownership.
87	pub const fn schema_owned_node_count(&self) -> u32 {
88		self.schema_owned_node_count
89	}
90
91	/// Return executable nodes still using the compatibility route.
92	pub const fn compatibility_node_count(&self) -> u32 {
93		self.compatibility_node_count
94	}
95
96	/// Return semantic operations lowered directly to one unfused node.
97	pub const fn direct_op_count(&self) -> u32 {
98		self.direct_op_count
99	}
100
101	/// Return semantic operations decomposed into multiple nodes.
102	pub const fn decomposed_op_count(&self) -> u32 {
103		self.decomposed_op_count
104	}
105
106	/// Return semantic operations participating in fused nodes.
107	pub const fn fused_op_count(&self) -> u32 {
108		self.fused_op_count
109	}
110
111	/// Return executable nodes owning multiple semantic operations.
112	pub const fn fused_node_count(&self) -> u32 {
113		self.fused_node_count
114	}
115
116	/// Return the widest decomposition of one semantic operation.
117	pub const fn maximum_nodes_per_op(&self) -> u32 {
118		self.maximum_nodes_per_op
119	}
120
121	/// Return the widest semantic fusion represented by one executable node.
122	pub const fn maximum_ops_per_node(&self) -> u32 {
123		self.maximum_ops_per_node
124	}
125
126	pub(crate) fn node_counts_mut(&mut self) -> &mut [u32] {
127		&mut self.executable_node_counts
128	}
129
130	pub(crate) fn note_compatibility_node(&mut self) {
131		self.compatibility_node_count = self.compatibility_node_count.saturating_add(1);
132	}
133
134	pub(crate) fn note_schema_node(&mut self, owner_count: usize) -> Result<()> {
135		let owner_count = u32::try_from(owner_count)
136			.map_err(|_| Error::resource_exhausted("semantic node owner count exceeds u32"))?;
137		self.schema_owned_node_count = self.schema_owned_node_count.saturating_add(1);
138		self.maximum_ops_per_node = self.maximum_ops_per_node.max(owner_count);
139		if owner_count > 1 {
140			self.fused_node_count = self.fused_node_count.saturating_add(1);
141		}
142		Ok(())
143	}
144
145	pub(crate) fn finish(&mut self, fusion_membership: &[bool]) -> Result<()> {
146		for (index, count) in self.executable_node_counts.iter().copied().enumerate() {
147			if count == 0 {
148				return Err(Error::failed_precondition(format!(
149					"semantic operation {index} has no executable lowering"
150				)));
151			}
152			if count == 1 && !fusion_membership[index] {
153				self.direct_op_count = self.direct_op_count.saturating_add(1);
154			}
155			if count > 1 {
156				self.decomposed_op_count = self.decomposed_op_count.saturating_add(1);
157			}
158			if fusion_membership[index] {
159				self.fused_op_count = self.fused_op_count.saturating_add(1);
160			}
161			self.maximum_nodes_per_op = self.maximum_nodes_per_op.max(count);
162		}
163		Ok(())
164	}
165}
166
167/// Logical access mode derived from an operation contract.
168#[non_exhaustive]
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170pub enum SemanticAccessMode {
171	/// Read without semantic mutation.
172	Read,
173	/// Write without reading the prior value.
174	Write,
175	/// Read and semantically mutate the same value.
176	ReadWrite,
177}
178
179impl SemanticAccessMode {
180	/// Return the stable semantic-report token.
181	pub const fn token(self) -> &'static str {
182		match self {
183			Self::Read => "read",
184			Self::Write => "write",
185			Self::ReadWrite => "read_write",
186		}
187	}
188}
189
190/// Handle-free description of one logical value.
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub struct SemanticValueDesc {
193	id: Option<SemanticValueId>,
194	name: String,
195	kind: OpValueKind,
196	shape: Vec<usize>,
197	strides: Vec<isize>,
198	dtype: DType,
199	byte_offset: u64,
200	external: bool,
201	virtual_value: bool,
202	producer: Option<SemanticOpId>,
203	view_source: Option<SemanticValueId>,
204	view_byte_offset: i64,
205}
206
207impl SemanticValueDesc {
208	/// Construct a dense handle-free value description.
209	pub fn new(
210		name: impl Into<String>,
211		kind: OpValueKind,
212		shape: impl Into<Vec<usize>>,
213		dtype: DType,
214	) -> Result<Self> {
215		let shape = shape.into();
216		let strides = dense_strides(&shape)?;
217		Ok(Self {
218			id: None,
219			name: name.into(),
220			kind,
221			shape,
222			strides,
223			dtype,
224			byte_offset: 0,
225			external: false,
226			virtual_value: false,
227			producer: None,
228			view_source: None,
229			view_byte_offset: 0,
230		})
231	}
232
233	/// Mark whether storage is supplied from outside the captured graph.
234	pub const fn external(mut self, external: bool) -> Self {
235		self.external = external;
236		self
237	}
238
239	/// Mark whether the value should be materialized only during lowering.
240	pub const fn virtual_value(mut self, virtual_value: bool) -> Self {
241		self.virtual_value = virtual_value;
242		self
243	}
244
245	/// Set the captured absolute byte offset within a storage identity.
246	pub const fn byte_offset(mut self, byte_offset: u64) -> Self {
247		self.byte_offset = byte_offset;
248		self
249	}
250
251	/// Replace dense strides with explicit element strides.
252	pub fn strides(mut self, strides: impl Into<Vec<isize>>) -> Result<Self> {
253		let strides = strides.into();
254		if strides.len() != self.shape.len() || strides.iter().any(|stride| *stride < 0) {
255			return Err(Error::invalid_argument(
256				"semantic value strides must be non-negative and match shape rank",
257			));
258		}
259		self.strides = strides;
260		Ok(self)
261	}
262
263	/// Return the graph-assigned identity, if this value has been admitted.
264	pub const fn id(&self) -> Option<SemanticValueId> {
265		self.id
266	}
267
268	/// Return the diagnostic name.
269	pub fn name(&self) -> &str {
270		&self.name
271	}
272
273	/// Return the semantic value kind.
274	pub const fn kind(&self) -> OpValueKind {
275		self.kind
276	}
277
278	/// Return the logical shape.
279	pub fn shape(&self) -> &[usize] {
280		&self.shape
281	}
282
283	/// Return element strides.
284	pub fn strides_ref(&self) -> &[isize] {
285		&self.strides
286	}
287
288	/// Return the scalar dtype.
289	pub const fn dtype(&self) -> DType {
290		self.dtype
291	}
292
293	/// Return the absolute byte offset within captured storage.
294	pub const fn byte_offset_value(&self) -> u64 {
295		self.byte_offset
296	}
297
298	/// Return whether storage enters from outside this graph.
299	pub const fn is_external(&self) -> bool {
300		self.external
301	}
302
303	/// Return whether lowering owns materialization.
304	pub const fn is_virtual(&self) -> bool {
305		self.virtual_value
306	}
307
308	/// Return the producing semantic operation, if any.
309	pub const fn producer(&self) -> Option<SemanticOpId> {
310		self.producer
311	}
312
313	/// Return the earlier value from which this metadata-only view derives.
314	pub const fn view_source(&self) -> Option<SemanticValueId> {
315		self.view_source
316	}
317
318	/// Return the signed byte delta from the view source.
319	pub const fn view_byte_offset(&self) -> i64 {
320		self.view_byte_offset
321	}
322}
323
324/// One merged semantic value access made by an operation.
325#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub struct SemanticValueAccess {
327	value: SemanticValueId,
328	mode: SemanticAccessMode,
329}
330
331impl SemanticValueAccess {
332	/// Return the accessed value.
333	pub const fn value(self) -> SemanticValueId {
334		self.value
335	}
336
337	/// Return the merged access mode.
338	pub const fn mode(self) -> SemanticAccessMode {
339		self.mode
340	}
341}
342
343/// Proven storage alias from one fresh semantic output version to its input.
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345pub struct SemanticAliasDesc {
346	output: SemanticValueId,
347	input: SemanticValueId,
348}
349
350impl SemanticAliasDesc {
351	/// Return the aliasing output.
352	pub const fn output(self) -> SemanticValueId {
353		self.output
354	}
355
356	/// Return the aliased input.
357	pub const fn input(self) -> SemanticValueId {
358		self.input
359	}
360}
361
362/// Provenance between one forward output and its autograd tape expansion.
363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
364pub struct SemanticAutogradDesc {
365	forward_op: SemanticOpId,
366	output: SemanticValueId,
367	output_index: usize,
368	sequence: u64,
369	backward_first_op: Option<SemanticOpId>,
370	backward_op_count: usize,
371	backward_expanded: bool,
372}
373
374impl SemanticAutogradDesc {
375	/// Return the forward operation.
376	pub const fn forward_op(self) -> SemanticOpId {
377		self.forward_op
378	}
379
380	/// Return the attached forward output.
381	pub const fn output(self) -> SemanticValueId {
382		self.output
383	}
384
385	/// Return the output's index within the forward contract.
386	pub const fn output_index(self) -> usize {
387		self.output_index
388	}
389
390	/// Return the nonzero tape sequence.
391	pub const fn sequence(self) -> u64 {
392		self.sequence
393	}
394
395	/// Return the first operation in the expanded backward range.
396	pub const fn backward_first_op(self) -> Option<SemanticOpId> {
397		self.backward_first_op
398	}
399
400	/// Return the number of operations in the expanded backward range.
401	pub const fn backward_op_count(self) -> usize {
402		self.backward_op_count
403	}
404
405	/// Return whether the backward range has been attached.
406	pub const fn is_backward_expanded(self) -> bool {
407		self.backward_expanded
408	}
409}
410
411/// One mathematical or domain operation before executable lowering.
412#[derive(Clone, Debug, PartialEq)]
413pub struct SemanticOpDesc {
414	id: SemanticOpId,
415	name: &'static str,
416	contract_hash: u64,
417	differentiation: OpDifferentiation,
418	lowering: OpLowering,
419	control_flow: crate::OpControlFlow,
420	optional_input_mask: u8,
421	inputs: Vec<Option<SemanticValueId>>,
422	outputs: Vec<SemanticValueId>,
423	attributes: Vec<OpAttribute>,
424	accesses: Vec<SemanticValueAccess>,
425	mutated_inputs: Vec<SemanticValueId>,
426	aliases: Vec<SemanticAliasDesc>,
427	control_dependencies: Vec<SemanticOpId>,
428	backward_of: Option<SemanticOpId>,
429	backward_sequence: u64,
430}
431
432impl SemanticOpDesc {
433	/// Return the graph-local operation identity.
434	pub const fn id(&self) -> SemanticOpId {
435		self.id
436	}
437
438	/// Return the stable qualified operation name.
439	pub const fn name(&self) -> &'static str {
440		self.name
441	}
442
443	/// Return the schema-derived operation contract hash.
444	pub const fn contract_hash(&self) -> u64 {
445		self.contract_hash
446	}
447
448	/// Return the differentiation behavior.
449	pub const fn differentiation(&self) -> OpDifferentiation {
450		self.differentiation
451	}
452
453	/// Return the requested lowering family.
454	pub const fn lowering(&self) -> OpLowering {
455		self.lowering
456	}
457
458	/// Return the semantic control-flow class.
459	pub const fn control_flow(&self) -> crate::OpControlFlow {
460		self.control_flow
461	}
462
463	/// Return logical input identities; `None` preserves an absent optional slot.
464	pub fn inputs(&self) -> &[Option<SemanticValueId>] {
465		&self.inputs
466	}
467
468	/// Return logical output identities.
469	pub fn outputs(&self) -> &[SemanticValueId] {
470		&self.outputs
471	}
472
473	/// Return ordered non-value semantic inputs.
474	pub fn attributes(&self) -> &[OpAttribute] {
475		&self.attributes
476	}
477
478	/// Return merged logical accesses.
479	pub fn accesses(&self) -> &[SemanticValueAccess] {
480		&self.accesses
481	}
482
483	/// Return semantically mutated inputs.
484	pub fn mutated_inputs(&self) -> &[SemanticValueId] {
485		&self.mutated_inputs
486	}
487
488	/// Return output-to-input aliases.
489	pub fn aliases(&self) -> &[SemanticAliasDesc] {
490		&self.aliases
491	}
492
493	/// Return explicit control dependencies.
494	pub fn control_dependencies(&self) -> &[SemanticOpId] {
495		&self.control_dependencies
496	}
497
498	/// Return the fixed-input optionality mask preserved from the schema.
499	pub const fn optional_input_mask(&self) -> u8 {
500		self.optional_input_mask
501	}
502
503	/// Return the forward operation owning this backward operation.
504	pub const fn backward_of(&self) -> Option<SemanticOpId> {
505		self.backward_of
506	}
507
508	/// Return the owning autograd tape sequence.
509	pub const fn backward_sequence(&self) -> u64 {
510		self.backward_sequence
511	}
512}
513
514/// Canonical semantic graph, deliberately independent of Vulkan objects.
515#[derive(Clone, Debug)]
516pub struct SemanticGraph {
517	values: Vec<SemanticValueDesc>,
518	operations: Vec<SemanticOpDesc>,
519	autograd: Vec<SemanticAutogradDesc>,
520	generation: u64,
521}
522
523impl Default for SemanticGraph {
524	fn default() -> Self {
525		Self::new()
526	}
527}
528
529impl SemanticGraph {
530	/// Construct an empty first-generation graph.
531	pub const fn new() -> Self {
532		Self {
533			values: Vec::new(),
534			operations: Vec::new(),
535			autograd: Vec::new(),
536			generation: 1,
537		}
538	}
539
540	pub(crate) fn take_recording(&mut self) -> Result<Self> {
541		let generation = self
542			.generation
543			.checked_add(1)
544			.ok_or_else(|| Error::resource_exhausted("semantic graph generation exhausted"))?;
545		Ok(std::mem::replace(
546			self,
547			Self {
548				values: Vec::new(),
549				operations: Vec::new(),
550				autograd: Vec::new(),
551				generation,
552			},
553		))
554	}
555
556	/// Add a handle-free value and assign its canonical identity.
557	pub fn add_value(&mut self, mut value: SemanticValueDesc) -> Result<SemanticValueId> {
558		if value.id.is_some()
559			|| value.producer.is_some()
560			|| value.view_source.is_some()
561			|| value.view_byte_offset != 0
562		{
563			return Err(Error::invalid_argument(
564				"semantic value identity and provenance are assigned by the graph",
565			));
566		}
567		let id = SemanticValueId(next_u32(self.values.len(), "semantic value")?);
568		value.id = Some(id);
569		self.values.push(value);
570		Ok(id)
571	}
572
573	/// Record a metadata-only value derived from an earlier value.
574	pub fn add_view(
575		&mut self,
576		source: SemanticValueId,
577		view: SemanticValueId,
578		byte_offset: i64,
579	) -> Result<()> {
580		if source.usize() >= self.values.len() || view.usize() >= self.values.len() {
581			return Err(Error::out_of_range(
582				"semantic view references an unknown value",
583			));
584		}
585		if source >= view {
586			return Err(Error::invalid_argument(
587				"semantic view source must precede its derived value",
588			));
589		}
590		let source_value = &self.values[source.usize()];
591		let source_kind = source_value.kind;
592		let source_dtype = source_value.dtype;
593		let source_offset = source_value.byte_offset;
594		let view_value = &self.values[view.usize()];
595		if view_value.producer.is_some() {
596			return Err(Error::invalid_argument(
597				"semantic view cannot also have an operation producer",
598			));
599		}
600		if view_value.view_source.is_some() {
601			return Err(Error::already_exists(
602				"semantic value already has a view source",
603			));
604		}
605		if view_value.kind != source_kind || view_value.dtype != source_dtype {
606			return Err(Error::invalid_argument(
607				"semantic view must preserve value kind and dtype",
608			));
609		}
610		if view_value.external {
611			return Err(Error::invalid_argument(
612				"semantic view cannot be an external value",
613			));
614		}
615		let source_offset = i64::try_from(source_offset)
616			.map_err(|_| Error::out_of_range("semantic view source byte offset exceeds i64"))?;
617		let absolute_offset = source_offset
618			.checked_add(byte_offset)
619			.filter(|offset| *offset >= 0)
620			.ok_or_else(|| Error::out_of_range("semantic view byte offset is invalid"))?;
621		let view_value = &mut self.values[view.usize()];
622		view_value.view_source = Some(source);
623		view_value.view_byte_offset = byte_offset;
624		view_value.byte_offset = absolute_offset as u64;
625		Ok(())
626	}
627
628	/// Add one schema-owned semantic operation transactionally.
629	pub fn add_operation(
630		&mut self,
631		contract: OperationContract,
632		inputs: &[Option<SemanticValueId>],
633		outputs: &[SemanticValueId],
634		control_dependencies: &[SemanticOpId],
635		attributes: &[OpAttribute],
636	) -> Result<SemanticOpId> {
637		if !contract.validate(attributes) {
638			return Err(Error::invalid_argument(
639				"semantic operation has an invalid schema contract or attribute signature",
640			));
641		}
642		if !contract.accepts_input_count(inputs.len())
643			|| !contract.accepts_output_count(outputs.len())
644			|| !contract.variadic_alias_counts_match(inputs.len(), outputs.len())
645		{
646			return Err(Error::invalid_argument(
647				"semantic operation arity does not match its contract",
648			));
649		}
650		for (index, input) in inputs.iter().enumerate() {
651			let Some(input) = input else {
652				if contract.input_is_optional(index) {
653					continue;
654				}
655				return Err(Error::invalid_argument(
656					"semantic operation omits a required input",
657				));
658			};
659			let value = self
660				.values
661				.get(input.usize())
662				.ok_or_else(|| Error::out_of_range("semantic operation has an unknown input"))?;
663			if Some(value.kind) != contract.input_kind(index) {
664				return Err(Error::invalid_argument(
665					"semantic operation input kind does not match its contract",
666				));
667			}
668		}
669		for (index, output) in outputs.iter().copied().enumerate() {
670			let value = self
671				.values
672				.get(output.usize())
673				.ok_or_else(|| Error::out_of_range("semantic operation has an unknown output"))?;
674			if Some(value.kind) != contract.output_kind(index) {
675				return Err(Error::invalid_argument(
676					"semantic operation output kind does not match its contract",
677				));
678			}
679			if value.producer.is_some() {
680				return Err(Error::already_exists(
681					"semantic operation output already has a producer",
682				));
683			}
684			if inputs.contains(&Some(output)) {
685				return Err(Error::invalid_argument(
686					"semantic operation outputs must be fresh SSA values",
687				));
688			}
689			if let Some(alias_input) = contract.alias_input(index) {
690				if alias_input >= inputs.len() {
691					return Err(Error::out_of_range(
692						"semantic output alias references an unknown input",
693					));
694				}
695				if contract.input_is_optional(alias_input) {
696					return Err(Error::invalid_argument(
697						"semantic output cannot alias an optional input",
698					));
699				}
700			}
701		}
702		let mut seen_dependencies = BTreeSet::new();
703		for dependency in control_dependencies {
704			if dependency.usize() >= self.operations.len() {
705				return Err(Error::out_of_range(
706					"semantic control dependency must reference an earlier operation",
707				));
708			}
709			if !seen_dependencies.insert(*dependency) {
710				return Err(Error::already_exists(
711					"semantic control dependency is duplicated",
712				));
713			}
714		}
715
716		let id = SemanticOpId(next_u32(self.operations.len(), "semantic operation")?);
717		let mut operation = SemanticOpDesc {
718			id,
719			name: contract.name(),
720			contract_hash: contract.hash(),
721			differentiation: contract.differentiation(),
722			lowering: contract.lowering(),
723			control_flow: contract.control_flow(),
724			optional_input_mask: contract.optional_input_mask(),
725			inputs: inputs.to_vec(),
726			outputs: outputs.to_vec(),
727			attributes: attributes.to_vec(),
728			accesses: Vec::new(),
729			mutated_inputs: Vec::new(),
730			aliases: Vec::new(),
731			control_dependencies: control_dependencies.to_vec(),
732			backward_of: None,
733			backward_sequence: 0,
734		};
735		if contract.effects_value().contains(OpEffect::READ_INPUTS) {
736			for (index, input) in inputs.iter().copied().enumerate() {
737				if let Some(input) = input {
738					merge_access(
739						&mut operation.accesses,
740						input,
741						if contract.mutates_input(index) {
742							SemanticAccessMode::ReadWrite
743						} else {
744							SemanticAccessMode::Read
745						},
746					);
747				}
748			}
749		}
750		if contract.effects_value().contains(OpEffect::WRITE_OUTPUTS) {
751			for output in outputs {
752				merge_access(&mut operation.accesses, *output, SemanticAccessMode::Write);
753			}
754		}
755		for (index, input) in inputs.iter().copied().enumerate() {
756			if !contract.mutates_input(index) {
757				continue;
758			}
759			let input = input.ok_or_else(|| {
760				Error::invalid_argument("semantic operation cannot mutate an absent input")
761			})?;
762			operation.mutated_inputs.push(input);
763			if !contract.effects_value().contains(OpEffect::READ_INPUTS) {
764				merge_access(&mut operation.accesses, input, SemanticAccessMode::Write);
765			}
766		}
767		for (index, output) in outputs.iter().copied().enumerate() {
768			if let Some(alias_input) = contract.alias_input(index) {
769				let input = inputs[alias_input]
770					.ok_or_else(|| Error::invalid_argument("semantic output cannot alias an absent input"))?;
771				operation.aliases.push(SemanticAliasDesc { output, input });
772			}
773		}
774
775		for output in outputs {
776			self.values[output.usize()].producer = Some(id);
777		}
778		self.operations.push(operation);
779		Ok(id)
780	}
781
782	/// Attach a reverse-differentiable forward output to a tape sequence.
783	pub fn attach_autograd(
784		&mut self,
785		forward_op: SemanticOpId,
786		output_index: usize,
787		sequence: u64,
788	) -> Result<()> {
789		let operation = self
790			.operations
791			.get(forward_op.usize())
792			.ok_or_else(|| Error::out_of_range("semantic autograd references an unknown operation"))?;
793		if operation.differentiation != OpDifferentiation::Reverse {
794			return Err(Error::invalid_argument(
795				"semantic autograd requires a reverse-mode operation contract",
796			));
797		}
798		let output = *operation
799			.outputs
800			.get(output_index)
801			.ok_or_else(|| Error::out_of_range("semantic autograd references an unknown output"))?;
802		if sequence == 0 {
803			return Err(Error::invalid_argument(
804				"semantic autograd requires a nonzero tape sequence",
805			));
806		}
807		if self
808			.autograd
809			.iter()
810			.any(|entry| entry.output == output || entry.sequence == sequence)
811		{
812			return Err(Error::already_exists(
813				"semantic output or tape sequence is already attached",
814			));
815		}
816		self.autograd.push(SemanticAutogradDesc {
817			forward_op,
818			output,
819			output_index,
820			sequence,
821			backward_first_op: None,
822			backward_op_count: 0,
823			backward_expanded: false,
824		});
825		Ok(())
826	}
827
828	/// Complete one tape attachment with its contiguous backward operation range.
829	pub fn complete_autograd(
830		&mut self,
831		forward_op: SemanticOpId,
832		sequence: u64,
833		backward_first_op: SemanticOpId,
834		backward_op_count: usize,
835	) -> Result<()> {
836		let attachment_index = self
837			.autograd
838			.iter()
839			.position(|entry| entry.forward_op == forward_op && entry.sequence == sequence)
840			.ok_or_else(|| Error::not_found("semantic backward expansion has no tape attachment"))?;
841		if self.autograd[attachment_index].backward_expanded {
842			return Err(Error::already_exists(
843				"semantic backward expansion is already complete",
844			));
845		}
846		let first = backward_first_op.usize();
847		let end = first
848			.checked_add(backward_op_count)
849			.ok_or_else(|| Error::out_of_range("semantic backward operation range overflows"))?;
850		if end > self.operations.len() {
851			return Err(Error::out_of_range(
852				"semantic backward operation range is outside the graph",
853			));
854		}
855		for operation in &self.operations[first..end] {
856			if operation.id <= forward_op {
857				return Err(Error::invalid_argument(
858					"semantic backward expansion must follow its forward operation",
859				));
860			}
861			if operation.backward_of.is_some() {
862				return Err(Error::already_exists(
863					"semantic operation already belongs to a backward expansion",
864				));
865			}
866		}
867		for operation in &mut self.operations[first..end] {
868			operation.backward_of = Some(forward_op);
869			operation.backward_sequence = sequence;
870		}
871		let attachment = &mut self.autograd[attachment_index];
872		attachment.backward_first_op = Some(backward_first_op);
873		attachment.backward_op_count = backward_op_count;
874		attachment.backward_expanded = true;
875		Ok(())
876	}
877
878	/// Validate canonical identities and every graph-local provenance edge.
879	pub fn validate(&self) -> Result<()> {
880		for (index, value) in self.values.iter().enumerate() {
881			if value.id.map(SemanticValueId::usize) != Some(index) {
882				return Err(Error::internal("semantic value ids are not canonical"));
883			}
884			if value
885				.producer
886				.is_some_and(|producer| producer.usize() >= self.operations.len())
887			{
888				return Err(Error::internal("semantic value has an invalid producer"));
889			}
890			if let Some(source) = value.view_source {
891				if source.usize() >= index
892					|| value.producer.is_some()
893					|| value.external
894					|| self.values[source.usize()].kind != value.kind
895					|| self.values[source.usize()].dtype != value.dtype
896				{
897					return Err(Error::internal("semantic value has an invalid view source"));
898				}
899				let source_offset = i64::try_from(self.values[source.usize()].byte_offset)
900					.map_err(|_| Error::internal("semantic view source offset exceeds i64"))?;
901				let absolute = source_offset
902					.checked_add(value.view_byte_offset)
903					.filter(|offset| *offset >= 0)
904					.ok_or_else(|| Error::internal("semantic view offset is inconsistent"))?;
905				if value.byte_offset != absolute as u64 {
906					return Err(Error::internal("semantic view offset is inconsistent"));
907				}
908			}
909		}
910		for (index, operation) in self.operations.iter().enumerate() {
911			if operation.id.usize() != index || operation.name.is_empty() || operation.contract_hash == 0
912			{
913				return Err(Error::internal("semantic operation identity is invalid"));
914			}
915			for (input_index, input) in operation.inputs.iter().enumerate() {
916				if input.is_none()
917					&& input_index < u8::BITS as usize
918					&& operation.optional_input_mask & (1 << input_index) != 0
919				{
920					continue;
921				}
922				if input.is_none_or(|value| value.usize() >= self.values.len()) {
923					return Err(Error::internal("semantic operation has an invalid input"));
924				}
925			}
926			for output in &operation.outputs {
927				if output.usize() >= self.values.len()
928					|| self.values[output.usize()].producer != Some(operation.id)
929				{
930					return Err(Error::internal(
931						"semantic producer/output relationship is invalid",
932					));
933				}
934			}
935			let mut names = BTreeSet::new();
936			for attribute in &operation.attributes {
937				if !attribute.validate() || !names.insert(attribute.name()) {
938					return Err(Error::internal("semantic operation has invalid attributes"));
939				}
940			}
941			if operation
942				.accesses
943				.iter()
944				.any(|access| access.value.usize() >= self.values.len())
945				|| operation
946					.mutated_inputs
947					.iter()
948					.any(|value| value.usize() >= self.values.len())
949				|| operation.aliases.iter().any(|alias| {
950					alias.output.usize() >= self.values.len()
951						|| alias.input.usize() >= self.values.len()
952						|| alias.output == alias.input
953						|| !operation.outputs.contains(&alias.output)
954						|| !operation.inputs.contains(&Some(alias.input))
955				}) {
956				return Err(Error::internal(
957					"semantic operation has invalid value provenance",
958				));
959			}
960			if operation.mutated_inputs.iter().any(|mutated| {
961				operation
962					.aliases
963					.iter()
964					.filter(|alias| alias.input == *mutated)
965					.count()
966					!= 1
967			}) {
968				return Err(Error::internal(
969					"semantic mutation does not produce one fresh alias version",
970				));
971			}
972			if operation
973				.control_dependencies
974				.iter()
975				.any(|dependency| dependency.usize() >= index)
976			{
977				return Err(Error::internal(
978					"semantic operation has an invalid control dependency",
979				));
980			}
981			if operation
982				.backward_of
983				.is_some_and(|forward| forward.usize() >= index || operation.backward_sequence == 0)
984			{
985				return Err(Error::internal(
986					"semantic backward operation has invalid provenance",
987				));
988			}
989		}
990		let mut outputs = BTreeSet::new();
991		let mut sequences = BTreeSet::new();
992		for attachment in &self.autograd {
993			let operation = self
994				.operations
995				.get(attachment.forward_op.usize())
996				.ok_or_else(|| Error::internal("semantic autograd has an invalid forward operation"))?;
997			if operation.differentiation != OpDifferentiation::Reverse
998				|| operation.outputs.get(attachment.output_index) != Some(&attachment.output)
999				|| attachment.sequence == 0
1000				|| !outputs.insert(attachment.output)
1001				|| !sequences.insert(attachment.sequence)
1002			{
1003				return Err(Error::internal("semantic autograd attachment is invalid"));
1004			}
1005			if attachment.backward_expanded {
1006				let first = attachment.backward_first_op.ok_or_else(|| {
1007					Error::internal("expanded semantic backward range has no first operation")
1008				})?;
1009				let end = first
1010					.usize()
1011					.checked_add(attachment.backward_op_count)
1012					.filter(|end| *end <= self.operations.len())
1013					.ok_or_else(|| Error::internal("semantic backward range is invalid"))?;
1014				for backward in &self.operations[first.usize()..end] {
1015					if backward.backward_of != Some(attachment.forward_op)
1016						|| backward.backward_sequence != attachment.sequence
1017					{
1018						return Err(Error::internal(
1019							"semantic backward range disagrees with its operations",
1020						));
1021					}
1022				}
1023			} else if attachment.backward_first_op.is_some() || attachment.backward_op_count != 0 {
1024				return Err(Error::internal(
1025					"incomplete semantic backward attachment owns a range",
1026				));
1027			}
1028		}
1029		Ok(())
1030	}
1031
1032	/// Replace this empty graph with a validated clone of `source`.
1033	pub fn copy_from(&mut self, source: &Self) -> Result<()> {
1034		if std::ptr::eq(self, source) {
1035			return Err(Error::invalid_argument(
1036				"semantic graph cannot copy onto itself",
1037			));
1038		}
1039		if !self.values.is_empty() || !self.operations.is_empty() || !self.autograd.is_empty() {
1040			return Err(Error::failed_precondition(
1041				"semantic graph copy requires an empty destination",
1042			));
1043		}
1044		source.validate()?;
1045		self.values.clone_from(&source.values);
1046		self.operations.clone_from(&source.operations);
1047		self.autograd.clone_from(&source.autograd);
1048		Ok(())
1049	}
1050
1051	/// Return a value by graph-local identity.
1052	pub fn find_value(&self, id: SemanticValueId) -> Option<&SemanticValueDesc> {
1053		self.values.get(id.usize())
1054	}
1055
1056	/// Return all semantic values in canonical order.
1057	pub fn values(&self) -> &[SemanticValueDesc] {
1058		&self.values
1059	}
1060
1061	/// Return all semantic operations in canonical order.
1062	pub fn operations(&self) -> &[SemanticOpDesc] {
1063		&self.operations
1064	}
1065
1066	/// Return all autograd attachments in capture order.
1067	pub fn autograd(&self) -> &[SemanticAutogradDesc] {
1068		&self.autograd
1069	}
1070
1071	/// Return the deterministic donor-compatible semantic graph report as JSON.
1072	///
1073	/// The report is backend-independent and contains no storage handles,
1074	/// descriptors, addresses, kernels, or device policy.
1075	pub fn debug_report_json(&self, name: &str) -> String {
1076		let mut output = String::new();
1077		output.push_str("{\n  \"schema\": \"oa.semantic_graph.v2\",\n  \"name\": ");
1078		crate::core::push_json_string(&mut output, name);
1079		output.push_str(",\n  \"values\": [");
1080		for (index, value) in self.values.iter().enumerate() {
1081			output.push_str(if index == 0 { "\n" } else { ",\n" });
1082			crate::core::push_format(
1083				&mut output,
1084				format_args!(
1085					"    {{\"id\": {}, \"name\": ",
1086					value
1087						.id
1088						.expect("validated graph value must have an identity")
1089						.index()
1090				),
1091			);
1092			crate::core::push_json_string(&mut output, &value.name);
1093			output.push_str(", \"kind\": ");
1094			crate::core::push_json_string(&mut output, value.kind.token());
1095			output.push_str(", \"dtype\": ");
1096			crate::core::push_json_string(&mut output, dtype_report_token(value.dtype));
1097			output.push_str(", \"shape\": [");
1098			push_usize_list(&mut output, &value.shape);
1099			crate::core::push_format(
1100				&mut output,
1101				format_args!(
1102					"], \"byte_offset\": {}, \"external\": {}, \"virtual\": {}, \"strides\": [",
1103					value.byte_offset, value.external, value.virtual_value
1104				),
1105			);
1106			push_isize_list(&mut output, &value.strides);
1107			output.push_str("], \"view_source\": ");
1108			push_optional_value_id(&mut output, value.view_source);
1109			crate::core::push_format(
1110				&mut output,
1111				format_args!(
1112					", \"view_byte_offset\": {}, \"producer\": ",
1113					value.view_byte_offset
1114				),
1115			);
1116			push_optional_op_id(&mut output, value.producer);
1117			output.push('}');
1118		}
1119		if !self.values.is_empty() {
1120			output.push('\n');
1121		}
1122		output.push_str("  ],\n  \"operations\": [");
1123		for (index, operation) in self.operations.iter().enumerate() {
1124			output.push_str(if index == 0 { "\n" } else { ",\n" });
1125			crate::core::push_format(
1126				&mut output,
1127				format_args!("    {{\"id\": {}, \"name\": ", operation.id.index()),
1128			);
1129			crate::core::push_json_string(&mut output, operation.name);
1130			crate::core::push_format(
1131				&mut output,
1132				format_args!(
1133					", \"contract_hash\": \"0x{:016x}\", \"lowering\": ",
1134					operation.contract_hash
1135				),
1136			);
1137			crate::core::push_json_string(&mut output, operation.lowering.token());
1138			output.push_str(", \"differentiation\": ");
1139			crate::core::push_json_string(&mut output, operation.differentiation.token());
1140			output.push_str(", \"control_flow\": ");
1141			crate::core::push_json_string(&mut output, operation.control_flow.token());
1142			output.push_str(", \"inputs\": [");
1143			for (input_index, input) in operation.inputs.iter().copied().enumerate() {
1144				if input_index != 0 {
1145					output.push_str(", ");
1146				}
1147				push_optional_value_id(&mut output, input);
1148			}
1149			output.push_str("], \"outputs\": [");
1150			push_value_ids(&mut output, &operation.outputs);
1151			output.push_str("], \"attributes\": [");
1152			for (attribute_index, attribute) in operation.attributes.iter().enumerate() {
1153				if attribute_index != 0 {
1154					output.push_str(", ");
1155				}
1156				output.push_str("{\"name\": ");
1157				crate::core::push_json_string(&mut output, attribute.name());
1158				output.push_str(", \"kind\": ");
1159				crate::core::push_json_string(&mut output, attribute.kind().token());
1160				output.push_str(", \"value\": ");
1161				push_attribute_value(&mut output, attribute);
1162				output.push('}');
1163			}
1164			output.push_str("], \"accesses\": [");
1165			for (access_index, access) in operation.accesses.iter().enumerate() {
1166				if access_index != 0 {
1167					output.push_str(", ");
1168				}
1169				crate::core::push_format(
1170					&mut output,
1171					format_args!("{{\"value\": {}, \"mode\": ", access.value.index()),
1172				);
1173				crate::core::push_json_string(&mut output, access.mode.token());
1174				output.push('}');
1175			}
1176			output.push_str("], \"mutated_inputs\": [");
1177			push_value_ids(&mut output, &operation.mutated_inputs);
1178			output.push_str("], \"aliases\": [");
1179			for (alias_index, alias) in operation.aliases.iter().enumerate() {
1180				if alias_index != 0 {
1181					output.push_str(", ");
1182				}
1183				crate::core::push_format(
1184					&mut output,
1185					format_args!(
1186						"{{\"output\": {}, \"input\": {}}}",
1187						alias.output.index(),
1188						alias.input.index()
1189					),
1190				);
1191			}
1192			output.push_str("], \"control_dependencies\": [");
1193			push_op_ids(&mut output, &operation.control_dependencies);
1194			output.push_str("], \"backward_of\": ");
1195			push_optional_op_id(&mut output, operation.backward_of);
1196			crate::core::push_format(
1197				&mut output,
1198				format_args!(", \"backward_sequence\": {}}}", operation.backward_sequence),
1199			);
1200		}
1201		if !self.operations.is_empty() {
1202			output.push('\n');
1203		}
1204		output.push_str("  ],\n  \"autograd\": [");
1205		for (index, attachment) in self.autograd.iter().enumerate() {
1206			output.push_str(if index == 0 { "\n" } else { ",\n" });
1207			crate::core::push_format(
1208				&mut output,
1209				format_args!(
1210					"    {{\"forward_operation\": {}, \"output\": {}, \"output_index\": {}, \"sequence\": {}, \"backward_expanded\": {}, \"backward_first_operation\": ",
1211					attachment.forward_op.index(),
1212					attachment.output.index(),
1213					attachment.output_index,
1214					attachment.sequence,
1215					attachment.backward_expanded,
1216				),
1217			);
1218			push_optional_op_id(&mut output, attachment.backward_first_op);
1219			crate::core::push_format(
1220				&mut output,
1221				format_args!(
1222					", \"backward_operation_count\": {}}}",
1223					attachment.backward_op_count
1224				),
1225			);
1226		}
1227		if !self.autograd.is_empty() {
1228			output.push('\n');
1229		}
1230		output.push_str("  ]\n}\n");
1231		output
1232	}
1233
1234	/// Return the number of metadata-only views.
1235	pub fn view_count(&self) -> usize {
1236		self
1237			.values
1238			.iter()
1239			.filter(|value| value.view_source.is_some())
1240			.count()
1241	}
1242
1243	/// Return the generation incremented by each reset.
1244	pub const fn generation(&self) -> u64 {
1245		self.generation
1246	}
1247
1248	/// Clear all graph content and advance its finite generation.
1249	pub fn reset(&mut self) {
1250		self.values.clear();
1251		self.operations.clear();
1252		self.autograd.clear();
1253		self.generation = self.generation.checked_add(1).unwrap_or(1);
1254	}
1255}
1256
1257const fn dtype_report_token(dtype: DType) -> &'static str {
1258	match dtype {
1259		DType::U8 => "uint8",
1260		DType::F16 => "float16",
1261		DType::F32 => "float32",
1262		DType::I32 => "int32",
1263		DType::U32 => "uint32",
1264	}
1265}
1266
1267fn push_usize_list(output: &mut String, values: &[usize]) {
1268	for (index, value) in values.iter().enumerate() {
1269		if index != 0 {
1270			output.push_str(", ");
1271		}
1272		crate::core::push_format(output, format_args!("{value}"));
1273	}
1274}
1275
1276fn push_isize_list(output: &mut String, values: &[isize]) {
1277	for (index, value) in values.iter().enumerate() {
1278		if index != 0 {
1279			output.push_str(", ");
1280		}
1281		crate::core::push_format(output, format_args!("{value}"));
1282	}
1283}
1284
1285fn push_value_ids(output: &mut String, values: &[SemanticValueId]) {
1286	for (index, value) in values.iter().enumerate() {
1287		if index != 0 {
1288			output.push_str(", ");
1289		}
1290		crate::core::push_format(output, format_args!("{}", value.index()));
1291	}
1292}
1293
1294fn push_op_ids(output: &mut String, values: &[SemanticOpId]) {
1295	for (index, value) in values.iter().enumerate() {
1296		if index != 0 {
1297			output.push_str(", ");
1298		}
1299		crate::core::push_format(output, format_args!("{}", value.index()));
1300	}
1301}
1302
1303fn push_optional_value_id(output: &mut String, value: Option<SemanticValueId>) {
1304	if let Some(value) = value {
1305		crate::core::push_format(output, format_args!("{}", value.index()));
1306	} else {
1307		output.push_str("null");
1308	}
1309}
1310
1311fn push_optional_op_id(output: &mut String, value: Option<SemanticOpId>) {
1312	if let Some(value) = value {
1313		crate::core::push_format(output, format_args!("{}", value.index()));
1314	} else {
1315		output.push_str("null");
1316	}
1317}
1318
1319fn push_attribute_value(output: &mut String, attribute: &OpAttribute) {
1320	match attribute {
1321		OpAttribute::Boolean { value, .. } => {
1322			crate::core::push_format(output, format_args!("{value}"));
1323		}
1324		OpAttribute::SignedInteger { value, .. } => {
1325			crate::core::push_format(output, format_args!("{value}"));
1326		}
1327		OpAttribute::UnsignedInteger { value, .. } => {
1328			crate::core::push_format(output, format_args!("{value}"));
1329		}
1330		OpAttribute::Float { value, .. } if value.is_finite() => {
1331			crate::core::push_format(output, format_args!("{value}"));
1332		}
1333		OpAttribute::Float { .. } => output.push_str("null"),
1334		OpAttribute::String { value, .. } | OpAttribute::Enum { value, .. } => {
1335			crate::core::push_json_string(output, value);
1336		}
1337		OpAttribute::Shape { value, .. } => {
1338			output.push('[');
1339			push_usize_list(output, value);
1340			output.push(']');
1341		}
1342	}
1343}
1344
1345fn merge_access(
1346	accesses: &mut Vec<SemanticValueAccess>,
1347	value: SemanticValueId,
1348	mode: SemanticAccessMode,
1349) {
1350	if let Some(access) = accesses.iter_mut().find(|access| access.value == value) {
1351		if access.mode != mode {
1352			access.mode = SemanticAccessMode::ReadWrite;
1353		}
1354	} else {
1355		accesses.push(SemanticValueAccess { value, mode });
1356	}
1357}
1358
1359pub(crate) fn dense_strides(shape: &[usize]) -> Result<Vec<isize>> {
1360	let mut stride = 1_usize;
1361	let mut strides = vec![0_isize; shape.len()];
1362	for (index, dimension) in shape.iter().copied().enumerate().rev() {
1363		strides[index] = isize::try_from(stride)
1364			.map_err(|_| Error::invalid_argument("semantic value stride exceeds isize"))?;
1365		stride = stride
1366			.checked_mul(dimension)
1367			.ok_or_else(|| Error::invalid_argument("semantic value shape overflows usize"))?;
1368	}
1369	Ok(strides)
1370}
1371
1372fn next_u32(length: usize, noun: &str) -> Result<u32> {
1373	u32::try_from(length)
1374		.map_err(|_| Error::resource_exhausted(format!("{noun} identity space is exhausted")))
1375}