Skip to main content

oa/runtime/
plan.rs

1use std::sync::Arc;
2
3use std::{
4	cell::{Cell, RefCell},
5	fmt,
6};
7
8use crate::{Error, Matrix, Result, core::Element};
9
10use super::{
11	Buffer, BufferAccess, Device, EngineHandle, Event, RecordedCommandBuffer, ReusableCommandBuffer,
12	SemanticGraph, SemanticLoweringAnalysis, Storage,
13	device::NativeFlagBits,
14	dna::{DnnPlan, DnnPolicy, fusion},
15	graph::executable::{AccessState, ExecutableGraph, GraphNode},
16	session::{PendingExecution, SemanticStorageSnapshot, StableResourceSnapshot},
17};
18
19pub(super) mod serialization;
20
21/// Immutable snapshot of execution-plan diagnostics.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct ExecutionPlanDiagnostics {
24	graph_id: u64,
25	device_capability_identity: u64,
26	node_count: usize,
27	barrier_count: usize,
28	semantic_operation_count: usize,
29	semantic_autograd_attachment_count: usize,
30	semantic_autograd_expanded_count: usize,
31	semantic_backward_operation_count: usize,
32	schema_owned_node_count: usize,
33	compatibility_node_count: usize,
34	semantic_fused_operation_count: usize,
35	semantic_fused_node_count: usize,
36	maximum_semantic_operations_per_node: usize,
37	dnn_graph_hash: u64,
38	dnn_value_count: usize,
39	dnn_external_value_count: usize,
40	dnn_virtual_value_count: usize,
41	dnn_partition_count: usize,
42	dnn_recognized_partition_count: u32,
43	dnn_portable_partition_count: usize,
44	dnn_captured_operation_count: u32,
45	dnn_applied_partition_count: u32,
46	dnn_inherited_partition_count: u32,
47	dnn_fallback_partition_count: u32,
48	dnn_unexpected_fallback_count: u32,
49	input_binding_count: usize,
50	captured_resource_count: usize,
51	physical_resource_count: usize,
52	stable_replay_input_count: usize,
53	stable_transient_count: usize,
54	semantic_binding_count: usize,
55	observed_output_count: usize,
56	alias_candidate_count: usize,
57	alias_materialized_count: usize,
58	planned_alias_group_count: usize,
59	potential_alias_savings: usize,
60	materialized_alias_savings: usize,
61	descriptor_write_count: u64,
62	push_byte_count: usize,
63	peak_memory_bytes: usize,
64	cross_queue_edge_count: usize,
65	ownership_transfer_count: usize,
66	queue_run_count: usize,
67	command_recording_count: u64,
68	command_cache_hit_count: u64,
69	submission_count: u64,
70	input_rebinding_count: u64,
71	input_upload_count: u64,
72	fallback_count: u64,
73}
74
75impl ExecutionPlanDiagnostics {
76	/// Return the deterministic identity of the captured executable structure.
77	pub const fn graph_id(self) -> u64 {
78		self.graph_id
79	}
80
81	/// Return the stable device/driver/capability identity used to prepare this plan.
82	pub const fn device_capability_identity(self) -> u64 {
83		self.device_capability_identity
84	}
85
86	/// Return the number of captured executable nodes.
87	pub const fn node_count(self) -> usize {
88		self.node_count
89	}
90
91	/// Return the number of intra-graph buffer hazards requiring barriers.
92	pub const fn barrier_count(self) -> usize {
93		self.barrier_count
94	}
95
96	/// Return the number of canonical semantic operations.
97	pub const fn semantic_operation_count(self) -> usize {
98		self.semantic_operation_count
99	}
100
101	/// Return forward outputs attached to a reverse-mode tape.
102	pub const fn semantic_autograd_attachment_count(self) -> usize {
103		self.semantic_autograd_attachment_count
104	}
105
106	/// Return tape attachments with a completed backward operation range.
107	pub const fn semantic_autograd_expanded_count(self) -> usize {
108		self.semantic_autograd_expanded_count
109	}
110
111	/// Return semantic operations owned by completed backward ranges.
112	pub const fn semantic_backward_operation_count(self) -> usize {
113		self.semantic_backward_operation_count
114	}
115
116	/// Return executable nodes with schema-owned semantic provenance.
117	pub const fn schema_owned_node_count(self) -> usize {
118		self.schema_owned_node_count
119	}
120
121	/// Return executable nodes still using the compatibility route.
122	pub const fn compatibility_node_count(self) -> usize {
123		self.compatibility_node_count
124	}
125
126	/// Return semantic operations represented by multi-operation executable nodes.
127	pub const fn semantic_fused_operation_count(self) -> usize {
128		self.semantic_fused_operation_count
129	}
130
131	/// Return executable nodes that own more than one semantic operation.
132	pub const fn semantic_fused_node_count(self) -> usize {
133		self.semantic_fused_node_count
134	}
135
136	/// Return the widest semantic fusion represented by one executable node.
137	pub const fn maximum_semantic_operations_per_node(self) -> usize {
138		self.maximum_semantic_operations_per_node
139	}
140
141	/// Return the deterministic identity of DNN planning inputs.
142	pub const fn dnn_graph_hash(self) -> u64 {
143		self.dnn_graph_hash
144	}
145
146	/// Return semantic values admitted into DNN analysis.
147	pub const fn dnn_value_count(self) -> usize {
148		self.dnn_value_count
149	}
150
151	/// Return DNN values entering from outside captured work.
152	pub const fn dnn_external_value_count(self) -> usize {
153		self.dnn_external_value_count
154	}
155
156	/// Return DNN values reserved for lowering-time materialization.
157	pub const fn dnn_virtual_value_count(self) -> usize {
158		self.dnn_virtual_value_count
159	}
160
161	/// Return the number of DNN candidate partitions.
162	pub const fn dnn_partition_count(self) -> usize {
163		self.dnn_partition_count
164	}
165
166	/// Return partitions recognized by a schema-owned DNN provider role.
167	pub const fn dnn_recognized_partition_count(self) -> u32 {
168		self.dnn_recognized_partition_count
169	}
170
171	/// Return partitions retained on the portable executable path.
172	pub const fn dnn_portable_partition_count(self) -> usize {
173		self.dnn_portable_partition_count
174	}
175
176	/// Return semantic operations admitted into DNN analysis.
177	pub const fn dnn_captured_operation_count(self) -> u32 {
178		self.dnn_captured_operation_count
179	}
180
181	/// Return provider-recognized partitions that replaced source executable nodes.
182	pub const fn dnn_applied_partition_count(self) -> u32 {
183		self.dnn_applied_partition_count
184	}
185
186	/// Return recognized single-node partitions already using an admitted provider.
187	pub const fn dnn_inherited_partition_count(self) -> u32 {
188		self.dnn_inherited_partition_count
189	}
190
191	/// Return recognized partitions deliberately retained on their source lowering.
192	pub const fn dnn_fallback_partition_count(self) -> u32 {
193		self.dnn_fallback_partition_count
194	}
195
196	/// Return fallback partitions caused by a violated internal lowering invariant.
197	pub const fn dnn_unexpected_fallback_count(self) -> u32 {
198		self.dnn_unexpected_fallback_count
199	}
200
201	/// Return the number of Matrix inputs admitted for stable rebinding.
202	pub const fn input_binding_count(self) -> usize {
203		self.input_binding_count
204	}
205
206	/// Return the number of physical resources present in the captured graph.
207	pub const fn captured_resource_count(self) -> usize {
208		self.captured_resource_count
209	}
210
211	/// Return the number of distinct physical buffers used after memory planning.
212	pub const fn physical_resource_count(self) -> usize {
213		self.physical_resource_count
214	}
215
216	/// Return captured resources allocated before the replay-input seal.
217	pub const fn stable_replay_input_count(self) -> usize {
218		self.stable_replay_input_count
219	}
220
221	/// Return captured resources allocated after the replay-input seal.
222	///
223	/// These resources have stable allocation ordinals and known graph lifetimes,
224	/// but are not automatically eligible for physical aliasing.
225	pub const fn stable_transient_count(self) -> usize {
226		self.stable_transient_count
227	}
228
229	/// Return handle-free semantic value-to-resource bindings in the plan.
230	pub const fn semantic_binding_count(self) -> usize {
231		self.semantic_binding_count
232	}
233
234	/// Return captured resources explicitly retained as observable results.
235	pub const fn observed_output_count(self) -> usize {
236		self.observed_output_count
237	}
238
239	/// Return stable transients whose lifetimes and storage ownership are fully
240	/// explained and which are not externally live.
241	pub const fn alias_candidate_count(self) -> usize {
242		self.alias_candidate_count
243	}
244
245	/// Return logical resources rebound into a graph-lifetime alias arena.
246	pub const fn alias_materialized_count(self) -> usize {
247		self.alias_materialized_count
248	}
249
250	/// Return the number of nontrivial alias groups found by memory planning.
251	pub const fn planned_alias_group_count(self) -> usize {
252		self.planned_alias_group_count
253	}
254
255	/// Return logical bytes removable if every planned alias group materializes.
256	pub const fn potential_alias_savings(self) -> usize {
257		self.potential_alias_savings
258	}
259
260	/// Return logical bytes removed by materialized alias arenas.
261	pub const fn materialized_alias_savings(self) -> usize {
262		self.materialized_alias_savings
263	}
264
265	/// Return how many Vulkan command buffers were recorded for this plan.
266	pub const fn command_recording_count(self) -> u64 {
267		self.command_recording_count
268	}
269
270	/// Return descriptor writes issued while this plan was captured.
271	///
272	/// On the Core profile binding amortizes at buffer/image creation, so a
273	/// plan whose inputs were already bound reports zero — the bindless
274	/// recording-cost fact OA-CC-21 measures.
275	pub const fn descriptor_write_count(self) -> u64 {
276		self.descriptor_write_count
277	}
278
279	/// Return total push-constant bytes recorded per submission of this plan.
280	pub const fn push_byte_count(self) -> usize {
281		self.push_byte_count
282	}
283
284	/// Return peak live physical-buffer bytes across the plan's node order.
285	///
286	/// Interval sweep over captured resource lifetimes: aliased transients
287	/// share one physical buffer identity, so the peak counts each live
288	/// allocation once — the memory-planning number OA-CC-23 minimizes.
289	pub const fn peak_memory_bytes(self) -> usize {
290		self.peak_memory_bytes
291	}
292
293	/// Derived cross-queue timeline edges: hazards whose source and
294	/// destination nodes submit to different queue families (OA-CC-22).
295	pub const fn cross_queue_edge_count(self) -> usize {
296		self.cross_queue_edge_count
297	}
298
299	/// Derived queue-family ownership transfers required by cross-queue
300	/// hazards on exclusive-owned buffers.
301	pub const fn ownership_transfer_count(self) -> usize {
302		self.ownership_transfer_count
303	}
304
305	/// Ordered queue runs the plan splits into by resolved queue family
306	/// (OA-CC-22). One run submits on the compute family today; a mixed
307	/// plan produces one timeline-chained submission per run.
308	pub const fn queue_run_count(self) -> usize {
309		self.queue_run_count
310	}
311
312	/// Return how many submissions reused an already recorded command buffer.
313	pub const fn command_cache_hit_count(self) -> u64 {
314		self.command_cache_hit_count
315	}
316
317	/// Return how many plan submissions completed queue admission.
318	pub const fn submission_count(self) -> u64 {
319		self.submission_count
320	}
321
322	/// Return how many stable Matrix input bindings changed.
323	pub const fn input_rebinding_count(self) -> u64 {
324		self.input_rebinding_count
325	}
326
327	/// Return how many stable Matrix input slots received new host values.
328	pub const fn input_upload_count(self) -> u64 {
329		self.input_upload_count
330	}
331
332	/// Return the number of runtime fallback decisions made by this plan.
333	pub const fn fallback_count(self) -> u64 {
334		self.fallback_count
335	}
336}
337
338/// One buffer position in a stable input slot's triple-buffered staging ring.
339///
340/// `consumer` records the most recent submission event that reads this buffer;
341/// an upload may write it only after that event completes.
342struct InputStagingSlot {
343	buffer: Buffer,
344	consumer: RefCell<Option<Event>>,
345}
346
347struct MatrixInputBinding {
348	original: Buffer,
349	current: Buffer,
350	/// Ring of staging buffers. Slot zero is the captured input itself; further
351	/// slots are lazily allocated up to the staging depth.
352	staging: Vec<InputStagingSlot>,
353}
354
355/// Handle-free lifetime and stable-frame evidence for one captured resource.
356///
357/// Resource IDs follow deterministic graph-resource order and never expose a
358/// Vulkan handle or bindless descriptor. Alias-candidate state records completed
359/// liveness, external-output, and storage-owner qualification; physical storage
360/// is not shared until a later materialization stage succeeds transactionally.
361#[derive(Clone, Copy, Debug, PartialEq, Eq)]
362pub struct CapturedResourceDesc {
363	resource: u32,
364	byte_len: usize,
365	first_access: usize,
366	last_access: usize,
367	stable_replay_input: bool,
368	stable_transient: bool,
369	semantic_external: bool,
370	observed_output: bool,
371	capture_retained_owner_count: usize,
372	unaccounted_owner_count: usize,
373	alias_candidate: bool,
374	alias_materialized: bool,
375}
376
377impl CapturedResourceDesc {
378	pub const fn resource(self) -> u32 {
379		self.resource
380	}
381
382	pub const fn byte_len(self) -> usize {
383		self.byte_len
384	}
385
386	pub const fn first_access(self) -> usize {
387		self.first_access
388	}
389
390	pub const fn last_access(self) -> usize {
391		self.last_access
392	}
393
394	pub const fn stable_replay_input(self) -> bool {
395		self.stable_replay_input
396	}
397
398	pub const fn stable_transient(self) -> bool {
399		self.stable_transient
400	}
401
402	pub const fn semantic_external(self) -> bool {
403		self.semantic_external
404	}
405
406	pub const fn observed_output(self) -> bool {
407		self.observed_output
408	}
409
410	/// Return whether a semantic input, replay input, or observed output keeps
411	/// this resource externally live across plan execution.
412	pub const fn is_externally_live(self) -> bool {
413		self.semantic_external || self.stable_replay_input || self.observed_output
414	}
415
416	/// Return storage owners retained by the capture transaction itself.
417	pub const fn capture_retained_owner_count(self) -> usize {
418		self.capture_retained_owner_count
419	}
420
421	/// Return storage owners not explained by capture-owned structures.
422	pub const fn unaccounted_owner_count(self) -> usize {
423		self.unaccounted_owner_count
424	}
425
426	/// Return whether this resource passed liveness and ownership qualification.
427	///
428	/// This is planning evidence only; it does not mean alias storage was
429	/// materialized.
430	pub const fn alias_candidate(self) -> bool {
431		self.alias_candidate
432	}
433
434	pub const fn alias_materialized(self) -> bool {
435		self.alias_materialized
436	}
437}
438
439/// Position of one compiled specialization contract entry.
440///
441/// Donor: `oa::ExecutionBindingRole` in
442/// `oacpp/source/cpp/include/oa/runtime/executionPlan.h`.
443#[derive(Clone, Copy, Debug, PartialEq, Eq)]
444pub enum ExecutionBindingRole {
445	/// Unproduced semantic value consumed by the captured graph.
446	Input,
447	/// Produced semantic value not consumed by any captured operation.
448	Output,
449}
450
451/// Handle-free boundary contract for one exact compiled specialization.
452///
453/// A binding describes selection/validation only: plans retain their captured
454/// resources and validation never rebinds them. Rust matrices are dense, so a
455/// specialization candidate's implied strides are its dense strides.
456///
457/// Donor: `oa::ExecutionBindingDesc`.
458#[derive(Clone, Debug, PartialEq, Eq)]
459pub struct ExecutionBindingDesc {
460	slot: u32,
461	semantic_value: super::SemanticValueId,
462	kind: crate::OpValueKind,
463	role: ExecutionBindingRole,
464	shape: Vec<usize>,
465	strides: Vec<isize>,
466	dtype: crate::DType,
467	byte_offset: u64,
468}
469
470impl ExecutionBindingDesc {
471	/// Construct one contract entry. Field order mirrors the donor aggregate.
472	#[allow(clippy::too_many_arguments)]
473	pub(super) fn new(
474		slot: u32,
475		semantic_value: super::SemanticValueId,
476		kind: crate::OpValueKind,
477		role: ExecutionBindingRole,
478		shape: Vec<usize>,
479		strides: Vec<isize>,
480		dtype: crate::DType,
481		byte_offset: u64,
482	) -> Self {
483		Self {
484			slot,
485			semantic_value,
486			kind,
487			role,
488			shape,
489			strides,
490			dtype,
491			byte_offset,
492		}
493	}
494
495	/// Return the position of this entry inside the plan contract.
496	pub const fn slot(&self) -> u32 {
497		self.slot
498	}
499
500	/// Return the semantic value described by this entry.
501	pub const fn semantic_value(&self) -> super::SemanticValueId {
502		self.semantic_value
503	}
504
505	/// Return the semantic value kind.
506	pub const fn kind(&self) -> crate::OpValueKind {
507		self.kind
508	}
509
510	/// Return whether this entry is an input or an output.
511	pub const fn role(&self) -> ExecutionBindingRole {
512		self.role
513	}
514
515	/// Return the required logical shape.
516	pub fn shape(&self) -> &[usize] {
517		&self.shape
518	}
519
520	/// Return the required element strides.
521	pub fn strides(&self) -> &[isize] {
522		&self.strides
523	}
524
525	/// Return the required scalar dtype.
526	pub const fn dtype(&self) -> crate::DType {
527		self.dtype
528	}
529
530	/// Return the required absolute byte offset inside its storage.
531	pub const fn byte_offset(&self) -> u64 {
532		self.byte_offset
533	}
534}
535
536/// Deterministic bridge from one semantic value to a captured resource.
537#[derive(Clone, Copy, Debug, PartialEq, Eq)]
538pub struct SemanticStorageBinding {
539	value: super::SemanticValueId,
540	resource: u32,
541	semantic_external: bool,
542	stable_replay_input: bool,
543	observed_output: bool,
544}
545
546impl SemanticStorageBinding {
547	pub const fn value(self) -> super::SemanticValueId {
548		self.value
549	}
550
551	pub const fn resource(self) -> u32 {
552		self.resource
553	}
554
555	pub const fn semantic_external(self) -> bool {
556		self.semantic_external
557	}
558
559	pub const fn stable_replay_input(self) -> bool {
560		self.stable_replay_input
561	}
562
563	pub const fn observed_output(self) -> bool {
564		self.observed_output
565	}
566}
567
568const MAX_CACHED_BINDING_COMMANDS: usize = 8;
569const STABLE_INPUT_STAGING_DEPTH: usize = 3;
570
571#[derive(Default)]
572struct PlanCounters {
573	command_recordings: Cell<u64>,
574	command_cache_hits: Cell<u64>,
575	submissions: Cell<u64>,
576	input_rebindings: Cell<u64>,
577	input_uploads: Cell<u64>,
578	fallbacks: Cell<u64>,
579}
580
581/// Engine-associated executable work captured for repeated submission.
582///
583/// The captured executable structure is immutable. Read-only Matrix inputs may
584/// be rebound to shape- and dtype-identical storage while preserving the graph
585/// identity. Replays cache one recorded Vulkan command per binding set, so
586/// rotating through a bounded set of input buffers reuses the recorded commands
587/// after the first submission of each set.
588#[must_use]
589pub struct ExecutionPlan {
590	engine: EngineHandle,
591	graph_id: u64,
592	device_capability_identity: u64,
593	graph: ExecutableGraph,
594	outputs: Vec<Storage>,
595	semantic: SemanticGraph,
596	semantic_lowering: SemanticLoweringAnalysis,
597	dnn: DnnPlan,
598	input_bindings: Vec<MatrixInputBinding>,
599	bindings: Vec<ExecutionBindingDesc>,
600	binding_contract_hash: u64,
601	captured_resources: Vec<CapturedResourceDesc>,
602	semantic_bindings: Vec<SemanticStorageBinding>,
603	descriptor_write_count: u64,
604	materialized_alias_savings: usize,
605	alias_materialization_fallback_reason: Option<String>,
606	cached_commands: RefCell<Vec<(Vec<u32>, Vec<ReusableCommandBuffer>)>>,
607	last_submission: RefCell<Option<Event>>,
608	counters: PlanCounters,
609}
610
611impl ExecutionPlan {
612	pub(super) fn new(
613		engine: EngineHandle,
614		pending: PendingExecution,
615		source_recording_retained: bool,
616	) -> Result<Self> {
617		let (mut graph, mut outputs, semantic, stable_resources, semantic_storage, observed_outputs) =
618			pending.into_parts();
619		let device_capability_identity = engine.device_info().capability_identity();
620		let mut dnn = DnnPlan::plan(&semantic, DnnPolicy::default())?;
621		if dnn.source_operation_count() as usize != semantic.operations().len() {
622			return Err(Error::internal(
623				"DNN plan source operation count does not match the semantic graph",
624			));
625		}
626		let (bindings, binding_contract_hash) = dnn.build_binding_contract(&semantic)?;
627		let input_bindings = graph
628			.read_only_buffers()
629			.into_iter()
630			.map(|buffer| MatrixInputBinding {
631				original: buffer.clone(),
632				current: buffer.clone(),
633				staging: vec![InputStagingSlot {
634					buffer,
635					consumer: RefCell::new(None),
636				}],
637			})
638			.collect();
639		let mut resource_lifetimes = graph.resource_lifetimes();
640		// Composite semantic operations may expose a zero-copy input as an output
641		// without any physical dispatch reading it. Retain that semantic-only
642		// resource in the plan inventory even though it has no GPU access edge.
643		// This keeps the semantic graph complete without manufacturing a shader
644		// read or weakening storage identity checks.
645		for binding in &semantic_storage {
646			let Some(buffer) = binding.storage.buffer() else {
647				continue;
648			};
649			if !resource_lifetimes
650				.iter()
651				.any(|lifetime| lifetime.buffer.same_as(buffer))
652			{
653				resource_lifetimes.push(super::graph::executable::ResourceLifetime {
654					buffer: buffer.clone(),
655					first_access: 0,
656					last_access: 0,
657				});
658			}
659		}
660		let mut captured_resources = resource_lifetimes
661			.iter()
662			.enumerate()
663			.map(|(resource, lifetime)| {
664				let stable = stable_resources.iter().find(|candidate| {
665					candidate
666						.storage
667						.buffer()
668						.is_some_and(|buffer| buffer.same_as(&lifetime.buffer))
669				});
670				let owner = find_resource_storage(
671					&lifetime.buffer,
672					&stable_resources,
673					&semantic_storage,
674					&observed_outputs,
675					&outputs,
676				);
677				let stable_owner_count = stable_resources
678					.iter()
679					.filter(|candidate| owner.is_some_and(|owner| candidate.storage.same_as(owner)))
680					.count()
681					.saturating_mul(2);
682				let source_copy_count = usize::from(source_recording_retained);
683				let capture_retained_owner_count = stable_owner_count
684					.saturating_add(
685						semantic_storage
686							.iter()
687							.filter(|candidate| owner.is_some_and(|owner| candidate.storage.same_as(owner)))
688							.count()
689							.saturating_mul(1 + source_copy_count),
690					)
691					.saturating_add(
692						observed_outputs
693							.iter()
694							.filter(|candidate| owner.is_some_and(|owner| candidate.same_as(owner)))
695							.count(),
696					)
697					.saturating_add(
698						outputs
699							.iter()
700							.filter(|candidate| owner.is_some_and(|owner| candidate.same_as(owner)))
701							.count()
702							.saturating_mul(1 + source_copy_count),
703					);
704				let unaccounted_owner_count = owner.map_or(0, |owner| {
705					owner
706						.owner_count()
707						.saturating_sub(capture_retained_owner_count)
708				});
709				Ok(CapturedResourceDesc {
710					resource: u32::try_from(resource)
711						.map_err(|_| Error::resource_exhausted("captured resource identity exceeds u32"))?,
712					byte_len: lifetime.buffer.byte_len(),
713					first_access: lifetime.first_access,
714					last_access: lifetime.last_access,
715					stable_replay_input: stable.is_some_and(|value| value.replay_input),
716					stable_transient: stable.is_some_and(|value| value.transient),
717					semantic_external: false,
718					observed_output: false,
719					capture_retained_owner_count,
720					unaccounted_owner_count,
721					alias_candidate: false,
722					alias_materialized: false,
723				})
724			})
725			.collect::<Result<Vec<_>>>()?;
726		let mut semantic_bindings = Vec::with_capacity(semantic_storage.len());
727		for binding in &semantic_storage {
728			let value = semantic
729				.values()
730				.get(binding.value.index() as usize)
731				.ok_or_else(|| Error::internal("semantic storage binding value is out of range"))?;
732			let resource = find_resource(&resource_lifetimes, &binding.storage)?;
733			let resource_id = u32::try_from(resource)
734				.map_err(|_| Error::resource_exhausted("captured resource identity exceeds u32"))?;
735			captured_resources[resource].semantic_external |= value.is_external();
736			semantic_bindings.push(SemanticStorageBinding {
737				value: binding.value,
738				resource: resource_id,
739				semantic_external: value.is_external(),
740				stable_replay_input: captured_resources[resource].stable_replay_input,
741				observed_output: false,
742			});
743		}
744		for output in &observed_outputs {
745			let resource = find_resource(&resource_lifetimes, output)?;
746			captured_resources[resource].observed_output = true;
747			for binding in &mut semantic_bindings {
748				if binding.resource as usize == resource {
749					binding.observed_output = true;
750				}
751			}
752		}
753		graph = dnn.lower_captured_plan(
754			&engine,
755			&semantic,
756			&semantic_bindings,
757			&resource_lifetimes,
758			&captured_resources,
759			!source_recording_retained,
760			&graph,
761		)?;
762		engine.record_dnn_partitions(
763			dnn.applied_partition_count(),
764			dnn.fallback_partition_count(),
765		);
766		let graph_id = graph.identity();
767		let semantic_lowering = graph.analyze_semantic_lowering(&semantic)?;
768		// OA-CC-23: reusable storage must first be fully written. For buffers
769		// outside the stable transient set, a final read also bounds the
770		// lifetime to this replay.
771		let mut first_access: std::collections::BTreeMap<u32, BufferAccess> =
772			std::collections::BTreeMap::new();
773		let mut last_access: std::collections::BTreeMap<u32, BufferAccess> =
774			std::collections::BTreeMap::new();
775		for node in graph.nodes() {
776			if let Some(indirect) = node.indirect() {
777				let identity = indirect.buffer.descriptor_index();
778				first_access.entry(identity).or_insert(BufferAccess::Read);
779				last_access.insert(identity, BufferAccess::Read);
780			}
781			for usage in node.buffers() {
782				let identity = usage.buffer.descriptor_index();
783				first_access.entry(identity).or_insert(usage.access);
784				last_access.insert(identity, usage.access);
785			}
786		}
787		for (index, resource) in captured_resources.iter_mut().enumerate() {
788			let buffer = &resource_lifetimes[index].buffer;
789			let identity = buffer.descriptor_index();
790			// A first read or partial write depends on the original contents.
791			resource.alias_candidate = matches!(first_access.get(&identity), Some(BufferAccess::Write))
792				&& (resource.stable_transient
793					|| matches!(last_access.get(&identity), Some(BufferAccess::Read)))
794				&& !resource.is_externally_live()
795				&& resource.unaccounted_owner_count == 0
796				&& !fusion::buffer_is_fused_binding(graph.compute_nodes(), buffer);
797		}
798		let materialization = materialize_aliases(
799			&engine,
800			&graph,
801			&outputs,
802			&resource_lifetimes,
803			&captured_resources,
804		);
805		let (retired, materialized_alias_savings, alias_materialization_fallback_reason) =
806			match materialization {
807				Ok(materialized) => {
808					graph = materialized.graph;
809					outputs = materialized.outputs;
810					captured_resources = materialized.captured_resources;
811					(materialized.retired, materialized.savings, None)
812				}
813				Err(error) => (
814					Vec::new(),
815					0,
816					Some(format!("transient alias materialization failed: {error}")),
817				),
818			};
819		engine.release_stable_transient_resources(&retired);
820		let initial_fallback_count = u64::from(alias_materialization_fallback_reason.is_some())
821			.saturating_add(u64::from(dnn.fallback_partition_count()));
822		Ok(Self {
823			engine,
824			graph_id,
825			device_capability_identity,
826			graph,
827			outputs,
828			semantic,
829			semantic_lowering,
830			dnn,
831			input_bindings,
832			bindings,
833			binding_contract_hash,
834			captured_resources,
835			semantic_bindings,
836			descriptor_write_count: 0,
837			materialized_alias_savings,
838			alias_materialization_fallback_reason,
839			cached_commands: RefCell::new(Vec::new()),
840			last_submission: RefCell::new(None),
841			counters: PlanCounters {
842				fallbacks: Cell::new(initial_fallback_count),
843				..PlanCounters::default()
844			},
845		})
846	}
847
848	/// Record the capture-time descriptor-write count the guard measured.
849	pub(super) fn set_descriptor_write_count(&mut self, count: u64) {
850		self.descriptor_write_count = count;
851	}
852
853	/// Return the canonical backend-independent graph captured by this plan.
854	pub const fn semantic_graph(&self) -> &SemanticGraph {
855		&self.semantic
856	}
857
858	/// Return the validated semantic-to-executable lowering provenance.
859	pub const fn semantic_lowering(&self) -> &SemanticLoweringAnalysis {
860		&self.semantic_lowering
861	}
862
863	/// Return deterministic physical-resource lifetime and stable-frame evidence.
864	pub fn captured_resources(&self) -> &[CapturedResourceDesc] {
865		&self.captured_resources
866	}
867
868	/// Return the handle-free semantic value-to-resource capture table.
869	pub fn semantic_bindings(&self) -> &[SemanticStorageBinding] {
870		&self.semantic_bindings
871	}
872
873	/// Return why transient alias materialization fell back to distinct storage.
874	///
875	/// The plan remains executable when this returns `Some`; diagnostics count the
876	/// decision as one fallback and report zero materialized alias savings.
877	pub fn alias_materialization_fallback_reason(&self) -> Option<&str> {
878		self.alias_materialization_fallback_reason.as_deref()
879	}
880
881	/// Upload values into one stable captured Matrix input slot.
882	///
883	/// The captured shape, dtype, descriptor slot, and graph identity remain
884	/// unchanged. The slot rotates through a bounded triple-buffered staging
885	/// ring: each upload writes the next ring buffer and rebinds it, so a
886	/// pending prior replay stalls only when the target ring buffer is still
887	/// consumed by an in-flight submission. The captured Matrix's own buffer
888	/// mirrors each upload, so the stable value remains coherent for host
889	/// reads.
890	///
891	/// # Errors
892	///
893	/// Returns an error when `captured` is not a ring-bound read-only plan
894	/// input, the element type or count differs, or prior completion/upload
895	/// fails.
896	pub fn upload_matrix_input<T: Element>(&mut self, captured: &Matrix, values: &[T]) -> Result<()> {
897		if !self.engine.same_as(captured.engine_handle()) {
898			return Err(Error::invalid_argument(
899				"execution-plan Matrix input belongs to another engine",
900			));
901		}
902		let captured_buffer = captured.storage().buffer().ok_or_else(|| {
903			Error::invalid_argument("zero-sized Matrix storage cannot identify a captured plan input")
904		})?;
905		let binding_index = self
906			.input_bindings
907			.iter()
908			.position(|binding| binding.original.same_as(captured_buffer))
909			.ok_or_else(|| {
910				Error::invalid_argument("captured Matrix is not a read-only input of this execution plan")
911			})?;
912		if captured.dtype() != T::DTYPE {
913			return Err(Error::invalid_argument(format!(
914				"matrix element type {} does not match dtype {}",
915				T::DTYPE.token(),
916				captured.dtype().token()
917			)));
918		}
919		if values.len() != captured.element_count() {
920			return Err(Error::invalid_argument(format!(
921				"matrix upload requires {} elements; received {}",
922				captured.element_count(),
923				values.len()
924			)));
925		}
926		let binding = &mut self.input_bindings[binding_index];
927		let current_slot = binding
928			.staging
929			.iter()
930			.position(|slot| slot.buffer.same_as(&binding.current))
931			.ok_or_else(|| {
932				Error::failed_precondition(
933					"execution-plan host upload requires a ring-bound stable input slot",
934				)
935			})?;
936		let next_slot = (current_slot + 1) % STABLE_INPUT_STAGING_DEPTH;
937		if next_slot == binding.staging.len() {
938			let buffer =
939				Buffer::host_visible_storage(binding.original.device(), binding.original.byte_len())?;
940			binding.staging.push(InputStagingSlot {
941				buffer,
942				consumer: RefCell::new(None),
943			});
944		}
945		let slot = &binding.staging[next_slot];
946		if let Some(event) = slot.consumer.borrow().as_ref() {
947			event.wait()?;
948		}
949		// Both branches below write the captured buffer on the host: directly
950		// when the ring lands on it, or through the mirror update. Other plans
951		// sharing this Matrix may still have an in-flight submission bound to
952		// it, which this plan's per-slot consumers cannot observe.
953		binding.original.wait_bound_consumer()?;
954		if slot.buffer.same_as(&binding.original) {
955			captured.write_values(values)?;
956		} else {
957			let byte_len = values
958				.len()
959				.checked_mul(std::mem::size_of::<T>())
960				.ok_or_else(|| Error::invalid_argument("matrix byte size overflows usize"))?;
961			// SAFETY: `Element` is sealed to initialized, no-padding OA scalar
962			// types and the checked length covers exactly the supplied slice.
963			let bytes = unsafe { std::slice::from_raw_parts(values.as_ptr().cast(), byte_len) };
964			if T::DTYPE == crate::DType::U8 {
965				let mut padded = vec![0_u8; crate::matrix::byte_storage_len(byte_len, T::DTYPE)?];
966				padded[..byte_len].copy_from_slice(bytes);
967				slot.buffer.write(0, &padded)?;
968			} else {
969				slot.buffer.write(0, bytes)?;
970			}
971			// Mirror the newest upload into the captured Matrix's buffer so the
972			// stable value stays coherent for host reads while the ring
973			// pipelines device reads. The buffer-level wait above covered every
974			// plan's last bound submission, so this wait is bounded by the ring
975			// depth.
976			captured.write_values(values)?;
977		}
978		if !binding.current.same_as(&slot.buffer) {
979			self.graph.rebind_read_only(
980				&binding.current,
981				&slot.buffer,
982				self.engine.execution_profile(),
983			)?;
984			binding.current = slot.buffer.clone();
985		}
986		increment(&self.counters.input_uploads);
987		Ok(())
988	}
989
990	/// Rebind one read-only Matrix input while preserving its captured contract.
991	///
992	/// `captured` remains the stable slot identity even after repeated rebinding.
993	/// The replacement must have the same shape and dtype, belong to the plan's
994	/// engine, and not alias another resource already used by the plan. Rebinding
995	/// does not submit or wait; the next submission records one command buffer per
996	/// unseen binding set and later submissions of the same set reuse it.
997	///
998	/// # Errors
999	///
1000	/// Returns an error when either Matrix belongs to another engine, their shape
1001	/// or dtype differs, `captured` is not a read-only plan input, the replacement
1002	/// aliases another plan resource, or its production state is invalid.
1003	pub fn bind_matrix_input(&mut self, captured: &Matrix, replacement: &Matrix) -> Result<()> {
1004		if !self.engine.same_as(captured.engine_handle())
1005			|| !self.engine.same_as(replacement.engine_handle())
1006		{
1007			return Err(Error::invalid_argument(
1008				"execution-plan Matrix bindings must belong to the plan's engine",
1009			));
1010		}
1011		if captured.shape() != replacement.shape() || captured.dtype() != replacement.dtype() {
1012			return Err(Error::invalid_argument(format!(
1013				"execution-plan Matrix input requires shape {:?} and dtype {}; replacement has shape {:?} and dtype {}",
1014				captured.shape(),
1015				captured.dtype().token(),
1016				replacement.shape(),
1017				replacement.dtype().token()
1018			)));
1019		}
1020		replacement
1021			.storage()
1022			.validate_recording_access(BufferAccess::Read)?;
1023		let captured_buffer = captured.storage().buffer().ok_or_else(|| {
1024			Error::invalid_argument("zero-sized Matrix storage cannot identify a captured plan input")
1025		})?;
1026		let replacement_buffer = replacement.storage().buffer().ok_or_else(|| {
1027			Error::invalid_argument("zero-sized Matrix storage cannot replace a captured plan input")
1028		})?;
1029
1030		let existing = self
1031			.input_bindings
1032			.iter()
1033			.position(|binding| binding.original.same_as(captured_buffer))
1034			.ok_or_else(|| {
1035				Error::invalid_argument("captured Matrix is not a read-only input of this execution plan")
1036			})?;
1037		let current = self.input_bindings[existing].current.clone();
1038		if current.same_as(replacement_buffer) {
1039			return Ok(());
1040		}
1041		self.graph.rebind_read_only(
1042			&current,
1043			replacement_buffer,
1044			self.engine.execution_profile(),
1045		)?;
1046		self.input_bindings[existing].current = replacement_buffer.clone();
1047		increment(&self.counters.input_rebindings);
1048		Ok(())
1049	}
1050
1051	/// Return the number of entries in the compiled specialization contract.
1052	///
1053	/// Donor: `oa::ExecutionPlan::bindingCount`.
1054	pub const fn binding_count(&self) -> usize {
1055		self.bindings.len()
1056	}
1057
1058	/// Return the number of contract entries with an input role.
1059	///
1060	/// Donor: `oa::ExecutionPlan::inputBindingCount`.
1061	pub fn input_binding_count(&self) -> usize {
1062		self
1063			.bindings
1064			.iter()
1065			.filter(|binding| binding.role() == ExecutionBindingRole::Input)
1066			.count()
1067	}
1068
1069	/// Return the number of contract entries with an output role.
1070	///
1071	/// Donor: `oa::ExecutionPlan::outputBindingCount`.
1072	pub fn output_binding_count(&self) -> usize {
1073		self.bindings.len() - self.input_binding_count()
1074	}
1075
1076	/// Return the contract entry at `slot`.
1077	///
1078	/// Donor: `oa::ExecutionPlan::binding`.
1079	///
1080	/// # Errors
1081	///
1082	/// Returns `InvalidArgument` when `slot` is out of range.
1083	pub fn binding(&self, slot: u32) -> Result<ExecutionBindingDesc> {
1084		self
1085			.bindings
1086			.get(slot as usize)
1087			.cloned()
1088			.ok_or_else(|| Error::invalid_argument("execution plan binding slot is out of range"))
1089	}
1090
1091	/// Return the deterministic hash of the compiled specialization contract.
1092	///
1093	/// Donor: `oa::ExecutionPlan::bindingContractHash`.
1094	pub const fn binding_contract_hash(&self) -> u64 {
1095		self.binding_contract_hash
1096	}
1097
1098	/// Validate specialization input matrices against the compiled contract.
1099	///
1100	/// Validation checks the exact shape, dtype, strides, and byte offset of
1101	/// each contract input in order. It deliberately does not rebind resources:
1102	/// dynamic dimensions select or recapture another checked plan rather than
1103	/// mutating this plan's recorded command buffers.
1104	///
1105	/// Donor: `oa::ExecutionPlan::validateSpecializationInputs`.
1106	///
1107	/// # Errors
1108	///
1109	/// Returns `InvalidArgument` when the input count differs, and
1110	/// `FailedPrecondition` when any input's contract requires another plan or
1111	/// is not a matrix.
1112	pub fn validate_specialization_inputs(&self, inputs: &[crate::Matrix]) -> Result<()> {
1113		if inputs.len() != self.input_binding_count() {
1114			return Err(Error::invalid_argument(
1115				"specialization input count does not match the compiled plan",
1116			));
1117		}
1118		let mut input_index = 0_usize;
1119		for binding in &self.bindings {
1120			if binding.role() != ExecutionBindingRole::Input {
1121				continue;
1122			}
1123			if binding.kind() != crate::OpValueKind::Matrix {
1124				return Err(Error::failed_precondition(
1125					"matrix specialization validation cannot bind a non-Matrix input",
1126				));
1127			}
1128			let input = &inputs[input_index];
1129			input_index += 1;
1130			let absolute_offset = {
1131				let mut offset = 0_i64;
1132				let mut semantic = input.semantic().clone();
1133				loop {
1134					offset = offset
1135						.checked_add(semantic.view_byte_offset())
1136						.ok_or_else(|| Error::internal("matrix view byte offset overflows i64"))?;
1137					match semantic.view_source() {
1138						Some(source) => semantic = source.clone(),
1139						None => break,
1140					}
1141				}
1142				offset
1143			};
1144			if input.shape() != binding.shape()
1145				|| input.dtype() != binding.dtype()
1146				|| absolute_offset < 0
1147				|| absolute_offset as u64 != binding.byte_offset()
1148			{
1149				return Err(Error::failed_precondition(
1150					"specialization input shape, dtype or offset requires another plan",
1151				));
1152			}
1153			if super::graph::semantic::dense_strides(input.shape())? != binding.strides() {
1154				return Err(Error::failed_precondition(
1155					"specialization input strides require another plan",
1156				));
1157			}
1158		}
1159		Ok(())
1160	}
1161
1162	/// Return current graph, cache, submission, rebinding, and fallback counters.
1163	pub fn diagnostics(&self) -> ExecutionPlanDiagnostics {
1164		let (planned_alias_group_count, potential_alias_savings) =
1165			alias_analysis(&self.captured_resources);
1166		ExecutionPlanDiagnostics {
1167			graph_id: self.graph_id,
1168			device_capability_identity: self.device_capability_identity,
1169			node_count: self.graph.nodes().len(),
1170			barrier_count: self.graph.barrier_count(),
1171			cross_queue_edge_count: self.graph.cross_queue_edge_count(),
1172			ownership_transfer_count: self.graph.ownership_transfer_count(),
1173			queue_run_count: self.graph.queue_runs().len(),
1174			semantic_operation_count: self.semantic.operations().len(),
1175			semantic_autograd_attachment_count: self.semantic.autograd().len(),
1176			semantic_autograd_expanded_count: self
1177				.semantic
1178				.autograd()
1179				.iter()
1180				.filter(|entry| entry.is_backward_expanded())
1181				.count(),
1182			semantic_backward_operation_count: self
1183				.semantic
1184				.autograd()
1185				.iter()
1186				.map(|entry| entry.backward_op_count())
1187				.sum(),
1188			schema_owned_node_count: self.semantic_lowering.schema_owned_node_count() as usize,
1189			compatibility_node_count: self.semantic_lowering.compatibility_node_count() as usize,
1190			semantic_fused_operation_count: self.semantic_lowering.fused_op_count() as usize,
1191			semantic_fused_node_count: self.semantic_lowering.fused_node_count() as usize,
1192			maximum_semantic_operations_per_node: self.semantic_lowering.maximum_ops_per_node() as usize,
1193			dnn_graph_hash: self.dnn.graph_hash(),
1194			dnn_value_count: self.dnn.value_count(),
1195			dnn_external_value_count: self.dnn.external_value_count(),
1196			dnn_virtual_value_count: self.dnn.virtual_value_count(),
1197			dnn_partition_count: self.dnn.partition_count(),
1198			dnn_recognized_partition_count: self.dnn.recognized_partition_count(),
1199			dnn_portable_partition_count: self.dnn.portable_partition_count(),
1200			dnn_captured_operation_count: self.dnn.captured_operation_count(),
1201			dnn_applied_partition_count: self.dnn.applied_partition_count(),
1202			dnn_inherited_partition_count: self.dnn.inherited_partition_count(),
1203			dnn_fallback_partition_count: self.dnn.fallback_partition_count(),
1204			dnn_unexpected_fallback_count: self.dnn.unexpected_fallback_count(),
1205			input_binding_count: self.input_bindings.len(),
1206			captured_resource_count: self.captured_resources.len(),
1207			physical_resource_count: self.graph.resource_lifetimes().len(),
1208			stable_replay_input_count: self
1209				.captured_resources
1210				.iter()
1211				.filter(|resource| resource.stable_replay_input)
1212				.count(),
1213			stable_transient_count: self
1214				.captured_resources
1215				.iter()
1216				.filter(|resource| resource.stable_transient)
1217				.count(),
1218			semantic_binding_count: self.semantic_bindings.len(),
1219			observed_output_count: self
1220				.captured_resources
1221				.iter()
1222				.filter(|resource| resource.observed_output)
1223				.count(),
1224			alias_candidate_count: self
1225				.captured_resources
1226				.iter()
1227				.filter(|resource| resource.alias_candidate)
1228				.count(),
1229			alias_materialized_count: self
1230				.captured_resources
1231				.iter()
1232				.filter(|resource| resource.alias_materialized)
1233				.count(),
1234			planned_alias_group_count,
1235			potential_alias_savings,
1236			materialized_alias_savings: self.materialized_alias_savings,
1237			descriptor_write_count: self.descriptor_write_count,
1238			peak_memory_bytes: {
1239				let mut lifetimes = self.graph.resource_lifetimes();
1240				lifetimes.sort_by_key(|lifetime| lifetime.first_access);
1241				let mut active: Vec<(usize, u32, usize)> = Vec::new();
1242				let mut peak = 0_usize;
1243				for lifetime in lifetimes {
1244					active.retain(|(last, _, _)| *last >= lifetime.first_access);
1245					let index = lifetime.buffer.descriptor_index();
1246					if !active.iter().any(|(_, live, _)| *live == index) {
1247						active.push((lifetime.last_access, index, lifetime.buffer.byte_len()));
1248					}
1249					peak = peak.max(active.iter().map(|(_, _, bytes)| *bytes).sum::<usize>());
1250				}
1251				peak
1252			},
1253			push_byte_count: self
1254				.graph
1255				.compute_nodes()
1256				.map(|node| node.push_constants.len() * 4)
1257				.sum(),
1258			command_recording_count: self.counters.command_recordings.get(),
1259			command_cache_hit_count: self.counters.command_cache_hits.get(),
1260			submission_count: self.counters.submissions.get(),
1261			input_rebinding_count: self.counters.input_rebindings.get(),
1262			input_upload_count: self.counters.input_uploads.get(),
1263			fallback_count: self.counters.fallbacks.get(),
1264		}
1265	}
1266
1267	pub(crate) fn dnn_fallback_reasons(&self) -> impl Iterator<Item = &str> {
1268		self.dnn.fallback_reasons()
1269	}
1270
1271	/// Return whether the most recently submitted replay has completed.
1272	///
1273	/// A plan that has not been submitted is complete.
1274	///
1275	/// # Errors
1276	///
1277	/// Returns an error when Vulkan cannot query the originating timeline.
1278	pub fn is_complete(&self) -> Result<bool> {
1279		let event = self.last_submission.borrow().clone();
1280		event.map_or(Ok(true), |event| event.is_complete())
1281	}
1282
1283	/// Wait for the most recently submitted replay and its host retirement.
1284	///
1285	/// Same-queue timeline order means completion of the latest replay also proves
1286	/// completion of every earlier replay submitted through this plan.
1287	///
1288	/// # Errors
1289	///
1290	/// Returns an error when Vulkan completion or host retirement waiting fails.
1291	pub fn wait(&self) -> Result<()> {
1292		let event = self.last_submission.borrow().clone();
1293		if let Some(event) = event {
1294			event.wait()?;
1295		}
1296		Ok(())
1297	}
1298
1299	/// Wait for pending replay and consume the plan, releasing retained state.
1300	///
1301	/// This is the Rust ownership equivalent of the donor's mutable `reset`: plan
1302	/// capture constructs a new value rather than repopulating an empty shell.
1303	/// Destruction remains non-blocking when this explicit boundary is not used.
1304	///
1305	/// # Errors
1306	///
1307	/// Returns an error from [`ExecutionPlan::wait`]. The consumed plan still drops
1308	/// safely on error; submitted resources remain owned by engine retirement.
1309	pub fn reset(self) -> Result<()> {
1310		self.wait()
1311	}
1312
1313	/// Return the deterministic normalized executable graph report as JSON.
1314	///
1315	/// Resource and hazard-domain IDs follow first graph access. Vulkan handles,
1316	/// device addresses, descriptor indices, and push payloads are omitted.
1317	pub fn debug_report_json(&self, name: &str) -> String {
1318		let diagnostics = self.diagnostics();
1319		let lifetimes = self.graph.resource_lifetimes();
1320		let compiled = self
1321			.cached_commands
1322			.borrow()
1323			.iter()
1324			.any(|(cached_key, _)| *cached_key == self.binding_key());
1325		let last_event = self.last_submission.borrow().clone();
1326		let mut output = String::new();
1327		output.push_str("{\n  \"schema\": \"oa.execution_graph.v3\",\n  \"name\": ");
1328		crate::core::push_json_string(&mut output, name);
1329		crate::core::push_format(
1330			&mut output,
1331			format_args!(
1332				",\n  \"compiled\": {},\n  \"completion\": {{\"submitted\": {}, \"timeline_value\": {}}},\n",
1333				compiled,
1334				last_event.is_some(),
1335				last_event.as_ref().map_or(0, Event::epoch),
1336			),
1337		);
1338		let mut war_barriers = 0;
1339		let mut indirect_barriers = 0;
1340		for barrier in (0..self.graph.nodes().len()).flat_map(|node| self.graph.barriers_before(node)) {
1341			war_barriers += usize::from(!barrier.source.writes() && barrier.destination.writes());
1342			indirect_barriers += usize::from(barrier.destination.uses_indirect_commands());
1343		}
1344		let dispatches = self.graph.compute_nodes().count();
1345		let copies = self
1346			.graph
1347			.nodes()
1348			.iter()
1349			.filter(|node| matches!(node, GraphNode::BufferCopy(_)))
1350			.count();
1351		let video_commands = diagnostics.node_count() - dispatches - copies;
1352		let buffer_bytes = lifetimes.iter().fold(0_usize, |total, lifetime| {
1353			total.saturating_add(lifetime.buffer.byte_len())
1354		});
1355		crate::core::push_format(
1356			&mut output,
1357			format_args!(
1358				"  \"stats\": {{\"dispatches\": {dispatches}, \"barriers\": {}, \"war_barriers\": {}, \"indirect_barriers\": {}, \"alias_barriers\": 0, \"host_barriers\": 0, \"descriptor_sets\": 0, \"kernel_selections\": {dispatches}, \"kernel_fallbacks\": 0, \"precision_fallbacks\": 0, \"layout_fallbacks\": 0, \"naive_fallbacks\": 0, \"buffer_bytes\": {}, \"potential_alias_savings\": {}, \"materialized_alias_savings\": {}",
1359				diagnostics.barrier_count(),
1360				war_barriers,
1361				indirect_barriers,
1362				buffer_bytes,
1363				diagnostics.potential_alias_savings(),
1364				diagnostics.materialized_alias_savings(),
1365			),
1366		);
1367		if copies != 0 {
1368			crate::core::push_format(&mut output, format_args!(r#", "copies": {copies}"#));
1369		}
1370		if video_commands != 0 {
1371			let image_transfers = self.graph.image_transfer_count();
1372			crate::core::push_format(
1373				&mut output,
1374				format_args!(
1375					r#", "video_commands": {video_commands}, "image_transfers": {image_transfers}"#
1376				),
1377			);
1378		}
1379		output.push_str("},\n  \"resources\": [");
1380		for (resource, lifetime) in lifetimes.iter().enumerate() {
1381			output.push_str(if resource == 0 { "\n" } else { ",\n" });
1382			crate::core::push_format(
1383				&mut output,
1384				format_args!(
1385					"    {{\"id\": {resource}, \"hazard_domain\": {resource}, \"bytes\": {}, \"first_node\": {}, \"last_node\": {}}}",
1386					lifetime.buffer.byte_len(),
1387					lifetime.first_access,
1388					lifetime.last_access,
1389				),
1390			);
1391		}
1392		if !lifetimes.is_empty() {
1393			output.push('\n');
1394		}
1395		// OARS alias arenas deliberately collapse a group to one buffer identity.
1396		// Logical group membership remains available in the compilation report.
1397		output.push_str("  ],\n  \"alias_groups\": [],\n  \"barriers\": [");
1398		let mut barrier_index = 0_usize;
1399		for destination_node in 0..self.graph.nodes().len() {
1400			let barriers = self.graph.barriers_before(destination_node);
1401			for barrier in barriers {
1402				output.push_str(if barrier_index == 0 { "\n" } else { ",\n" });
1403				barrier_index = barrier_index.saturating_add(1);
1404				let resource = graph_resource_id(&lifetimes, &barrier.buffer)
1405					.expect("planned barrier resource must have a lifetime");
1406				let [first_source, last_source] = barrier.source_nodes;
1407				let source_stage = barrier.source.vk_stages().as_raw();
1408				let destination_stage = barrier.destination.vk_stages().as_raw();
1409				let source_access = barrier.source.vk_access().as_raw();
1410				let destination_access = barrier.destination.vk_access().as_raw();
1411				crate::core::push_format(
1412					&mut output,
1413					format_args!(
1414						"    {{\"reason\": \"{}\", \"scope\": \"buffer\", \"source_nodes\": [{first_source}, {last_source}], \"destination_node\": {destination_node}, \"source_resource\": {resource}, \"destination_resource\": {resource}, \"hazard_domain\": {resource}, \"range\": {{\"offset\": 0, \"bytes\": {}}}, \"source_queue\": \"{}\", \"destination_queue\": \"{}\", \"source_family\": {}, \"destination_family\": {}, \"cross_queue\": {}, \"ownership_transfer\": {}, \"source_stage_mask\": \"0x{source_stage:016x}\", \"source_stages\": [",
1415						hazard_reason(barrier.source, barrier.destination),
1416						barrier.buffer.byte_len(),
1417						barrier.source_queue.name(),
1418						barrier.destination_queue.name(),
1419						barrier.source_family,
1420						barrier.destination_family,
1421						barrier.is_cross_queue(),
1422						barrier.is_ownership_transfer(),
1423					),
1424				);
1425				push_stage_names(&mut output, barrier.source);
1426				crate::core::push_format(
1427					&mut output,
1428					format_args!(
1429						"], \"source_access_mask\": \"0x{source_access:016x}\", \"source_accesses\": ["
1430					),
1431				);
1432				push_access_names(&mut output, barrier.source);
1433				crate::core::push_format(
1434					&mut output,
1435					format_args!(
1436						"], \"destination_stage_mask\": \"0x{destination_stage:016x}\", \"destination_stages\": ["
1437					),
1438				);
1439				push_stage_names(&mut output, barrier.destination);
1440				crate::core::push_format(
1441					&mut output,
1442					format_args!(
1443						"], \"destination_access_mask\": \"0x{destination_access:016x}\", \"destination_accesses\": ["
1444					),
1445				);
1446				push_access_names(&mut output, barrier.destination);
1447				output.push_str("]}");
1448			}
1449		}
1450		if barrier_index != 0 {
1451			output.push('\n');
1452		}
1453		output.push_str("  ],\n  \"nodes\": [");
1454		for (index, graph_node) in self.graph.nodes().iter().enumerate() {
1455			let (operation, semantic_ops, contract) = graph_node.semantic();
1456			output.push_str(if index == 0 { "\n" } else { ",\n" });
1457			crate::core::push_format(
1458				&mut output,
1459				format_args!("    {{\"index\": {index}, \"operation\": "),
1460			);
1461			crate::core::push_json_string(&mut output, operation);
1462			output.push_str(", \"semantic_operations\": [");
1463			for (owner_index, owner) in semantic_ops.iter().enumerate() {
1464				if owner_index != 0 {
1465					output.push_str(", ");
1466				}
1467				crate::core::push_format(&mut output, format_args!("{}", owner.index()));
1468			}
1469			match graph_node {
1470				GraphNode::Compute(node) => {
1471					let implementation_id = node.kernel.artifact().content_id();
1472					crate::core::push_format(
1473						&mut output,
1474						format_args!(
1475							"], \"implementation_id\": \"0x{implementation_id:016x}\", \"operation_contract_hash\": "
1476						),
1477					);
1478					push_optional_hex(&mut output, contract);
1479					crate::core::push_format(
1480						&mut output,
1481						format_args!(
1482							", \"problem_contract_hash\": null, \"kernel_content_hash\": \"0x{implementation_id:016x}\", \"kernel_selection\": \"direct\", \"kernel\": "
1483						),
1484					);
1485					crate::core::push_json_string(&mut output, node.kernel.report_name());
1486					output.push_str(", \"dtype_class\": null, \"dtype\": ");
1487					crate::core::push_json_string(&mut output, node.kernel.dtype_report_token());
1488					output.push_str(", \"physical_write\": ");
1489					match node.kernel.artifact().physical_write {
1490						None => output.push_str("null"),
1491						Some(contract) => {
1492							output.push_str("{\"writes\": [");
1493							for (write_index, write) in contract.writes.iter().enumerate() {
1494								if write_index != 0 {
1495									output.push_str(", ");
1496								}
1497								crate::core::push_format(
1498									&mut output,
1499									format_args!(
1500										"{{\"binding\": {}, \"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1501										write.binding,
1502										write.domain.token(),
1503										write.partition.token(),
1504										write.extent.token(),
1505										write.collision.token(),
1506										write.tail.token(),
1507									),
1508								);
1509							}
1510							output.push_str("], \"uniform_store\": ");
1511							match contract.uniform_store {
1512								None => output.push_str("null"),
1513								Some(proof) => crate::core::push_format(
1514									&mut output,
1515									format_args!(
1516										"{{\"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1517										proof.domain.token(),
1518										proof.partition.token(),
1519										proof.extent.token(),
1520										proof.collision.token(),
1521										proof.tail.token(),
1522									),
1523								),
1524							}
1525							crate::core::push_format(
1526								&mut output,
1527								format_args!(", \"workspace\": \"{}\"}}", contract.workspace.token()),
1528							);
1529						}
1530					}
1531					crate::core::push_format(
1532						&mut output,
1533						format_args!(
1534							", \"groups\": [{}, {}, {}], \"queue\": \"{}\", \"family\": {}, \"indirect\": {}",
1535							node.workgroups[0],
1536							node.workgroups[1],
1537							node.workgroups[2],
1538							graph_node.queue().name(),
1539							self.graph.node_families()[index],
1540							node.indirect.is_some()
1541						),
1542					);
1543				}
1544				GraphNode::BufferCopy(copy) => {
1545					output.push_str(
1546						r#"], "kind": "buffer_copy", "implementation_id": "0x4255465f434f5059", "operation_contract_hash": "#,
1547					);
1548					push_optional_hex(&mut output, contract);
1549					crate::core::push_format(
1550						&mut output,
1551						format_args!(
1552							r#", "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "vk.copy_buffer", "dtype_class": null, "dtype": "float32", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "copy_bytes": {}"#,
1553							graph_node.queue().name(),
1554							self.graph.node_families()[index],
1555							copy.bytes,
1556						),
1557					);
1558				}
1559				GraphNode::VideoDecode(video) => {
1560					crate::core::push_format(
1561						&mut output,
1562						format_args!(
1563							r#"], "kind": "video_decode", "implementation_id": "0x5649444445434f44", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{operation}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "decode_picture": ["#,
1564							graph_node.queue().name(),
1565							self.graph.node_families()[index],
1566						),
1567					);
1568					for (index, word) in video.descriptor_words().into_iter().enumerate() {
1569						if index != 0 {
1570							output.push_str(", ");
1571						}
1572						crate::core::push_format(&mut output, format_args!("{word}"));
1573					}
1574					output.push(']');
1575				}
1576
1577				GraphNode::VideoEncode(video) => {
1578					crate::core::push_format(
1579						&mut output,
1580						format_args!(
1581							r#"], "kind": "video_encode", "implementation_id": "0x564944454e434f44", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{operation}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "encode_picture": ["#,
1582							graph_node.queue().name(),
1583							self.graph.node_families()[index],
1584						),
1585					);
1586					for (index, word) in video.descriptor_words().into_iter().enumerate() {
1587						if index != 0 {
1588							output.push_str(", ");
1589						}
1590						crate::core::push_format(&mut output, format_args!("{word}"));
1591					}
1592					output.push(']');
1593				}
1594				GraphNode::VideoEncodeInput(video) => {
1595					crate::core::push_format(
1596						&mut output,
1597						format_args!(
1598							r#"], "kind": "video_encode_input", "implementation_id": "0x564944454e43494e", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "image_geometry": ["#,
1599							video.copy.name(),
1600							graph_node.queue().name(),
1601							self.graph.node_families()[index],
1602						),
1603					);
1604					for (index, word) in video.copy.descriptor_words().enumerate() {
1605						if index != 0 {
1606							output.push_str(", ");
1607						}
1608						crate::core::push_format(&mut output, format_args!("{word}"));
1609					}
1610					output.push(']');
1611				}
1612				GraphNode::VideoPlanes(video) => {
1613					crate::core::push_format(
1614						&mut output,
1615						format_args!(
1616							r#"], "kind": "video_plane_command", "implementation_id": "0x564944504c414e45", "operation_contract_hash": null, "problem_contract_hash": null, "kernel_content_hash": "0x0000000000000000", "kernel_selection": "native", "kernel": "{}", "dtype_class": null, "dtype": "uint8", "physical_write": null, "groups": [0, 0, 0], "queue": "{}", "family": {}, "indirect": false, "image_geometry": ["#,
1617							video.phase.name(),
1618							graph_node.queue().name(),
1619							self.graph.node_families()[index],
1620						),
1621					);
1622					for (index, word) in video.copy.descriptor_words().enumerate() {
1623						if index != 0 {
1624							output.push_str(", ");
1625						}
1626						crate::core::push_format(&mut output, format_args!("{word}"));
1627					}
1628					output.push(']');
1629				}
1630			}
1631			output.push_str(r#", "effects": ["#);
1632			for (effect_index, effect) in graph_node.buffers().iter().enumerate() {
1633				if effect_index != 0 {
1634					output.push_str(", ");
1635				}
1636				let resource = graph_resource_id(&lifetimes, &effect.buffer)
1637					.expect("node buffer must have a resource lifetime");
1638				crate::core::push_format(
1639					&mut output,
1640					format_args!(
1641						"{{\"resource\": {resource}, \"access\": \"{}\"}}",
1642						buffer_access_token(effect.access)
1643					),
1644				);
1645			}
1646			output.push_str("]}");
1647		}
1648		if !self.graph.nodes().is_empty() {
1649			output.push('\n');
1650		}
1651		output.push_str("  ]\n}\n");
1652		output
1653	}
1654
1655	pub(super) fn belongs_to(&self, engine: &EngineHandle) -> bool {
1656		self.engine.same_as(engine)
1657	}
1658
1659	pub(crate) fn validate_training_replay_safety(&self) -> Result<()> {
1660		self.graph.validate_training_replay_safety()
1661	}
1662
1663	fn binding_key(&self) -> Vec<u32> {
1664		self
1665			.input_bindings
1666			.iter()
1667			.map(|binding| binding.current.descriptor_index())
1668			.collect()
1669	}
1670
1671	/// Node ranges of the executable graph that each fit the device's
1672	/// estimated submission budget. Splitting is per queue run — every
1673	/// emitted range resolves to one queue family. A single returned range
1674	/// keeps the one-buffer fast path; several ranges become sequential
1675	/// timeline submissions at node boundaries. A node whose own estimate
1676	/// exceeds the budget declines here, before anything records or
1677	/// submits.
1678	pub(super) fn submission_ranges(
1679		&self,
1680		device: &Arc<Device>,
1681	) -> Result<Vec<std::ops::Range<usize>>> {
1682		let budget = device.submission_budget_ns();
1683		let mut ranges = Vec::new();
1684		for run in self.graph.queue_runs() {
1685			for range in
1686				self
1687					.graph
1688					.budget_ranges_within(run.nodes, budget)
1689					.map_err(|(index, estimate)| {
1690						Error::resource_exhausted(format!(
1691							"node {} ({}) estimated {:.1}ms exceeds the {:.1}ms submission budget",
1692							index,
1693							self.graph.nodes()[index].semantic().0,
1694							estimate as f64 / 1e6,
1695							budget as f64 / 1e6,
1696						))
1697					})? {
1698				if !range.is_empty() {
1699					ranges.push(range);
1700				}
1701			}
1702		}
1703		Ok(ranges)
1704	}
1705
1706	pub(super) fn graph(&self) -> &ExecutableGraph {
1707		&self.graph
1708	}
1709
1710	/// One reusable command buffer per queue run, in submission order.
1711	/// A single-run graph returns one command; a mixed-family graph
1712	/// returns one command per run for the timeline-chained batch.
1713	pub(super) fn reusable_commands(
1714		&self,
1715		device: &Arc<Device>,
1716	) -> Result<Vec<RecordedCommandBuffer>> {
1717		let key = self.binding_key();
1718		if let Some((_, commands)) = self
1719			.cached_commands
1720			.borrow()
1721			.iter()
1722			.find(|(cached_key, _)| *cached_key == key)
1723		{
1724			increment(&self.counters.command_cache_hits);
1725			return Ok(
1726				commands
1727					.iter()
1728					.map(|command| command.submission())
1729					.collect(),
1730			);
1731		}
1732		let runs = self.graph.queue_runs();
1733		let commands = if runs.len() == 1 {
1734			vec![device.record_reusable_compute_graph(&self.graph)?]
1735		} else {
1736			runs
1737				.into_iter()
1738				.map(|run| device.record_reusable_graph_range(&self.graph, run.nodes))
1739				.collect::<Result<Vec<_>>>()?
1740		};
1741		increment(&self.counters.command_recordings);
1742		let submissions = commands
1743			.iter()
1744			.map(|command| command.submission())
1745			.collect();
1746		let mut cache = self.cached_commands.borrow_mut();
1747		if cache.len() == MAX_CACHED_BINDING_COMMANDS {
1748			cache.remove(0);
1749		}
1750		cache.push((key, commands));
1751		Ok(submissions)
1752	}
1753
1754	pub(super) fn count_command_recording(&self) {
1755		increment(&self.counters.command_recordings);
1756	}
1757
1758	pub(super) fn precompile(&self, device: &Arc<Device>) -> Result<()> {
1759		if self.graph.has_video() {
1760			let mut commands = super::device::logical::command::RecordedBatch::new(device);
1761			for range in self.submission_ranges(device)? {
1762				commands.push(device.record_fresh_graph_range(&self.graph, range, false)?);
1763			}
1764		} else {
1765			let _ = self.reusable_commands(device)?;
1766		}
1767		Ok(())
1768	}
1769
1770	pub(super) fn mark_submitted(&self, event: &Event) {
1771		for output in &self.outputs {
1772			output.mark_submitted(event.clone());
1773		}
1774		for binding in &self.input_bindings {
1775			if let Some(slot) = binding
1776				.staging
1777				.iter()
1778				.find(|slot| slot.buffer.same_as(&binding.current))
1779			{
1780				slot.consumer.replace(Some(event.clone()));
1781			}
1782			binding.current.record_bound_consumer(event);
1783		}
1784		self.last_submission.replace(Some(event.clone()));
1785		increment(&self.counters.submissions);
1786	}
1787
1788	pub(super) fn mark_failed(&self) {
1789		for output in &self.outputs {
1790			output.mark_failed();
1791		}
1792	}
1793}
1794
1795fn increment(counter: &Cell<u64>) {
1796	counter.set(counter.get().saturating_add(1));
1797}
1798
1799fn graph_resource_id(
1800	lifetimes: &[super::graph::executable::ResourceLifetime],
1801	buffer: &Buffer,
1802) -> Option<usize> {
1803	lifetimes
1804		.iter()
1805		.position(|lifetime| lifetime.buffer.same_as(buffer))
1806}
1807
1808const fn hazard_reason(source: AccessState, destination: AccessState) -> &'static str {
1809	match (source.writes(), destination.writes()) {
1810		(true, true) => "write_after_write",
1811		(true, false) => "read_after_write",
1812		(false, true) => "write_after_read",
1813		(false, false) => "queue_ownership",
1814	}
1815}
1816
1817fn push_stage_names(output: &mut String, access: AccessState) {
1818	let mask = access.vk_stages();
1819	push_names(
1820		output,
1821		[
1822			(
1823				mask.contains(vk::PipelineStageFlagBits2::COMPUTE_SHADER_BIT),
1824				"compute_shader",
1825			),
1826			(
1827				mask.contains(vk::PipelineStageFlagBits2::DRAW_INDIRECT_BIT),
1828				"draw_indirect",
1829			),
1830			(mask.contains(vk::PipelineStageFlagBits2::COPY_BIT), "copy"),
1831		],
1832	);
1833}
1834
1835fn push_access_names(output: &mut String, access: AccessState) {
1836	let mask = access.vk_access();
1837	push_names(
1838		output,
1839		[
1840			(
1841				mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_READ_BIT),
1842				"shader_storage_read",
1843			),
1844			(
1845				mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_WRITE_BIT),
1846				"shader_storage_write",
1847			),
1848			(
1849				mask.contains(vk::AccessFlagBits2::INDIRECT_COMMAND_READ_BIT),
1850				"indirect_command_read",
1851			),
1852			(
1853				mask.contains(vk::AccessFlagBits2::TRANSFER_READ_BIT),
1854				"transfer_read",
1855			),
1856			(
1857				mask.contains(vk::AccessFlagBits2::TRANSFER_WRITE_BIT),
1858				"transfer_write",
1859			),
1860		],
1861	);
1862}
1863
1864fn push_names(output: &mut String, names: impl IntoIterator<Item = (bool, &'static str)>) {
1865	let mut separator = "";
1866	for (_, name) in names.into_iter().filter(|(present, _)| *present) {
1867		output.push_str(separator);
1868		crate::core::push_json_string(output, name);
1869		separator = ", ";
1870	}
1871}
1872
1873const fn buffer_access_token(access: super::BufferAccess) -> &'static str {
1874	match access {
1875		super::BufferAccess::Read => "read",
1876		super::BufferAccess::Write => "write",
1877		super::BufferAccess::ReadWrite => "read_write",
1878	}
1879}
1880
1881fn push_optional_hex(output: &mut String, value: u64) {
1882	if value == 0 {
1883		output.push_str("null");
1884	} else {
1885		crate::core::push_format(output, format_args!("\"0x{value:016x}\""));
1886	}
1887}
1888
1889fn find_resource(
1890	lifetimes: &[super::graph::executable::ResourceLifetime],
1891	storage: &Storage,
1892) -> Result<usize> {
1893	let buffer = storage.buffer().ok_or_else(|| {
1894		Error::failed_precondition("captured semantic resource has no allocated storage")
1895	})?;
1896	lifetimes
1897		.iter()
1898		.position(|lifetime| lifetime.buffer.same_as(buffer))
1899		.ok_or_else(|| Error::failed_precondition("captured resource does not appear in the graph"))
1900}
1901
1902fn find_resource_storage<'a>(
1903	buffer: &Buffer,
1904	stable_resources: &'a [StableResourceSnapshot],
1905	semantic_storage: &'a [SemanticStorageSnapshot],
1906	observed_outputs: &'a [Storage],
1907	outputs: &'a [Storage],
1908) -> Option<&'a Storage> {
1909	// A lowering may create an immutable physical parameter buffer that is not a
1910	// semantic value or public output. The executable graph's Buffer retains
1911	// that allocation; absence here only means there is no Matrix-level owner to
1912	// count or consider for transient aliasing.
1913	stable_resources
1914		.iter()
1915		.map(|candidate| &candidate.storage)
1916		.chain(semantic_storage.iter().map(|candidate| &candidate.storage))
1917		.chain(observed_outputs.iter())
1918		.chain(outputs.iter())
1919		.find(|storage| {
1920			storage
1921				.buffer()
1922				.is_some_and(|candidate| candidate.same_as(buffer))
1923		})
1924}
1925
1926struct AliasGroup {
1927	resources: Vec<usize>,
1928	required_size: usize,
1929}
1930
1931struct AliasMaterialization {
1932	graph: ExecutableGraph,
1933	outputs: Vec<Storage>,
1934	captured_resources: Vec<CapturedResourceDesc>,
1935	retired: Vec<Buffer>,
1936	savings: usize,
1937}
1938
1939fn materialize_aliases(
1940	engine: &EngineHandle,
1941	graph: &ExecutableGraph,
1942	outputs: &[Storage],
1943	resource_lifetimes: &[super::graph::executable::ResourceLifetime],
1944	captured_resources: &[CapturedResourceDesc],
1945) -> Result<AliasMaterialization> {
1946	let mut graph = graph.clone();
1947	let mut outputs = outputs.to_vec();
1948	let mut captured_resources = captured_resources.to_vec();
1949	let groups = alias_groups(&captured_resources);
1950	let mut replacements = Vec::new();
1951	let mut retired = Vec::new();
1952	let mut savings = 0_usize;
1953	for group in groups.iter().filter(|group| group.resources.len() > 1) {
1954		let arena = engine.create_alias_arena(group.required_size)?;
1955		let original_bytes = group.resources.iter().try_fold(0_usize, |sum, resource| {
1956			sum
1957				.checked_add(captured_resources[*resource].byte_len)
1958				.ok_or_else(|| Error::resource_exhausted("materialized alias byte accounting overflowed"))
1959		})?;
1960		savings = savings
1961			.checked_add(original_bytes.saturating_sub(group.required_size))
1962			.ok_or_else(|| Error::resource_exhausted("alias savings accounting overflowed"))?;
1963		for resource in &group.resources {
1964			let source = resource_lifetimes[*resource].buffer.clone();
1965			retired.push(source.clone());
1966			replacements.push((source, arena.clone()));
1967			captured_resources[*resource].alias_materialized = true;
1968		}
1969	}
1970	if !replacements.is_empty() {
1971		graph.materialize_alias_replacements(&replacements)?;
1972		outputs.retain(|storage| {
1973			storage
1974				.buffer()
1975				.is_none_or(|buffer| !retired.iter().any(|candidate| candidate.same_as(buffer)))
1976		});
1977	}
1978	Ok(AliasMaterialization {
1979		graph,
1980		outputs,
1981		captured_resources,
1982		retired,
1983		savings,
1984	})
1985}
1986
1987fn alias_groups(resources: &[CapturedResourceDesc]) -> Vec<AliasGroup> {
1988	let mut eligible = resources
1989		.iter()
1990		.enumerate()
1991		.filter_map(|(index, resource)| resource.alias_candidate.then_some(index))
1992		.collect::<Vec<_>>();
1993	eligible.sort_by_key(|index| (resources[*index].first_access, resources[*index].resource));
1994	let mut groups = Vec::<AliasGroup>::new();
1995	for resource in eligible {
1996		let desc = resources[resource];
1997		if let Some(group) = groups.iter_mut().find(|group| {
1998			group.resources.iter().all(|member| {
1999				let member = resources[*member];
2000				desc.first_access > member.last_access || desc.last_access < member.first_access
2001			})
2002		}) {
2003			group.required_size = group.required_size.max(desc.byte_len);
2004			group.resources.push(resource);
2005		} else {
2006			groups.push(AliasGroup {
2007				resources: vec![resource],
2008				required_size: desc.byte_len,
2009			});
2010		}
2011	}
2012	groups
2013}
2014
2015fn alias_analysis(resources: &[CapturedResourceDesc]) -> (usize, usize) {
2016	let groups = alias_groups(resources);
2017	let mut count = 0_usize;
2018	let mut savings = 0_usize;
2019	for group in groups.iter().filter(|group| group.resources.len() > 1) {
2020		count = count.saturating_add(1);
2021		let bytes = group.resources.iter().fold(0_usize, |total, resource| {
2022			total.saturating_add(resources[*resource].byte_len)
2023		});
2024		savings = savings.saturating_add(bytes.saturating_sub(group.required_size));
2025	}
2026	(count, savings)
2027}
2028
2029impl fmt::Debug for ExecutionPlan {
2030	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2031		formatter
2032			.debug_struct("ExecutionPlan")
2033			.field("graph_id", &format_args!("{:016x}", self.graph_id))
2034			.field("node_count", &self.graph.nodes().len())
2035			.finish_non_exhaustive()
2036	}
2037}
2038
2039#[cfg(test)]
2040#[path = "../../../../test/rs/runtime/plan_binding_unit.rs"]
2041mod tests;