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, Event, RecordedCommandBuffer, ReusableCommandBuffer, RuntimeHandle,
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/// Runtime-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	runtime: RuntimeHandle,
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		runtime: RuntimeHandle,
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 = runtime.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			&runtime,
755			&semantic,
756			&semantic_bindings,
757			&resource_lifetimes,
758			&captured_resources,
759			!source_recording_retained,
760			&graph,
761		)?;
762		runtime.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			&runtime,
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		runtime.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			runtime,
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.runtime.same_as(captured.runtime()) {
898			return Err(Error::invalid_argument(
899				"execution-plan Matrix input belongs to another runtime",
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.runtime.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	/// runtime, 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 runtime, 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.runtime.same_as(captured.runtime()) || !self.runtime.same_as(replacement.runtime()) {
1005			return Err(Error::invalid_argument(
1006				"execution-plan Matrix bindings must belong to the plan's runtime",
1007			));
1008		}
1009		if captured.shape() != replacement.shape() || captured.dtype() != replacement.dtype() {
1010			return Err(Error::invalid_argument(format!(
1011				"execution-plan Matrix input requires shape {:?} and dtype {}; replacement has shape {:?} and dtype {}",
1012				captured.shape(),
1013				captured.dtype().token(),
1014				replacement.shape(),
1015				replacement.dtype().token()
1016			)));
1017		}
1018		replacement
1019			.storage()
1020			.validate_recording_access(BufferAccess::Read)?;
1021		let captured_buffer = captured.storage().buffer().ok_or_else(|| {
1022			Error::invalid_argument("zero-sized Matrix storage cannot identify a captured plan input")
1023		})?;
1024		let replacement_buffer = replacement.storage().buffer().ok_or_else(|| {
1025			Error::invalid_argument("zero-sized Matrix storage cannot replace a captured plan input")
1026		})?;
1027
1028		let existing = self
1029			.input_bindings
1030			.iter()
1031			.position(|binding| binding.original.same_as(captured_buffer))
1032			.ok_or_else(|| {
1033				Error::invalid_argument("captured Matrix is not a read-only input of this execution plan")
1034			})?;
1035		let current = self.input_bindings[existing].current.clone();
1036		if current.same_as(replacement_buffer) {
1037			return Ok(());
1038		}
1039		self.graph.rebind_read_only(
1040			&current,
1041			replacement_buffer,
1042			self.runtime.execution_profile(),
1043		)?;
1044		self.input_bindings[existing].current = replacement_buffer.clone();
1045		increment(&self.counters.input_rebindings);
1046		Ok(())
1047	}
1048
1049	/// Return the number of entries in the compiled specialization contract.
1050	///
1051	/// Donor: `oa::ExecutionPlan::bindingCount`.
1052	pub const fn binding_count(&self) -> usize {
1053		self.bindings.len()
1054	}
1055
1056	/// Return the number of contract entries with an input role.
1057	///
1058	/// Donor: `oa::ExecutionPlan::inputBindingCount`.
1059	pub fn input_binding_count(&self) -> usize {
1060		self
1061			.bindings
1062			.iter()
1063			.filter(|binding| binding.role() == ExecutionBindingRole::Input)
1064			.count()
1065	}
1066
1067	/// Return the number of contract entries with an output role.
1068	///
1069	/// Donor: `oa::ExecutionPlan::outputBindingCount`.
1070	pub fn output_binding_count(&self) -> usize {
1071		self.bindings.len() - self.input_binding_count()
1072	}
1073
1074	/// Return the contract entry at `slot`.
1075	///
1076	/// Donor: `oa::ExecutionPlan::binding`.
1077	///
1078	/// # Errors
1079	///
1080	/// Returns `InvalidArgument` when `slot` is out of range.
1081	pub fn binding(&self, slot: u32) -> Result<ExecutionBindingDesc> {
1082		self
1083			.bindings
1084			.get(slot as usize)
1085			.cloned()
1086			.ok_or_else(|| Error::invalid_argument("execution plan binding slot is out of range"))
1087	}
1088
1089	/// Return the deterministic hash of the compiled specialization contract.
1090	///
1091	/// Donor: `oa::ExecutionPlan::bindingContractHash`.
1092	pub const fn binding_contract_hash(&self) -> u64 {
1093		self.binding_contract_hash
1094	}
1095
1096	/// Validate specialization input matrices against the compiled contract.
1097	///
1098	/// Validation checks the exact shape, dtype, strides, and byte offset of
1099	/// each contract input in order. It deliberately does not rebind resources:
1100	/// dynamic dimensions select or recapture another checked plan rather than
1101	/// mutating this plan's recorded command buffers.
1102	///
1103	/// Donor: `oa::ExecutionPlan::validateSpecializationInputs`.
1104	///
1105	/// # Errors
1106	///
1107	/// Returns `InvalidArgument` when the input count differs, and
1108	/// `FailedPrecondition` when any input's contract requires another plan or
1109	/// is not a matrix.
1110	pub fn validate_specialization_inputs(&self, inputs: &[crate::Matrix]) -> Result<()> {
1111		if inputs.len() != self.input_binding_count() {
1112			return Err(Error::invalid_argument(
1113				"specialization input count does not match the compiled plan",
1114			));
1115		}
1116		let mut input_index = 0_usize;
1117		for binding in &self.bindings {
1118			if binding.role() != ExecutionBindingRole::Input {
1119				continue;
1120			}
1121			if binding.kind() != crate::OpValueKind::Matrix {
1122				return Err(Error::failed_precondition(
1123					"matrix specialization validation cannot bind a non-Matrix input",
1124				));
1125			}
1126			let input = &inputs[input_index];
1127			input_index += 1;
1128			let absolute_offset = {
1129				let mut offset = 0_i64;
1130				let mut semantic = input.semantic().clone();
1131				loop {
1132					offset = offset
1133						.checked_add(semantic.view_byte_offset())
1134						.ok_or_else(|| Error::internal("matrix view byte offset overflows i64"))?;
1135					match semantic.view_source() {
1136						Some(source) => semantic = source.clone(),
1137						None => break,
1138					}
1139				}
1140				offset
1141			};
1142			if input.shape() != binding.shape()
1143				|| input.dtype() != binding.dtype()
1144				|| absolute_offset < 0
1145				|| absolute_offset as u64 != binding.byte_offset()
1146			{
1147				return Err(Error::failed_precondition(
1148					"specialization input shape, dtype or offset requires another plan",
1149				));
1150			}
1151			if super::graph::semantic::dense_strides(input.shape())? != binding.strides() {
1152				return Err(Error::failed_precondition(
1153					"specialization input strides require another plan",
1154				));
1155			}
1156		}
1157		Ok(())
1158	}
1159
1160	/// Return current graph, cache, submission, rebinding, and fallback counters.
1161	pub fn diagnostics(&self) -> ExecutionPlanDiagnostics {
1162		let (planned_alias_group_count, potential_alias_savings) =
1163			alias_analysis(&self.captured_resources);
1164		ExecutionPlanDiagnostics {
1165			graph_id: self.graph_id,
1166			device_capability_identity: self.device_capability_identity,
1167			node_count: self.graph.nodes().len(),
1168			barrier_count: self.graph.barrier_count(),
1169			cross_queue_edge_count: self.graph.cross_queue_edge_count(),
1170			ownership_transfer_count: self.graph.ownership_transfer_count(),
1171			queue_run_count: self.graph.queue_runs().len(),
1172			semantic_operation_count: self.semantic.operations().len(),
1173			semantic_autograd_attachment_count: self.semantic.autograd().len(),
1174			semantic_autograd_expanded_count: self
1175				.semantic
1176				.autograd()
1177				.iter()
1178				.filter(|entry| entry.is_backward_expanded())
1179				.count(),
1180			semantic_backward_operation_count: self
1181				.semantic
1182				.autograd()
1183				.iter()
1184				.map(|entry| entry.backward_op_count())
1185				.sum(),
1186			schema_owned_node_count: self.semantic_lowering.schema_owned_node_count() as usize,
1187			compatibility_node_count: self.semantic_lowering.compatibility_node_count() as usize,
1188			semantic_fused_operation_count: self.semantic_lowering.fused_op_count() as usize,
1189			semantic_fused_node_count: self.semantic_lowering.fused_node_count() as usize,
1190			maximum_semantic_operations_per_node: self.semantic_lowering.maximum_ops_per_node() as usize,
1191			dnn_graph_hash: self.dnn.graph_hash(),
1192			dnn_value_count: self.dnn.value_count(),
1193			dnn_external_value_count: self.dnn.external_value_count(),
1194			dnn_virtual_value_count: self.dnn.virtual_value_count(),
1195			dnn_partition_count: self.dnn.partition_count(),
1196			dnn_recognized_partition_count: self.dnn.recognized_partition_count(),
1197			dnn_portable_partition_count: self.dnn.portable_partition_count(),
1198			dnn_captured_operation_count: self.dnn.captured_operation_count(),
1199			dnn_applied_partition_count: self.dnn.applied_partition_count(),
1200			dnn_inherited_partition_count: self.dnn.inherited_partition_count(),
1201			dnn_fallback_partition_count: self.dnn.fallback_partition_count(),
1202			dnn_unexpected_fallback_count: self.dnn.unexpected_fallback_count(),
1203			input_binding_count: self.input_bindings.len(),
1204			captured_resource_count: self.captured_resources.len(),
1205			physical_resource_count: self.graph.resource_lifetimes().len(),
1206			stable_replay_input_count: self
1207				.captured_resources
1208				.iter()
1209				.filter(|resource| resource.stable_replay_input)
1210				.count(),
1211			stable_transient_count: self
1212				.captured_resources
1213				.iter()
1214				.filter(|resource| resource.stable_transient)
1215				.count(),
1216			semantic_binding_count: self.semantic_bindings.len(),
1217			observed_output_count: self
1218				.captured_resources
1219				.iter()
1220				.filter(|resource| resource.observed_output)
1221				.count(),
1222			alias_candidate_count: self
1223				.captured_resources
1224				.iter()
1225				.filter(|resource| resource.alias_candidate)
1226				.count(),
1227			alias_materialized_count: self
1228				.captured_resources
1229				.iter()
1230				.filter(|resource| resource.alias_materialized)
1231				.count(),
1232			planned_alias_group_count,
1233			potential_alias_savings,
1234			materialized_alias_savings: self.materialized_alias_savings,
1235			descriptor_write_count: self.descriptor_write_count,
1236			peak_memory_bytes: {
1237				let mut lifetimes = self.graph.resource_lifetimes();
1238				lifetimes.sort_by_key(|lifetime| lifetime.first_access);
1239				let mut active: Vec<(usize, u32, usize)> = Vec::new();
1240				let mut peak = 0_usize;
1241				for lifetime in lifetimes {
1242					active.retain(|(last, _, _)| *last >= lifetime.first_access);
1243					let index = lifetime.buffer.descriptor_index();
1244					if !active.iter().any(|(_, live, _)| *live == index) {
1245						active.push((lifetime.last_access, index, lifetime.buffer.byte_len()));
1246					}
1247					peak = peak.max(active.iter().map(|(_, _, bytes)| *bytes).sum::<usize>());
1248				}
1249				peak
1250			},
1251			push_byte_count: self
1252				.graph
1253				.compute_nodes()
1254				.map(|node| node.push_constants.len() * 4)
1255				.sum(),
1256			command_recording_count: self.counters.command_recordings.get(),
1257			command_cache_hit_count: self.counters.command_cache_hits.get(),
1258			submission_count: self.counters.submissions.get(),
1259			input_rebinding_count: self.counters.input_rebindings.get(),
1260			input_upload_count: self.counters.input_uploads.get(),
1261			fallback_count: self.counters.fallbacks.get(),
1262		}
1263	}
1264
1265	pub(crate) fn dnn_fallback_reasons(&self) -> impl Iterator<Item = &str> {
1266		self.dnn.fallback_reasons()
1267	}
1268
1269	/// Return whether the most recently submitted replay has completed.
1270	///
1271	/// A plan that has not been submitted is complete.
1272	///
1273	/// # Errors
1274	///
1275	/// Returns an error when Vulkan cannot query the originating timeline.
1276	pub fn is_complete(&self) -> Result<bool> {
1277		let event = self.last_submission.borrow().clone();
1278		event.map_or(Ok(true), |event| event.is_complete())
1279	}
1280
1281	/// Wait for the most recently submitted replay and its host retirement.
1282	///
1283	/// Same-queue timeline order means completion of the latest replay also proves
1284	/// completion of every earlier replay submitted through this plan.
1285	///
1286	/// # Errors
1287	///
1288	/// Returns an error when Vulkan completion or host retirement waiting fails.
1289	pub fn wait(&self) -> Result<()> {
1290		let event = self.last_submission.borrow().clone();
1291		if let Some(event) = event {
1292			event.wait()?;
1293		}
1294		Ok(())
1295	}
1296
1297	/// Wait for pending replay and consume the plan, releasing retained state.
1298	///
1299	/// This is the Rust ownership equivalent of the donor's mutable `reset`: plan
1300	/// capture constructs a new value rather than repopulating an empty shell.
1301	/// Destruction remains non-blocking when this explicit boundary is not used.
1302	///
1303	/// # Errors
1304	///
1305	/// Returns an error from [`ExecutionPlan::wait`]. The consumed plan still drops
1306	/// safely on error; submitted resources remain owned by runtime retirement.
1307	pub fn reset(self) -> Result<()> {
1308		self.wait()
1309	}
1310
1311	/// Return the deterministic normalized executable graph report as JSON.
1312	///
1313	/// Resource and hazard-domain IDs follow first graph access. Vulkan handles,
1314	/// device addresses, descriptor indices, and push payloads are omitted.
1315	pub fn debug_report_json(&self, name: &str) -> String {
1316		let diagnostics = self.diagnostics();
1317		let lifetimes = self.graph.resource_lifetimes();
1318		let compiled = self
1319			.cached_commands
1320			.borrow()
1321			.iter()
1322			.any(|(cached_key, _)| *cached_key == self.binding_key());
1323		let last_event = self.last_submission.borrow().clone();
1324		let mut output = String::new();
1325		output.push_str("{\n  \"schema\": \"oa.execution_graph.v3\",\n  \"name\": ");
1326		crate::core::push_json_string(&mut output, name);
1327		crate::core::push_format(
1328			&mut output,
1329			format_args!(
1330				",\n  \"compiled\": {},\n  \"completion\": {{\"submitted\": {}, \"timeline_value\": {}}},\n",
1331				compiled,
1332				last_event.is_some(),
1333				last_event.as_ref().map_or(0, Event::epoch),
1334			),
1335		);
1336		let mut war_barriers = 0;
1337		let mut indirect_barriers = 0;
1338		for barrier in (0..self.graph.nodes().len()).flat_map(|node| self.graph.barriers_before(node)) {
1339			war_barriers += usize::from(!barrier.source.writes() && barrier.destination.writes());
1340			indirect_barriers += usize::from(barrier.destination.uses_indirect_commands());
1341		}
1342		let dispatches = self.graph.compute_nodes().count();
1343		let copies = self
1344			.graph
1345			.nodes()
1346			.iter()
1347			.filter(|node| matches!(node, GraphNode::BufferCopy(_)))
1348			.count();
1349		let video_commands = diagnostics.node_count() - dispatches - copies;
1350		let buffer_bytes = lifetimes.iter().fold(0_usize, |total, lifetime| {
1351			total.saturating_add(lifetime.buffer.byte_len())
1352		});
1353		crate::core::push_format(
1354			&mut output,
1355			format_args!(
1356				"  \"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\": {}",
1357				diagnostics.barrier_count(),
1358				war_barriers,
1359				indirect_barriers,
1360				buffer_bytes,
1361				diagnostics.potential_alias_savings(),
1362				diagnostics.materialized_alias_savings(),
1363			),
1364		);
1365		if copies != 0 {
1366			crate::core::push_format(&mut output, format_args!(r#", "copies": {copies}"#));
1367		}
1368		if video_commands != 0 {
1369			let image_transfers = self.graph.image_transfer_count();
1370			crate::core::push_format(
1371				&mut output,
1372				format_args!(
1373					r#", "video_commands": {video_commands}, "image_transfers": {image_transfers}"#
1374				),
1375			);
1376		}
1377		output.push_str("},\n  \"resources\": [");
1378		for (resource, lifetime) in lifetimes.iter().enumerate() {
1379			output.push_str(if resource == 0 { "\n" } else { ",\n" });
1380			crate::core::push_format(
1381				&mut output,
1382				format_args!(
1383					"    {{\"id\": {resource}, \"hazard_domain\": {resource}, \"bytes\": {}, \"first_node\": {}, \"last_node\": {}}}",
1384					lifetime.buffer.byte_len(),
1385					lifetime.first_access,
1386					lifetime.last_access,
1387				),
1388			);
1389		}
1390		if !lifetimes.is_empty() {
1391			output.push('\n');
1392		}
1393		// OARS alias arenas deliberately collapse a group to one buffer identity.
1394		// Logical group membership remains available in the compilation report.
1395		output.push_str("  ],\n  \"alias_groups\": [],\n  \"barriers\": [");
1396		let mut barrier_index = 0_usize;
1397		for destination_node in 0..self.graph.nodes().len() {
1398			let barriers = self.graph.barriers_before(destination_node);
1399			for barrier in barriers {
1400				output.push_str(if barrier_index == 0 { "\n" } else { ",\n" });
1401				barrier_index = barrier_index.saturating_add(1);
1402				let resource = graph_resource_id(&lifetimes, &barrier.buffer)
1403					.expect("planned barrier resource must have a lifetime");
1404				let [first_source, last_source] = barrier.source_nodes;
1405				let source_stage = barrier.source.vk_stages().as_raw();
1406				let destination_stage = barrier.destination.vk_stages().as_raw();
1407				let source_access = barrier.source.vk_access().as_raw();
1408				let destination_access = barrier.destination.vk_access().as_raw();
1409				crate::core::push_format(
1410					&mut output,
1411					format_args!(
1412						"    {{\"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\": [",
1413						hazard_reason(barrier.source, barrier.destination),
1414						barrier.buffer.byte_len(),
1415						barrier.source_queue.name(),
1416						barrier.destination_queue.name(),
1417						barrier.source_family,
1418						barrier.destination_family,
1419						barrier.is_cross_queue(),
1420						barrier.is_ownership_transfer(),
1421					),
1422				);
1423				push_stage_names(&mut output, barrier.source);
1424				crate::core::push_format(
1425					&mut output,
1426					format_args!(
1427						"], \"source_access_mask\": \"0x{source_access:016x}\", \"source_accesses\": ["
1428					),
1429				);
1430				push_access_names(&mut output, barrier.source);
1431				crate::core::push_format(
1432					&mut output,
1433					format_args!(
1434						"], \"destination_stage_mask\": \"0x{destination_stage:016x}\", \"destination_stages\": ["
1435					),
1436				);
1437				push_stage_names(&mut output, barrier.destination);
1438				crate::core::push_format(
1439					&mut output,
1440					format_args!(
1441						"], \"destination_access_mask\": \"0x{destination_access:016x}\", \"destination_accesses\": ["
1442					),
1443				);
1444				push_access_names(&mut output, barrier.destination);
1445				output.push_str("]}");
1446			}
1447		}
1448		if barrier_index != 0 {
1449			output.push('\n');
1450		}
1451		output.push_str("  ],\n  \"nodes\": [");
1452		for (index, graph_node) in self.graph.nodes().iter().enumerate() {
1453			let (operation, semantic_ops, contract) = graph_node.semantic();
1454			output.push_str(if index == 0 { "\n" } else { ",\n" });
1455			crate::core::push_format(
1456				&mut output,
1457				format_args!("    {{\"index\": {index}, \"operation\": "),
1458			);
1459			crate::core::push_json_string(&mut output, operation);
1460			output.push_str(", \"semantic_operations\": [");
1461			for (owner_index, owner) in semantic_ops.iter().enumerate() {
1462				if owner_index != 0 {
1463					output.push_str(", ");
1464				}
1465				crate::core::push_format(&mut output, format_args!("{}", owner.index()));
1466			}
1467			match graph_node {
1468				GraphNode::Compute(node) => {
1469					let implementation_id = node.kernel.artifact().content_id();
1470					crate::core::push_format(
1471						&mut output,
1472						format_args!(
1473							"], \"implementation_id\": \"0x{implementation_id:016x}\", \"operation_contract_hash\": "
1474						),
1475					);
1476					push_optional_hex(&mut output, contract);
1477					crate::core::push_format(
1478						&mut output,
1479						format_args!(
1480							", \"problem_contract_hash\": null, \"kernel_content_hash\": \"0x{implementation_id:016x}\", \"kernel_selection\": \"direct\", \"kernel\": "
1481						),
1482					);
1483					crate::core::push_json_string(&mut output, node.kernel.report_name());
1484					output.push_str(", \"dtype_class\": null, \"dtype\": ");
1485					crate::core::push_json_string(&mut output, node.kernel.dtype_report_token());
1486					output.push_str(", \"physical_write\": ");
1487					match node.kernel.artifact().physical_write {
1488						None => output.push_str("null"),
1489						Some(contract) => {
1490							output.push_str("{\"writes\": [");
1491							for (write_index, write) in contract.writes.iter().enumerate() {
1492								if write_index != 0 {
1493									output.push_str(", ");
1494								}
1495								crate::core::push_format(
1496									&mut output,
1497									format_args!(
1498										"{{\"binding\": {}, \"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1499										write.binding,
1500										write.domain.token(),
1501										write.partition.token(),
1502										write.extent.token(),
1503										write.collision.token(),
1504										write.tail.token(),
1505									),
1506								);
1507							}
1508							output.push_str("], \"uniform_store\": ");
1509							match contract.uniform_store {
1510								None => output.push_str("null"),
1511								Some(proof) => crate::core::push_format(
1512									&mut output,
1513									format_args!(
1514										"{{\"domain\": \"{}\", \"partition\": \"{}\", \"extent\": \"{}\", \"collision\": \"{}\", \"tail\": \"{}\"}}",
1515										proof.domain.token(),
1516										proof.partition.token(),
1517										proof.extent.token(),
1518										proof.collision.token(),
1519										proof.tail.token(),
1520									),
1521								),
1522							}
1523							crate::core::push_format(
1524								&mut output,
1525								format_args!(", \"workspace\": \"{}\"}}", contract.workspace.token()),
1526							);
1527						}
1528					}
1529					crate::core::push_format(
1530						&mut output,
1531						format_args!(
1532							", \"groups\": [{}, {}, {}], \"queue\": \"{}\", \"family\": {}, \"indirect\": {}",
1533							node.workgroups[0],
1534							node.workgroups[1],
1535							node.workgroups[2],
1536							graph_node.queue().name(),
1537							self.graph.node_families()[index],
1538							node.indirect.is_some()
1539						),
1540					);
1541				}
1542				GraphNode::BufferCopy(copy) => {
1543					output.push_str(
1544						r#"], "kind": "buffer_copy", "implementation_id": "0x4255465f434f5059", "operation_contract_hash": "#,
1545					);
1546					push_optional_hex(&mut output, contract);
1547					crate::core::push_format(
1548						&mut output,
1549						format_args!(
1550							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": {}"#,
1551							graph_node.queue().name(),
1552							self.graph.node_families()[index],
1553							copy.bytes,
1554						),
1555					);
1556				}
1557				GraphNode::VideoDecode(video) => {
1558					crate::core::push_format(
1559						&mut output,
1560						format_args!(
1561							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": ["#,
1562							graph_node.queue().name(),
1563							self.graph.node_families()[index],
1564						),
1565					);
1566					for (index, word) in video.descriptor_words().into_iter().enumerate() {
1567						if index != 0 {
1568							output.push_str(", ");
1569						}
1570						crate::core::push_format(&mut output, format_args!("{word}"));
1571					}
1572					output.push(']');
1573				}
1574
1575				GraphNode::VideoEncode(video) => {
1576					crate::core::push_format(
1577						&mut output,
1578						format_args!(
1579							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": ["#,
1580							graph_node.queue().name(),
1581							self.graph.node_families()[index],
1582						),
1583					);
1584					for (index, word) in video.descriptor_words().into_iter().enumerate() {
1585						if index != 0 {
1586							output.push_str(", ");
1587						}
1588						crate::core::push_format(&mut output, format_args!("{word}"));
1589					}
1590					output.push(']');
1591				}
1592				GraphNode::VideoEncodeInput(video) => {
1593					crate::core::push_format(
1594						&mut output,
1595						format_args!(
1596							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": ["#,
1597							video.copy.name(),
1598							graph_node.queue().name(),
1599							self.graph.node_families()[index],
1600						),
1601					);
1602					for (index, word) in video.copy.descriptor_words().enumerate() {
1603						if index != 0 {
1604							output.push_str(", ");
1605						}
1606						crate::core::push_format(&mut output, format_args!("{word}"));
1607					}
1608					output.push(']');
1609				}
1610				GraphNode::VideoPlanes(video) => {
1611					crate::core::push_format(
1612						&mut output,
1613						format_args!(
1614							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": ["#,
1615							video.phase.name(),
1616							graph_node.queue().name(),
1617							self.graph.node_families()[index],
1618						),
1619					);
1620					for (index, word) in video.copy.descriptor_words().enumerate() {
1621						if index != 0 {
1622							output.push_str(", ");
1623						}
1624						crate::core::push_format(&mut output, format_args!("{word}"));
1625					}
1626					output.push(']');
1627				}
1628			}
1629			output.push_str(r#", "effects": ["#);
1630			for (effect_index, effect) in graph_node.buffers().iter().enumerate() {
1631				if effect_index != 0 {
1632					output.push_str(", ");
1633				}
1634				let resource = graph_resource_id(&lifetimes, &effect.buffer)
1635					.expect("node buffer must have a resource lifetime");
1636				crate::core::push_format(
1637					&mut output,
1638					format_args!(
1639						"{{\"resource\": {resource}, \"access\": \"{}\"}}",
1640						buffer_access_token(effect.access)
1641					),
1642				);
1643			}
1644			output.push_str("]}");
1645		}
1646		if !self.graph.nodes().is_empty() {
1647			output.push('\n');
1648		}
1649		output.push_str("  ]\n}\n");
1650		output
1651	}
1652
1653	pub(super) fn belongs_to(&self, runtime: &RuntimeHandle) -> bool {
1654		self.runtime.same_as(runtime)
1655	}
1656
1657	pub(crate) fn validate_training_replay_safety(&self) -> Result<()> {
1658		self.graph.validate_training_replay_safety()
1659	}
1660
1661	fn binding_key(&self) -> Vec<u32> {
1662		self
1663			.input_bindings
1664			.iter()
1665			.map(|binding| binding.current.descriptor_index())
1666			.collect()
1667	}
1668
1669	/// Node ranges of the executable graph that each fit the device's
1670	/// estimated submission budget. Splitting is per queue run — every
1671	/// emitted range resolves to one queue family. A single returned range
1672	/// keeps the one-buffer fast path; several ranges become sequential
1673	/// timeline submissions at node boundaries. A node whose own estimate
1674	/// exceeds the budget declines here, before anything records or
1675	/// submits.
1676	pub(super) fn submission_ranges(
1677		&self,
1678		device: &Arc<Device>,
1679	) -> Result<Vec<std::ops::Range<usize>>> {
1680		let budget = device.submission_budget_ns();
1681		let mut ranges = Vec::new();
1682		for run in self.graph.queue_runs() {
1683			for range in
1684				self
1685					.graph
1686					.budget_ranges_within(run.nodes, budget)
1687					.map_err(|(index, estimate)| {
1688						Error::resource_exhausted(format!(
1689							"node {} ({}) estimated {:.1}ms exceeds the {:.1}ms submission budget",
1690							index,
1691							self.graph.nodes()[index].semantic().0,
1692							estimate as f64 / 1e6,
1693							budget as f64 / 1e6,
1694						))
1695					})? {
1696				if !range.is_empty() {
1697					ranges.push(range);
1698				}
1699			}
1700		}
1701		Ok(ranges)
1702	}
1703
1704	pub(super) fn graph(&self) -> &ExecutableGraph {
1705		&self.graph
1706	}
1707
1708	/// One reusable command buffer per queue run, in submission order.
1709	/// A single-run graph returns one command; a mixed-family graph
1710	/// returns one command per run for the timeline-chained batch.
1711	pub(super) fn reusable_commands(
1712		&self,
1713		device: &Arc<Device>,
1714	) -> Result<Vec<RecordedCommandBuffer>> {
1715		let key = self.binding_key();
1716		if let Some((_, commands)) = self
1717			.cached_commands
1718			.borrow()
1719			.iter()
1720			.find(|(cached_key, _)| *cached_key == key)
1721		{
1722			increment(&self.counters.command_cache_hits);
1723			return Ok(
1724				commands
1725					.iter()
1726					.map(|command| command.submission())
1727					.collect(),
1728			);
1729		}
1730		let runs = self.graph.queue_runs();
1731		let commands = if runs.len() == 1 {
1732			vec![device.record_reusable_compute_graph(&self.graph)?]
1733		} else {
1734			runs
1735				.into_iter()
1736				.map(|run| device.record_reusable_graph_range(&self.graph, run.nodes))
1737				.collect::<Result<Vec<_>>>()?
1738		};
1739		increment(&self.counters.command_recordings);
1740		let submissions = commands
1741			.iter()
1742			.map(|command| command.submission())
1743			.collect();
1744		let mut cache = self.cached_commands.borrow_mut();
1745		if cache.len() == MAX_CACHED_BINDING_COMMANDS {
1746			cache.remove(0);
1747		}
1748		cache.push((key, commands));
1749		Ok(submissions)
1750	}
1751
1752	pub(super) fn count_command_recording(&self) {
1753		increment(&self.counters.command_recordings);
1754	}
1755
1756	pub(super) fn precompile(&self, device: &Arc<Device>) -> Result<()> {
1757		if self.graph.has_video() {
1758			let mut commands = super::device::logical::command::RecordedBatch::new(device);
1759			for range in self.submission_ranges(device)? {
1760				commands.push(device.record_fresh_graph_range(&self.graph, range, false)?);
1761			}
1762		} else {
1763			let _ = self.reusable_commands(device)?;
1764		}
1765		Ok(())
1766	}
1767
1768	pub(super) fn mark_submitted(&self, event: &Event) {
1769		for output in &self.outputs {
1770			output.mark_submitted(event.clone());
1771		}
1772		for binding in &self.input_bindings {
1773			if let Some(slot) = binding
1774				.staging
1775				.iter()
1776				.find(|slot| slot.buffer.same_as(&binding.current))
1777			{
1778				slot.consumer.replace(Some(event.clone()));
1779			}
1780			binding.current.record_bound_consumer(event);
1781		}
1782		self.last_submission.replace(Some(event.clone()));
1783		increment(&self.counters.submissions);
1784	}
1785
1786	pub(super) fn mark_failed(&self) {
1787		for output in &self.outputs {
1788			output.mark_failed();
1789		}
1790	}
1791}
1792
1793fn increment(counter: &Cell<u64>) {
1794	counter.set(counter.get().saturating_add(1));
1795}
1796
1797fn graph_resource_id(
1798	lifetimes: &[super::graph::executable::ResourceLifetime],
1799	buffer: &Buffer,
1800) -> Option<usize> {
1801	lifetimes
1802		.iter()
1803		.position(|lifetime| lifetime.buffer.same_as(buffer))
1804}
1805
1806const fn hazard_reason(source: AccessState, destination: AccessState) -> &'static str {
1807	match (source.writes(), destination.writes()) {
1808		(true, true) => "write_after_write",
1809		(true, false) => "read_after_write",
1810		(false, true) => "write_after_read",
1811		(false, false) => "queue_ownership",
1812	}
1813}
1814
1815fn push_stage_names(output: &mut String, access: AccessState) {
1816	let mask = access.vk_stages();
1817	push_names(
1818		output,
1819		[
1820			(
1821				mask.contains(vk::PipelineStageFlagBits2::COMPUTE_SHADER_BIT),
1822				"compute_shader",
1823			),
1824			(
1825				mask.contains(vk::PipelineStageFlagBits2::DRAW_INDIRECT_BIT),
1826				"draw_indirect",
1827			),
1828			(mask.contains(vk::PipelineStageFlagBits2::COPY_BIT), "copy"),
1829		],
1830	);
1831}
1832
1833fn push_access_names(output: &mut String, access: AccessState) {
1834	let mask = access.vk_access();
1835	push_names(
1836		output,
1837		[
1838			(
1839				mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_READ_BIT),
1840				"shader_storage_read",
1841			),
1842			(
1843				mask.contains(vk::AccessFlagBits2::SHADER_STORAGE_WRITE_BIT),
1844				"shader_storage_write",
1845			),
1846			(
1847				mask.contains(vk::AccessFlagBits2::INDIRECT_COMMAND_READ_BIT),
1848				"indirect_command_read",
1849			),
1850			(
1851				mask.contains(vk::AccessFlagBits2::TRANSFER_READ_BIT),
1852				"transfer_read",
1853			),
1854			(
1855				mask.contains(vk::AccessFlagBits2::TRANSFER_WRITE_BIT),
1856				"transfer_write",
1857			),
1858		],
1859	);
1860}
1861
1862fn push_names(output: &mut String, names: impl IntoIterator<Item = (bool, &'static str)>) {
1863	let mut separator = "";
1864	for (_, name) in names.into_iter().filter(|(present, _)| *present) {
1865		output.push_str(separator);
1866		crate::core::push_json_string(output, name);
1867		separator = ", ";
1868	}
1869}
1870
1871const fn buffer_access_token(access: super::BufferAccess) -> &'static str {
1872	match access {
1873		super::BufferAccess::Read => "read",
1874		super::BufferAccess::Write => "write",
1875		super::BufferAccess::ReadWrite => "read_write",
1876	}
1877}
1878
1879fn push_optional_hex(output: &mut String, value: u64) {
1880	if value == 0 {
1881		output.push_str("null");
1882	} else {
1883		crate::core::push_format(output, format_args!("\"0x{value:016x}\""));
1884	}
1885}
1886
1887fn find_resource(
1888	lifetimes: &[super::graph::executable::ResourceLifetime],
1889	storage: &Storage,
1890) -> Result<usize> {
1891	let buffer = storage.buffer().ok_or_else(|| {
1892		Error::failed_precondition("captured semantic resource has no allocated storage")
1893	})?;
1894	lifetimes
1895		.iter()
1896		.position(|lifetime| lifetime.buffer.same_as(buffer))
1897		.ok_or_else(|| Error::failed_precondition("captured resource does not appear in the graph"))
1898}
1899
1900fn find_resource_storage<'a>(
1901	buffer: &Buffer,
1902	stable_resources: &'a [StableResourceSnapshot],
1903	semantic_storage: &'a [SemanticStorageSnapshot],
1904	observed_outputs: &'a [Storage],
1905	outputs: &'a [Storage],
1906) -> Option<&'a Storage> {
1907	// A lowering may create an immutable physical parameter buffer that is not a
1908	// semantic value or public output. The executable graph's Buffer retains
1909	// that allocation; absence here only means there is no Matrix-level owner to
1910	// count or consider for transient aliasing.
1911	stable_resources
1912		.iter()
1913		.map(|candidate| &candidate.storage)
1914		.chain(semantic_storage.iter().map(|candidate| &candidate.storage))
1915		.chain(observed_outputs.iter())
1916		.chain(outputs.iter())
1917		.find(|storage| {
1918			storage
1919				.buffer()
1920				.is_some_and(|candidate| candidate.same_as(buffer))
1921		})
1922}
1923
1924struct AliasGroup {
1925	resources: Vec<usize>,
1926	required_size: usize,
1927}
1928
1929struct AliasMaterialization {
1930	graph: ExecutableGraph,
1931	outputs: Vec<Storage>,
1932	captured_resources: Vec<CapturedResourceDesc>,
1933	retired: Vec<Buffer>,
1934	savings: usize,
1935}
1936
1937fn materialize_aliases(
1938	runtime: &RuntimeHandle,
1939	graph: &ExecutableGraph,
1940	outputs: &[Storage],
1941	resource_lifetimes: &[super::graph::executable::ResourceLifetime],
1942	captured_resources: &[CapturedResourceDesc],
1943) -> Result<AliasMaterialization> {
1944	let mut graph = graph.clone();
1945	let mut outputs = outputs.to_vec();
1946	let mut captured_resources = captured_resources.to_vec();
1947	let groups = alias_groups(&captured_resources);
1948	let mut replacements = Vec::new();
1949	let mut retired = Vec::new();
1950	let mut savings = 0_usize;
1951	for group in groups.iter().filter(|group| group.resources.len() > 1) {
1952		let arena = runtime.create_alias_arena(group.required_size)?;
1953		let original_bytes = group.resources.iter().try_fold(0_usize, |sum, resource| {
1954			sum
1955				.checked_add(captured_resources[*resource].byte_len)
1956				.ok_or_else(|| Error::resource_exhausted("materialized alias byte accounting overflowed"))
1957		})?;
1958		savings = savings
1959			.checked_add(original_bytes.saturating_sub(group.required_size))
1960			.ok_or_else(|| Error::resource_exhausted("alias savings accounting overflowed"))?;
1961		for resource in &group.resources {
1962			let source = resource_lifetimes[*resource].buffer.clone();
1963			retired.push(source.clone());
1964			replacements.push((source, arena.clone()));
1965			captured_resources[*resource].alias_materialized = true;
1966		}
1967	}
1968	if !replacements.is_empty() {
1969		graph.materialize_alias_replacements(&replacements)?;
1970		outputs.retain(|storage| {
1971			storage
1972				.buffer()
1973				.is_none_or(|buffer| !retired.iter().any(|candidate| candidate.same_as(buffer)))
1974		});
1975	}
1976	Ok(AliasMaterialization {
1977		graph,
1978		outputs,
1979		captured_resources,
1980		retired,
1981		savings,
1982	})
1983}
1984
1985fn alias_groups(resources: &[CapturedResourceDesc]) -> Vec<AliasGroup> {
1986	let mut eligible = resources
1987		.iter()
1988		.enumerate()
1989		.filter_map(|(index, resource)| resource.alias_candidate.then_some(index))
1990		.collect::<Vec<_>>();
1991	eligible.sort_by_key(|index| (resources[*index].first_access, resources[*index].resource));
1992	let mut groups = Vec::<AliasGroup>::new();
1993	for resource in eligible {
1994		let desc = resources[resource];
1995		if let Some(group) = groups.iter_mut().find(|group| {
1996			group.resources.iter().all(|member| {
1997				let member = resources[*member];
1998				desc.first_access > member.last_access || desc.last_access < member.first_access
1999			})
2000		}) {
2001			group.required_size = group.required_size.max(desc.byte_len);
2002			group.resources.push(resource);
2003		} else {
2004			groups.push(AliasGroup {
2005				resources: vec![resource],
2006				required_size: desc.byte_len,
2007			});
2008		}
2009	}
2010	groups
2011}
2012
2013fn alias_analysis(resources: &[CapturedResourceDesc]) -> (usize, usize) {
2014	let groups = alias_groups(resources);
2015	let mut count = 0_usize;
2016	let mut savings = 0_usize;
2017	for group in groups.iter().filter(|group| group.resources.len() > 1) {
2018		count = count.saturating_add(1);
2019		let bytes = group.resources.iter().fold(0_usize, |total, resource| {
2020			total.saturating_add(resources[*resource].byte_len)
2021		});
2022		savings = savings.saturating_add(bytes.saturating_sub(group.required_size));
2023	}
2024	(count, savings)
2025}
2026
2027impl fmt::Debug for ExecutionPlan {
2028	fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2029		formatter
2030			.debug_struct("ExecutionPlan")
2031			.field("graph_id", &format_args!("{:016x}", self.graph_id))
2032			.field("node_count", &self.graph.nodes().len())
2033			.finish_non_exhaustive()
2034	}
2035}
2036
2037#[cfg(test)]
2038#[path = "../../../../test/rs/runtime/plan_binding_unit.rs"]
2039mod tests;