Skip to main content

oa/runtime/
runtime.rs

1mod pqc;
2
3use std::sync::Arc;
4
5use std::{cell::RefCell, marker::PhantomData, rc::Rc};
6
7use crate::{Error, LogComponent, LogLevel, LogOptions, Matrix, Result};
8
9use super::{
10	AudioSemanticDispatch, Buffer, BufferBinding, ClockCalibration, ComputeDispatch, DecodeSession,
11	DeferredRetirement, Device, DevicePhysical, EncodeSession, Event, ExecutionPlan,
12	GraphicsPipeline, ImageSemanticDispatch, Instance, MeshBuffer, NativeRgbaImage,
13	OptionalSemanticDispatch, PresentationSurface, PushConstant, QuantSemanticDispatch,
14	RecordedCommandBuffer, RenderTarget, RetirementService, RetirementTicket, SceneDrawCmd,
15	SecretBinding, SecretBuffer, SecretErasure, SemanticDispatch, Storage, SurfaceDescriptorArena,
16	SurfaceDescriptorLayouts, Timer, UnlitDescriptorArena, UnlitDescriptorLayouts,
17	device::logical::command::RecordedBatch,
18	log::{LogSelection, Logger},
19	session::{ExecutionSession, RecordedDecodeStep, RecordedEncodeStep},
20};
21pub use crate::runtime::types::RuntimeRequirements;
22
23/// Policy for selecting the local device owned by an runtime.
24#[non_exhaustive]
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
26pub enum DeviceSelection {
27	/// Select a compatible hardware device by queried resource capacity.
28	#[default]
29	Automatic,
30	/// Select an exact physical-device ordinal, including software Vulkan CPU.
31	/// Use [`Runtime::available_devices`] to discover current ordinals.
32	Index(usize),
33}
34
35impl RuntimeRequirements {
36	/// Require a graphics-capable queue family.
37	pub fn graphics(mut self) -> Self {
38		self.graphics = true;
39		self
40	}
41
42	/// Require graphics and swapchain readiness.
43	///
44	/// The builder must also receive the window's required instance extensions.
45	pub fn presentation(mut self) -> Self {
46		self.graphics = true;
47		self.presentation = true;
48		self
49	}
50
51	/// Require support for one exact Vulkan Video decode profile.
52	pub fn video_decode(mut self, profile: crate::video::VideoDecodeProfile) -> Self {
53		if !self.video_decode.contains(&profile) {
54			self.video_decode.push(profile);
55		}
56		self
57	}
58
59	/// Require device support for one exact Vulkan Video encode profile.
60	///
61	/// This checks Vulkan capability only. OA encoder-session readiness is a
62	/// separate runtime capability.
63	pub fn video_encode(mut self, profile: crate::video::VideoEncodeProfile) -> Self {
64		if !self.video_encode.contains(&profile) {
65			self.video_encode.push(profile);
66		}
67		self
68	}
69}
70
71/// Configuration used to construct one OA execution runtime.
72#[derive(Clone, Debug, Default)]
73#[must_use]
74pub struct RuntimeBuilder {
75	device_selection: DeviceSelection,
76	requirements: RuntimeRequirements,
77	log_options: LogOptions,
78	instance_extensions: Vec<String>,
79}
80
81impl RuntimeBuilder {
82	/// Create a builder using automatic hardware-device selection.
83	pub fn new() -> Self {
84		Self {
85			device_selection: DeviceSelection::Automatic,
86			requirements: RuntimeRequirements::default(),
87			log_options: LogOptions::new(),
88			instance_extensions: Vec::new(),
89		}
90	}
91
92	/// Require optional device services during physical-device admission.
93	pub fn requirements(mut self, requirements: RuntimeRequirements) -> Self {
94		self.requirements = requirements;
95		self
96	}
97
98	/// Select how this runtime chooses its single local device.
99	pub const fn devices(mut self, selection: DeviceSelection) -> Self {
100		self.device_selection = selection;
101		self
102	}
103
104	/// Configure the logging session owned by the constructed runtime.
105	pub fn logging(mut self, options: LogOptions) -> Self {
106		self.log_options = options;
107		self
108	}
109
110	/// Require caller-selected Vulkan instance extensions.
111	///
112	/// This is the explicit construction seam required by a future WSI Presenter.
113	/// Headless callers leave it empty. Extension names are validated before the
114	/// Vulkan instance is created; no raw instance handle crosses this boundary.
115	pub fn instance_extensions(
116		mut self,
117		extensions: impl IntoIterator<Item = impl Into<String>>,
118	) -> Self {
119		self.instance_extensions = extensions.into_iter().map(Into::into).collect();
120		self
121	}
122
123	/// Construct the configured runtime and its execution services.
124	///
125	/// # Errors
126	///
127	/// Returns an error when the backend cannot be loaded, its required API is
128	/// unavailable, the requested device does not exist or lacks OA's required
129	/// capabilities, logging configuration or file creation fails, or a device
130	/// service cannot be constructed.
131	pub fn build(self) -> Result<Runtime> {
132		Runtime::build(
133			self.device_selection,
134			self.requirements,
135			self.log_options,
136			self.instance_extensions,
137		)
138	}
139}
140
141/// Sole owner of OA's local execution services.
142///
143/// The current one-device recorder is thread-affine. `Runtime` intentionally
144/// remains neither `Send` nor `Sync` until concurrent queue scheduling and
145/// submission synchronization are implemented and verified.
146///
147/// Clones share the execution handle and persistence guard: `.vkcache`
148/// persistence runs once, when the last `Runtime` clone drops, never per
149/// temporary handle. A clone does not own the log-selection restore that the
150/// constructing runtime performs on drop.
151pub struct Runtime {
152	// Restore thread-local selection before closing the logger and releasing the
153	// execution handle. Rust drops fields in declaration order.
154	_log_selection: LogSelection,
155	logger: Logger,
156	handle: RuntimeHandle,
157	persistence: Rc<RuntimePersistence>,
158	_not_send_sync: PhantomData<Rc<()>>,
159}
160
161impl Clone for Runtime {
162	fn clone(&self) -> Self {
163		Self {
164			_log_selection: self._log_selection.detached(),
165			logger: self.logger.clone(),
166			handle: self.handle.clone(),
167			persistence: self.persistence.clone(),
168			_not_send_sync: PhantomData,
169		}
170	}
171}
172
173/// One-shot `.vkcache` persistence owner shared by every `Runtime` clone of one
174/// runtime. Dropping the last clone fires the single snapshot write, matching
175/// the lifetime semantics the runtime had before it became cloneable.
176struct RuntimePersistence {
177	handle: RuntimeHandle,
178}
179
180thread_local! {
181	static DEFAULT_RUNTIME: RefCell<Option<Runtime>> = const { RefCell::new(None) };
182}
183
184pub(crate) enum CaptureAttempt<T> {
185	Captured { plan: Box<ExecutionPlan>, output: T },
186	Rejected { error: Error, output: T },
187}
188
189/// Runtime-owned implementation for public hardware video decoder sessions.
190pub(crate) struct VideoDecoderBackend {
191	runtime: RuntimeHandle,
192	session: Arc<DecodeSession>,
193	recording: Option<Vec<RecordedDecodeStep>>,
194	av1_ready: Vec<Option<Event>>,
195	av1_host_frames: Vec<Option<crate::video::VideoHostPlanes>>,
196	vp9_ready: Vec<Option<Event>>,
197	vp9_host_frames: Vec<Option<crate::video::VideoHostPlanes>>,
198}
199
200impl VideoDecoderBackend {
201	pub(crate) fn create(
202		runtime: &Runtime,
203		profile: crate::video::VideoDecodeProfile,
204		coded_extent: crate::video::VideoExtent,
205	) -> Result<Self> {
206		Self::create_on_handle(&runtime.handle, profile, coded_extent)
207	}
208
209	fn create_on_handle(
210		runtime: &RuntimeHandle,
211		profile: crate::video::VideoDecodeProfile,
212		coded_extent: crate::video::VideoExtent,
213	) -> Result<Self> {
214		let device = runtime.state.borrow().device.clone();
215		let capabilities = device.video_decode_capabilities(profile)?;
216		let device_capabilities = device.video_device_capabilities()?;
217		if !device_capabilities.supports_decode_result_status_queries() {
218			return Err(Error::missing_capability(
219				"the public decoder requires Vulkan Video result-status queries",
220			));
221		}
222		let max_dpb_slots = if matches!(profile, crate::video::VideoDecodeProfile::H264 { .. }) {
223			capabilities.max_dpb_slots().min(16)
224		} else {
225			capabilities.max_dpb_slots()
226		};
227		let max_active_references = capabilities
228			.max_active_reference_pictures()
229			.min(max_dpb_slots);
230		let session = device.create_video_decode_session(
231			profile,
232			coded_extent,
233			max_dpb_slots,
234			max_active_references,
235		)?;
236		Ok(Self {
237			runtime: runtime.clone(),
238			session: Arc::new(session),
239			recording: None,
240			av1_ready: vec![None; max_dpb_slots as usize],
241			av1_host_frames: vec![None; max_dpb_slots as usize],
242			vp9_ready: vec![None; max_dpb_slots as usize],
243			vp9_host_frames: vec![None; max_dpb_slots as usize],
244		})
245	}
246
247	pub(crate) fn require_decode_submission(&self) -> Result<()> {
248		if self.recording.is_none() {
249			require_immediate_batch(&self.runtime.state.borrow())?;
250		}
251		self.session.validate_ownership()
252	}
253
254	fn queue_device(&self) -> Result<Arc<Device>> {
255		let state = self.runtime.state.borrow();
256		require_immediate_batch(&state)?;
257		Ok(state.device.clone())
258	}
259
260	fn submit_native_batch(
261		&self,
262		frame: &crate::runtime::NativeDecodedFrame,
263		commands: RecordedBatch,
264	) -> Result<Event> {
265		let mut state = self.runtime.state.borrow_mut();
266		let start = state.next_epoch;
267		match submit_recorded_batch(&mut state, commands, false) {
268			Ok(event) => {
269				frame.mark_consumed(&event)?;
270				Ok(event)
271			}
272			Err(error) => {
273				if state.next_epoch != start {
274					// At least one ownership command may have executed without
275					// its matching return. Do not reuse the decoder's DPB.
276					frame.invalidate_ownership();
277				}
278				Err(error)
279			}
280		}
281	}
282
283	fn session_mut(&mut self) -> Result<&mut DecodeSession> {
284		self.session.validate_ownership()?;
285		Arc::get_mut(&mut self.session)
286			.ok_or_else(|| Error::failed_precondition("video decode session still has pending commands"))
287	}
288
289	fn complete_decode(&self, submitted: Result<Event>) -> Result<Event> {
290		let event = submitted.and_then(|event| {
291			event.wait()?;
292			Ok(event)
293		});
294		let event = event.inspect_err(|_| self.session.invalidate_ownership())?;
295		self
296			.session
297			.verify_decode_result()
298			.inspect_err(|_| self.session.invalidate_ownership())?;
299		Ok(event)
300	}
301
302	fn read_decoded_picture(
303		&mut self,
304		device: &Arc<Device>,
305		decode: RecordedCommandBuffer,
306	) -> Result<(crate::video::VideoHostPlanes, Event)> {
307		let mut commands = RecordedBatch::new(device);
308		commands.push(decode);
309		// Recording already advanced the decoder's tracked state. A
310		// discarded producer cannot be followed by another decode.
311		let copy = self
312			.session_mut()?
313			.record_decode_readback(device)
314			.inspect_err(|_| self.session.invalidate_ownership())?;
315		commands.push(copy);
316		commands.retain(self.session.clone());
317		let submitted = submit_recorded_batch(&mut self.runtime.state.borrow_mut(), commands, false);
318		let completion = self.complete_decode(submitted)?;
319		Ok((self.session.read_decode_yuv420()?, completion))
320	}
321
322	fn complete_native_picture(&self, mut command: RecordedCommandBuffer) -> Result<Event> {
323		command.retain(self.session.clone());
324		let submitted = submit_recorded(&mut self.runtime.state.borrow_mut(), command);
325		self.complete_decode(submitted)
326	}
327
328	pub(crate) fn set_h264_parameters(
329		&mut self,
330		sps: &crate::video::H264SequenceParameterSet,
331		pps: &crate::video::H264PictureParameterSet,
332	) -> Result<()> {
333		let coded_extent = crate::video::VideoExtent {
334			width: sps.coded_width()?,
335			height: sps.coded_height()?,
336		};
337		self.configure_coded_extent(coded_extent, |session| {
338			session.set_h264_parameters(sps, pps)
339		})
340	}
341
342	fn configure_coded_extent(
343		&mut self,
344		coded_extent: crate::video::VideoExtent,
345		configure: impl FnOnce(&mut DecodeSession) -> Result<()>,
346	) -> Result<()> {
347		if self.session.decode_extent() == coded_extent {
348			return configure(self.session_mut()?);
349		}
350		let mut replacement =
351			Self::create_on_handle(&self.runtime, self.session.decode_profile(), coded_extent)?;
352		configure(replacement.session_mut()?)?;
353		replacement.recording = self.recording.take();
354		*self = replacement;
355		Ok(())
356	}
357
358	pub(crate) fn restart_h265(&mut self) -> Result<()> {
359		self.session_mut()?.restart_h265();
360		Ok(())
361	}
362
363	pub(crate) fn set_h265_parameters(
364		&mut self,
365		vps: &crate::video::H265VideoParameterSet,
366		sps: &crate::video::H265SequenceParameterSet,
367		pps: &crate::video::H265PictureParameterSet,
368	) -> Result<()> {
369		let coded_extent = crate::video::VideoExtent {
370			width: sps.coded_width,
371			height: sps.coded_height,
372		};
373		self.configure_coded_extent(coded_extent, |session| {
374			session.set_h265_parameters(vps, sps, pps)
375		})
376	}
377
378	pub(crate) fn set_av1_parameters(
379		&mut self,
380		sequence: &crate::video::Av1SequenceHeader,
381	) -> Result<()> {
382		self.session_mut()?.set_av1_parameters(sequence)
383	}
384
385	pub(crate) fn decode_h264(
386		&mut self,
387		coded_slice: &[u8],
388		sps: &crate::video::H264SequenceParameterSet,
389		pps: &crate::video::H264PictureParameterSet,
390		slice: &crate::video::H264SliceHeader,
391	) -> Result<crate::video::VideoHostPlanes> {
392		let device = self.queue_device()?;
393		self.session_mut()?.upload_bitstream(coded_slice)?;
394		let command = self
395			.session_mut()?
396			.record_h264_picture_for_readback(&device, sps, pps, slice)?;
397		Ok(self.read_decoded_picture(&device, command)?.0)
398	}
399
400	pub(crate) fn begin_decode_capture(&self) -> Result<Self> {
401		let state = self.runtime.state.borrow();
402		if !state.capture_active || state.secret_scope.is_some() {
403			return Err(Error::failed_precondition(
404				"recorded video decode requires an active Runtime capture",
405			));
406		}
407		drop(state);
408		self.session.require_capture_support()?;
409		let mut backend = Self::create_on_handle(
410			&self.runtime,
411			self.session.decode_profile(),
412			self.session.decode_extent(),
413		)?;
414		backend.recording = Some(Vec::new());
415		Ok(backend)
416	}
417
418	pub(crate) fn finish_decode_capture(mut self) -> Result<()> {
419		let steps = self
420			.recording
421			.take()
422			.ok_or_else(|| Error::internal("video decode capture has no recording"))?;
423		let mut state = self.runtime.state.borrow_mut();
424		let device = state.device.clone();
425		state
426			.session
427			.record_video_decode(&device, &self.session, steps)
428	}
429
430	fn append_decode_step(&mut self, step: RecordedDecodeStep) -> Result<()> {
431		self
432			.recording
433			.as_mut()
434			.ok_or_else(|| Error::internal("video decode capture has no recording"))?
435			.push(step);
436		Ok(())
437	}
438
439	fn record_coded_picture(
440		&mut self,
441		prepare: impl FnOnce(
442			&mut DecodeSession,
443		) -> Result<(super::device::logical::video::PreparedDecode, u32)>,
444	) -> Result<u32> {
445		let (picture, slot) = prepare(self.session_mut()?)?;
446		self.append_decode_step(RecordedDecodeStep::Picture(picture))?;
447		Ok(slot)
448	}
449
450	fn record_planes(&mut self, slot: u32) -> Result<crate::video::DevicePlanar> {
451		let copy = self.session.retain_replay_planes(slot)?;
452		let extent = copy.extent();
453		let planes =
454			self.allocate_decoded_planes(copy.format(), extent.width as usize, extent.height as usize)?;
455		self.append_decode_step(RecordedDecodeStep::Planes(Arc::new(copy), planes.clone()))?;
456		Ok(planes)
457	}
458
459	pub(crate) fn record_h264_picture(
460		&mut self,
461		coded_slice: &[u8],
462		sps: &crate::video::H264SequenceParameterSet,
463		pps: &crate::video::H264PictureParameterSet,
464		slice: &crate::video::H264SliceHeader,
465	) -> Result<crate::video::DevicePlanar> {
466		let slot = self
467			.record_coded_picture(|session| session.prepare_h264_picture(coded_slice, sps, pps, slice))?;
468		self.record_planes(slot)
469	}
470
471	pub(crate) fn record_h265_picture(
472		&mut self,
473		coded_slice: &[u8],
474		sps: &crate::video::H265SequenceParameterSet,
475		pps: &crate::video::H265PictureParameterSet,
476		slice: &crate::video::H265SliceHeader,
477	) -> Result<crate::video::DevicePlanar> {
478		let slot = self
479			.record_coded_picture(|session| session.prepare_h265_picture(coded_slice, sps, pps, slice))?;
480		self.record_planes(slot)
481	}
482
483	pub(crate) fn record_av1_picture(
484		&mut self,
485		data: &[u8],
486		picture: &crate::video::Av1Picture,
487	) -> Result<Option<crate::video::DevicePlanar>> {
488		let frame = &picture.frame;
489		if frame.show_existing_frame {
490			let slot = self.session_mut()?.resolve_av1_show_existing_slot(frame)?;
491			return self.record_planes(slot).map(Some);
492		}
493		let slot = self.record_coded_picture(|session| session.prepare_av1_picture(data, picture))?;
494		frame
495			.show_frame
496			.then(|| self.record_planes(slot))
497			.transpose()
498	}
499
500	pub(crate) fn record_vp9_picture(
501		&mut self,
502		data: &[u8],
503		picture: &crate::video::Vp9Picture,
504	) -> Result<Option<crate::video::DevicePlanar>> {
505		if picture.show_existing_frame {
506			let slot = self
507				.session_mut()?
508				.resolve_vp9_show_existing_slot(picture)?;
509			return self.record_planes(slot).map(Some);
510		}
511		let slot = self.record_coded_picture(|session| session.prepare_vp9_picture(data, picture))?;
512		picture
513			.show_frame
514			.then(|| self.record_planes(slot))
515			.transpose()
516	}
517
518	pub(crate) fn allocate_decoded_planes(
519		&self,
520		format: crate::video::VideoPixelFormat,
521		width: usize,
522		height: usize,
523	) -> Result<crate::video::DevicePlanar> {
524		let planes = crate::video::plane_extents(format, width, height)?
525			.into_iter()
526			.map(|plane| {
527				let count = plane
528					.width
529					.checked_mul(plane.height)
530					.ok_or_else(|| Error::out_of_range("decoded plane size overflows usize"))?;
531				Matrix::allocate(
532					&self.runtime,
533					vec![plane.height, plane.width],
534					count,
535					crate::DType::U8,
536				)
537			})
538			.collect::<Result<Vec<_>>>()?;
539		Ok(crate::video::DevicePlanar {
540			planes: Rc::new(planes),
541			format,
542			width,
543			height,
544		})
545	}
546
547	pub(crate) fn stage_native_planes(
548		&self,
549		frame: &crate::runtime::NativeDecodedFrame,
550		planes: &[Matrix],
551	) -> Result<()> {
552		let copy = Arc::new(self.session.retain_plane_copy(frame)?);
553		let mut state = self.runtime.state.borrow_mut();
554		if state.secret_scope.is_some() {
555			return Err(Error::failed_precondition(
556				"video staging cannot enter secret lowering",
557			));
558		}
559		let device = state.device.clone();
560		state.session.record_video_planes(&device, copy, planes)
561	}
562
563	pub(crate) fn stage_native_canvas_planes(
564		&mut self,
565		frame: &crate::runtime::NativeDecodedFrame,
566	) -> Result<(crate::runtime::Storage, crate::video::CanvasYuvLayout)> {
567		let device = self.queue_device()?;
568		if device.physical().graphics_queue_family != Some(device.physical().compute_queue_family) {
569			return Err(Error::missing_capability(
570				"video canvas requires a unified graphics and compute queue",
571			));
572		}
573		let crate::runtime::device::logical::video::NativeCanvasTransfer {
574			commands,
575			planes,
576			layout,
577		} = self
578			.session
579			.record_native_plane_transfer(&device, frame, true)?;
580		let completion = self.submit_native_batch(frame, commands)?;
581		let storage = crate::runtime::Storage::from_submitted_buffer(&device, planes, completion)?;
582		Ok((storage, layout))
583	}
584
585	pub(crate) fn decode_h264_native(
586		&mut self,
587		coded_slice: &[u8],
588		sps: &crate::video::H264SequenceParameterSet,
589		pps: &crate::video::H264PictureParameterSet,
590		slice: &crate::video::H264SliceHeader,
591	) -> Result<crate::runtime::NativeDecodedFrame> {
592		let device = self.queue_device()?;
593		self.session_mut()?.upload_bitstream(coded_slice)?;
594		let (command, slot) = self
595			.session_mut()?
596			.record_h264_picture_native(&device, sps, pps, slice)?;
597		let event = self.complete_native_picture(command)?;
598		self.session.native_frame(slot, event)
599	}
600
601	pub(crate) fn decode_h265(
602		&mut self,
603		coded_slice: &[u8],
604		sps: &crate::video::H265SequenceParameterSet,
605		pps: &crate::video::H265PictureParameterSet,
606		slice: &crate::video::H265SliceHeader,
607	) -> Result<crate::video::VideoHostPlanes> {
608		let device = self.queue_device()?;
609		self.session_mut()?.upload_bitstream(coded_slice)?;
610		let command = self
611			.session_mut()?
612			.record_h265_picture_for_readback(&device, sps, pps, slice)?;
613		Ok(self.read_decoded_picture(&device, command)?.0)
614	}
615
616	pub(crate) fn decode_h265_native(
617		&mut self,
618		coded_slice: &[u8],
619		sps: &crate::video::H265SequenceParameterSet,
620		pps: &crate::video::H265PictureParameterSet,
621		slice: &crate::video::H265SliceHeader,
622	) -> Result<crate::runtime::NativeDecodedFrame> {
623		let device = self.queue_device()?;
624		self.session_mut()?.upload_bitstream(coded_slice)?;
625		let (command, slot) = self
626			.session_mut()?
627			.record_h265_picture_native(&device, sps, pps, slice)?;
628		let event = self.complete_native_picture(command)?;
629		self.session.native_frame(slot, event)
630	}
631
632	pub(crate) fn decode_av1(
633		&mut self,
634		access_unit: &[u8],
635		picture: &crate::video::Av1Picture,
636	) -> Result<crate::video::VideoHostPlanes> {
637		let tiles = picture
638			.tiles
639			.as_ref()
640			.ok_or_else(|| Error::invalid_argument("coded AV1 picture has no tile payloads"))?;
641		let device = self.queue_device()?;
642		self.session_mut()?.upload_bitstream(access_unit)?;
643		let (command, slot) = self.session_mut()?.record_av1_picture_for_readback(
644			&device,
645			&picture.sequence,
646			&picture.frame,
647			picture.frame_header_offset,
648			tiles,
649		)?;
650		let (decoded, decode_event) = self.read_decoded_picture(&device, command)?;
651		let index =
652			usize::try_from(slot).map_err(|_| Error::internal("AV1 output slot exceeds usize"))?;
653		*self
654			.av1_ready
655			.get_mut(index)
656			.ok_or_else(|| Error::internal("AV1 output slot exceeds readiness storage"))? =
657			Some(decode_event);
658		*self
659			.av1_host_frames
660			.get_mut(index)
661			.ok_or_else(|| Error::internal("AV1 output slot exceeds host-frame storage"))? =
662			Some(decoded.clone());
663		Ok(decoded)
664	}
665
666	pub(crate) fn decode_av1_native(
667		&mut self,
668		access_unit: &[u8],
669		picture: &crate::video::Av1Picture,
670	) -> Result<crate::runtime::NativeDecodedFrame> {
671		let tiles = picture
672			.tiles
673			.as_ref()
674			.ok_or_else(|| Error::invalid_argument("coded AV1 picture has no tile payloads"))?;
675		let device = self.queue_device()?;
676		self.session_mut()?.upload_bitstream(access_unit)?;
677		let (command, slot) = self.session_mut()?.record_av1_picture_native(
678			&device,
679			&picture.sequence,
680			&picture.frame,
681			picture.frame_header_offset,
682			tiles,
683		)?;
684		let event = self.complete_native_picture(command)?;
685		let index =
686			usize::try_from(slot).map_err(|_| Error::internal("AV1 output slot exceeds usize"))?;
687		*self
688			.av1_ready
689			.get_mut(index)
690			.ok_or_else(|| Error::internal("AV1 output slot exceeds readiness storage"))? =
691			Some(event.clone());
692		self.session.native_frame(slot, event)
693	}
694
695	pub(crate) fn show_existing_av1(
696		&mut self,
697		frame: &crate::video::Av1FrameHeader,
698	) -> Result<crate::video::VideoHostPlanes> {
699		let slot = self.session_mut()?.resolve_av1_show_existing_slot(frame)?;
700		let index =
701			usize::try_from(slot).map_err(|_| Error::internal("AV1 show-existing slot exceeds usize"))?;
702		self
703			.av1_host_frames
704			.get(index)
705			.and_then(Clone::clone)
706			.ok_or_else(|| Error::failed_precondition("AV1 show-existing host frame is unavailable"))
707	}
708
709	pub(crate) fn show_existing_av1_native(
710		&mut self,
711		frame: &crate::video::Av1FrameHeader,
712	) -> Result<crate::runtime::NativeDecodedFrame> {
713		let slot = self.session_mut()?.resolve_av1_show_existing_slot(frame)?;
714		let index =
715			usize::try_from(slot).map_err(|_| Error::internal("AV1 show-existing slot exceeds usize"))?;
716		let ready = self
717			.av1_ready
718			.get(index)
719			.and_then(Clone::clone)
720			.ok_or_else(|| Error::failed_precondition("AV1 show-existing readiness is unavailable"))?;
721		self.session.native_frame(slot, ready)
722	}
723
724	pub(crate) fn decode_vp9(
725		&mut self,
726		access_unit: &[u8],
727		picture: &crate::video::Vp9Picture,
728	) -> Result<crate::video::VideoHostPlanes> {
729		let device = self.queue_device()?;
730		self
731			.session_mut()?
732			.upload_vp9_picture(access_unit, picture)?;
733		let (command, slot) = self
734			.session_mut()?
735			.record_vp9_picture_for_readback(&device, picture)?;
736		let (decoded, decode_event) = self.read_decoded_picture(&device, command)?;
737		let index =
738			usize::try_from(slot).map_err(|_| Error::internal("VP9 output slot exceeds usize"))?;
739		*self
740			.vp9_ready
741			.get_mut(index)
742			.ok_or_else(|| Error::internal("VP9 output slot exceeds readiness storage"))? =
743			Some(decode_event);
744		*self
745			.vp9_host_frames
746			.get_mut(index)
747			.ok_or_else(|| Error::internal("VP9 output slot exceeds host-frame storage"))? =
748			Some(decoded.clone());
749		Ok(decoded)
750	}
751
752	pub(crate) fn decode_vp9_native(
753		&mut self,
754		access_unit: &[u8],
755		picture: &crate::video::Vp9Picture,
756	) -> Result<crate::runtime::NativeDecodedFrame> {
757		let device = self.queue_device()?;
758		self
759			.session_mut()?
760			.upload_vp9_picture(access_unit, picture)?;
761		let (command, slot) = self
762			.session_mut()?
763			.record_vp9_picture_native(&device, picture)?;
764		let event = self.complete_native_picture(command)?;
765		let index =
766			usize::try_from(slot).map_err(|_| Error::internal("VP9 output slot exceeds usize"))?;
767		*self
768			.vp9_ready
769			.get_mut(index)
770			.ok_or_else(|| Error::internal("VP9 output slot exceeds readiness storage"))? =
771			Some(event.clone());
772		self.session.native_frame(slot, event)
773	}
774
775	pub(crate) fn show_existing_vp9(
776		&mut self,
777		picture: &crate::video::Vp9Picture,
778	) -> Result<crate::video::VideoHostPlanes> {
779		let slot = self
780			.session_mut()?
781			.resolve_vp9_show_existing_slot(picture)?;
782		let index =
783			usize::try_from(slot).map_err(|_| Error::internal("VP9 show-existing slot exceeds usize"))?;
784		self
785			.vp9_host_frames
786			.get(index)
787			.and_then(Clone::clone)
788			.ok_or_else(|| Error::failed_precondition("VP9 show-existing host frame is unavailable"))
789	}
790
791	pub(crate) fn show_existing_vp9_native(
792		&mut self,
793		picture: &crate::video::Vp9Picture,
794	) -> Result<crate::runtime::NativeDecodedFrame> {
795		let slot = self
796			.session_mut()?
797			.resolve_vp9_show_existing_slot(picture)?;
798		let index =
799			usize::try_from(slot).map_err(|_| Error::internal("VP9 show-existing slot exceeds usize"))?;
800		let ready = self
801			.vp9_ready
802			.get(index)
803			.and_then(Clone::clone)
804			.ok_or_else(|| Error::failed_precondition("VP9 show-existing readiness is unavailable"))?;
805		self.session.native_frame(slot, ready)
806	}
807
808	pub(crate) fn read_native_yuv420(
809		&mut self,
810		frame: &crate::runtime::NativeDecodedFrame,
811	) -> Result<crate::video::VideoHostPlanes> {
812		let device = self.queue_device()?;
813		let commands = self.session_mut()?.record_native_readback(&device, frame)?;
814		self.submit_native_batch(frame, commands)?.wait()?;
815		self.session.read_decode_yuv420()
816	}
817
818	/// Convert one retained native frame to tightly packed RGBA8 device storage.
819	///
820	/// The pack and conversion submissions mirror [`read_native_yuv420`]'s queue
821	/// round trip but never cross to the host: the returned Storage adopts the
822	/// freshly converted buffer with `Submitted` readiness, so queue-ordered
823	/// consumers (for example a Texture upload) see the finished pixels. No wait
824	/// is performed here; `completion` orders the caller's later submissions.
825	pub(crate) fn read_native_rgba8(
826		&mut self,
827		frame: &crate::runtime::NativeDecodedFrame,
828		color_space: u32,
829		full_range: bool,
830	) -> Result<(crate::runtime::Storage, u32, u32)> {
831		let device = self.queue_device()?;
832		let crate::runtime::device::logical::video::NativePresentation {
833			commands,
834			rgba,
835			extent,
836		} = self
837			.session_mut()?
838			.record_native_presentation(&device, frame, color_space, full_range)?;
839		let completion = self.submit_native_batch(frame, commands)?;
840		let storage = crate::runtime::Storage::from_submitted_buffer(&device, rgba, completion)?;
841		Ok((storage, extent.width, extent.height))
842	}
843
844	pub(crate) fn runtime(&self) -> &RuntimeHandle {
845		&self.runtime
846	}
847}
848
849/// BT.709 color-space selector for the RGBA→NV12 conversion kernel.
850const ENCODE_COLOR_SPACE_BT709: u32 = 1;
851
852/// Runtime-owned implementation for public hardware video encoder sessions.
853///
854/// Owns the encode-slot event ring: each submitted job holds the completion
855/// event of its encode-queue submission until the slot is harvested. Packets
856/// harvested ahead of their caller-visible return point accumulate in `ready`
857/// and drain through `submit_rgba` and `flush`, so no encoded frame is lost.
858pub(crate) struct VideoEncoderBackend {
859	runtime: RuntimeHandle,
860	session: Arc<EncodeSession>,
861	settings: crate::video::VideoEncodeConfig,
862	submission: EncodeSubmission,
863	pending: Vec<Option<Event>>,
864	ready: Vec<crate::video::EncodedVideoPacket>,
865	recording: Option<Vec<RecordedEncodeStep>>,
866	next_slot: usize,
867}
868
869enum EncodeSubmission {
870	Ready,
871	Partial(Event),
872	Unconfirmed,
873}
874
875impl VideoEncoderBackend {
876	pub(crate) fn create(
877		runtime: &Runtime,
878		settings: crate::video::VideoEncodeConfig,
879	) -> Result<Self> {
880		let capabilities = runtime.query_video_encode_capabilities(settings.profile)?;
881		let plan = settings.validate_for_device(capabilities)?;
882		let session = runtime
883			.handle
884			.state
885			.borrow()
886			.device
887			.create_video_encode_session(&settings, plan)?;
888		let slots = session.slot_count();
889		Ok(Self {
890			runtime: runtime.handle.clone(),
891			session: Arc::new(session),
892			settings,
893			submission: EncodeSubmission::Ready,
894			pending: vec![None; slots],
895			ready: Vec::new(),
896			recording: None,
897			next_slot: 0,
898		})
899	}
900
901	/// The runtime timeline serializes conversion and encode across both queues.
902	/// Its latest outstanding event covers all earlier uses of this session.
903	pub(crate) fn retire(self) {
904		let latest = match &self.submission {
905			EncodeSubmission::Ready => self
906				.pending
907				.iter()
908				.flatten()
909				.max_by_key(|event| event.epoch()),
910			EncodeSubmission::Partial(event) => Some(event),
911			EncodeSubmission::Unconfirmed => {
912				// A queue accepted work, but submission retirement could not
913				// publish its completion. The session may still be in use.
914				std::mem::forget(self.session);
915				return;
916			}
917		};
918		if let Some(event) = latest {
919			event.retain_until_complete(self.session);
920		}
921	}
922
923	pub(crate) fn coded_extent(&self) -> crate::video::VideoExtent {
924		self.session.coded_extent()
925	}
926
927	pub(crate) fn visible_extent(&self) -> crate::video::VideoExtent {
928		self.session.visible_extent()
929	}
930
931	pub(crate) fn cached_headers(&self) -> &[u8] {
932		self.session.cached_headers()
933	}
934
935	/// Begin replayable encode recording against a fresh retained session.
936	/// The live session keeps its own GOP/DPB state; the capture owns a new
937	/// `EncodeSession` whose replay-facing images transition once up front,
938	/// so every recorded replay sees steady-state layouts.
939	pub(crate) fn begin_encode_capture(&self) -> Result<Self> {
940		{
941			let state = self.runtime.state.borrow();
942			if !state.capture_active || state.secret_scope.is_some() {
943				return Err(Error::failed_precondition(
944					"recorded video encode requires an active Runtime capture",
945				));
946			}
947		}
948		let session = {
949			let device = self.runtime.state.borrow().device.clone();
950			let capabilities = device.video_encode_capabilities(self.settings.profile)?;
951			let plan = self.settings.validate_for_device(capabilities)?;
952			Arc::new(device.create_video_encode_session(&self.settings, plan)?)
953		};
954		Ok(Self {
955			runtime: self.runtime.clone(),
956			session,
957			settings: self.settings,
958			submission: EncodeSubmission::Ready,
959			pending: vec![None; self.session.slot_count()],
960			ready: Vec::new(),
961			recording: Some(Vec::new()),
962			next_slot: self.next_slot,
963		})
964	}
965
966	pub(crate) fn finish_encode_capture(mut self) -> Result<()> {
967		let steps = self
968			.recording
969			.take()
970			.ok_or_else(|| Error::internal("video encode capture has no recording"))?;
971		let mut state = self.runtime.state.borrow_mut();
972		let device = state.device.clone();
973		state
974			.session
975			.record_video_encode(&device, &self.session, steps)
976	}
977
978	fn append_encode_step(&mut self, step: RecordedEncodeStep) -> Result<()> {
979		self
980			.recording
981			.as_mut()
982			.ok_or_else(|| Error::internal("video encode capture has no recording"))?
983			.push(step);
984		Ok(())
985	}
986
987	/// Record one RGBA frame's conversion + encode into the capture. The
988	/// RGBA upload happens on the host now; only the conversion dispatch and
989	/// `vkCmdEncodeVideoKHR` become graph nodes.
990	pub(crate) fn record_rgba(
991		&mut self,
992		rgba: &[u8],
993		presentation_timestamp_micros: u64,
994		color_space: u32,
995		full_range: bool,
996	) -> Result<()> {
997		if self.recording.is_none() {
998			return Err(Error::failed_precondition(
999				"video encode capture is not recording",
1000			));
1001		}
1002		self.session.validate_ownership()?;
1003		let index = self.next_slot;
1004		self.session.write_rgba(index, rgba)?;
1005		let input = Arc::new(self.session.retain_conversion(
1006			index,
1007			self.session.visible_extent(),
1008			color_space,
1009			full_range,
1010		)?);
1011		let picture = self
1012			.session
1013			.prepare_encode_frame(index, presentation_timestamp_micros)?;
1014		self.append_encode_step(RecordedEncodeStep {
1015			input: Some(input),
1016			planes: Vec::new(),
1017			picture,
1018		})?;
1019		self.next_slot = (index + 1) % self.pending.len();
1020		Ok(())
1021	}
1022
1023	/// Record one frame whose input planes are already graph storage
1024	/// (compute-produced NV12/P010 planes — the decode → compute → encode
1025	/// chain). The staging copy is a graph node on the compute family.
1026	pub(crate) fn record_planes(
1027		&mut self,
1028		planes: &[crate::Matrix],
1029		presentation_timestamp_micros: u64,
1030	) -> Result<()> {
1031		if self.recording.is_none() {
1032			return Err(Error::failed_precondition(
1033				"video encode capture is not recording",
1034			));
1035		}
1036		self.session.validate_ownership()?;
1037		let index = self.next_slot;
1038		let input = Arc::new(self.session.retain_input_copy(index)?);
1039		let expected = input.plane_bytes().len();
1040		if planes.len() != expected {
1041			return Err(Error::invalid_argument(format!(
1042				"encode input expects {expected} planes, got {}",
1043				planes.len()
1044			)));
1045		}
1046		let storages = planes
1047			.iter()
1048			.map(|plane| plane.storage().clone())
1049			.collect::<Vec<_>>();
1050		let picture = self
1051			.session
1052			.prepare_encode_frame(index, presentation_timestamp_micros)?;
1053		self.append_encode_step(RecordedEncodeStep {
1054			input: Some(input),
1055			planes: storages,
1056			picture,
1057		})?;
1058		self.next_slot = (index + 1) % self.pending.len();
1059		Ok(())
1060	}
1061
1062	/// Encode one RGBA8 frame synchronously and return its access unit.
1063	///
1064	/// The job uses the shared slot ring: if the target slot still carries a
1065	/// pending async job it is harvested into `ready` first, then this frame's
1066	/// own event is awaited before the packet is returned.
1067	pub(crate) fn encode_rgba(
1068		&mut self,
1069		rgba: &[u8],
1070		presentation_timestamp_micros: u64,
1071	) -> Result<crate::video::EncodedVideoPacket> {
1072		let index = self.submit_slot(
1073			rgba,
1074			presentation_timestamp_micros,
1075			ENCODE_COLOR_SPACE_BT709,
1076			false,
1077			true,
1078		)?;
1079		self.harvest_slot(index)
1080	}
1081
1082	/// Encode one RGBA64 frame synchronously and return its access unit.
1083	///
1084	/// The session must carry a wide-component profile (ten- or twelve-bit
1085	/// luma); an eight-bit session rejects the input length check.
1086	pub(crate) fn encode_rgba16(
1087		&mut self,
1088		rgba: &[u16],
1089		presentation_timestamp_micros: u64,
1090	) -> Result<crate::video::EncodedVideoPacket> {
1091		// SAFETY: u16 elements are fully initialized over exactly `rgba.len() * 2`
1092		// contiguous bytes, and u8 requires no alignment. The session copies the
1093		// bytes into its own staging buffer before returning, so the view cannot
1094		// outlive the source.
1095		let bytes = unsafe {
1096			std::slice::from_raw_parts(rgba.as_ptr().cast::<u8>(), std::mem::size_of_val(rgba))
1097		};
1098		let index = self.submit_slot(
1099			bytes,
1100			presentation_timestamp_micros,
1101			ENCODE_COLOR_SPACE_BT709,
1102			false,
1103			true,
1104		)?;
1105		self.harvest_slot(index)
1106	}
1107
1108	/// Queue one RGBA8 frame asynchronously and harvest every completed packet.
1109	pub(crate) fn submit_rgba(
1110		&mut self,
1111		rgba: &[u8],
1112		presentation_timestamp_micros: u64,
1113		color_space: u32,
1114		full_range: bool,
1115	) -> Result<Vec<crate::video::EncodedVideoPacket>> {
1116		self.submit_slot(
1117			rgba,
1118			presentation_timestamp_micros,
1119			color_space,
1120			full_range,
1121			false,
1122		)?;
1123		Ok(std::mem::take(&mut self.ready))
1124	}
1125
1126	/// Wait for every pending encode job and return all remaining packets.
1127	pub(crate) fn flush(&mut self) -> Result<Vec<crate::video::EncodedVideoPacket>> {
1128		require_immediate_batch(&self.runtime.state.borrow())?;
1129		// The ring may have wrapped. Visit oldest submission first, rather than
1130		// physical slot zero, so muxers receive monotonically ordered packets.
1131		for offset in 0..self.pending.len() {
1132			let index = (self.next_slot + offset) % self.pending.len();
1133			if self.session.slot_pending(index) {
1134				let packet = self.harvest_slot(index)?;
1135				self.ready.push(packet);
1136			}
1137		}
1138		Ok(std::mem::take(&mut self.ready))
1139	}
1140
1141	/// Upload and submit one frame on the next ring slot, returning its index.
1142	///
1143	/// The target slot's prior pending job (if any) is waited and harvested
1144	/// first. When `synchronous` is clear, completed slots elsewhere in the
1145	/// ring are also harvested non-blockingly into `ready`.
1146	fn submit_slot(
1147		&mut self,
1148		rgba: &[u8],
1149		presentation_timestamp_micros: u64,
1150		color_space: u32,
1151		full_range: bool,
1152		synchronous: bool,
1153	) -> Result<usize> {
1154		if self.recording.is_some() {
1155			return Err(Error::failed_precondition(
1156				"immediate encode submission during capture; use record_rgba",
1157			));
1158		}
1159		let device = {
1160			let state = self.runtime.state.borrow();
1161			require_immediate_batch(&state)?;
1162			state.device.clone()
1163		};
1164		let index = self.next_slot;
1165		if !matches!(self.submission, EncodeSubmission::Ready) {
1166			return Err(Error::failed_precondition(
1167				"encoder requires reopening after a partial submission",
1168			));
1169		}
1170		if self.session.slot_pending(index) {
1171			let packet = self.harvest_slot(index)?;
1172			self.ready.push(packet);
1173		}
1174		self.session.write_rgba(index, rgba)?;
1175		let mut commands = RecordedBatch::new(&device);
1176		commands.push(self.session.record_conversion(
1177			&device,
1178			index,
1179			self.session.visible_extent(),
1180			color_space,
1181			full_range,
1182		)?);
1183		commands.push(self.session.record_frame(&device, index)?);
1184		let event = {
1185			let mut state = self.runtime.state.borrow_mut();
1186			let starting_epoch = state.next_epoch;
1187			let mut accepted = None;
1188			match submit_recorded_batch_with(&mut state, commands, false, |state, command| {
1189				let event = submit_recorded(state, command)?;
1190				accepted = Some(event.clone());
1191				Ok(event)
1192			}) {
1193				Ok(event) => event,
1194				Err(error) => {
1195					if state.next_epoch != starting_epoch {
1196						self.submission = match accepted {
1197							Some(event) if event.epoch() == state.next_epoch => EncodeSubmission::Partial(event),
1198							_ => EncodeSubmission::Unconfirmed,
1199						};
1200					}
1201					return Err(error);
1202				}
1203			}
1204		};
1205		self.next_slot = (index + 1) % self.pending.len();
1206		self
1207			.session
1208			.mark_pending(index, presentation_timestamp_micros);
1209		self.pending[index] = Some(event);
1210		if !synchronous {
1211			for offset in 0..self.pending.len() {
1212				let slot = (self.next_slot + offset) % self.pending.len();
1213				if slot == index {
1214					continue;
1215				}
1216				let complete = match &self.pending[slot] {
1217					Some(candidate) => candidate.is_complete()?,
1218					None => false,
1219				};
1220				if complete {
1221					let packet = self.harvest_slot(slot)?;
1222					self.ready.push(packet);
1223				} else if self.pending[slot].is_some() {
1224					// Never publish a later packet ahead of an earlier pending job.
1225					break;
1226				}
1227			}
1228		}
1229		Ok(index)
1230	}
1231
1232	/// Wait the slot's event, read its feedback and bitstream, and build the
1233	/// access unit. Cached codec headers are prepended to keyframe packets so
1234	/// every random-access point is self-describing Annex-B.
1235	fn harvest_slot(&mut self, index: usize) -> Result<crate::video::EncodedVideoPacket> {
1236		let event = self.pending[index]
1237			.as_ref()
1238			.ok_or_else(|| Error::failed_precondition("encode slot has no pending submission"))?;
1239		event.wait()?;
1240		let feedback = self.session.read_feedback(index)?;
1241		let keyframe = self.session.slot_is_keyframe(index);
1242		let pts = self.session.slot_presentation_timestamp(index);
1243		let headers = if keyframe {
1244			self.session.cached_headers()
1245		} else {
1246			&[]
1247		};
1248		let length = headers
1249			.len()
1250			.checked_add(feedback.bytes_written as usize)
1251			.ok_or_else(|| Error::out_of_range("encoded packet size overflowed"))?;
1252		let mut packet = Vec::new();
1253		packet
1254			.try_reserve_exact(length)
1255			.map_err(|_| Error::resource_exhausted("encoded packet allocation failed"))?;
1256		packet.extend_from_slice(headers);
1257		packet.resize(length, 0);
1258		self.session.read_bitstream(
1259			index,
1260			u64::from(feedback.bitstream_offset),
1261			&mut packet[headers.len()..],
1262		)?;
1263		let packet = crate::video::EncodedVideoPacket::new(packet, pts, keyframe)?;
1264		self.session.mark_completed(index);
1265		self.pending[index] = None;
1266		Ok(packet)
1267	}
1268}
1269
1270/// Runtime-tracked compose image allocation — cleaned up on `destroy_compose_image`.
1271struct ComposeImageEntry {
1272	image: vk::Image,
1273	view: vk::ImageView,
1274	alloc: vk::mem::Allocation,
1275}
1276
1277struct RuntimeState {
1278	// Fields drop in declaration order. Retirement disconnects first and joins only
1279	// an already-drained host worker; an active worker retains the device and
1280	// transitive instance ownership until every submitted epoch completes.
1281	retirement: RetirementService,
1282	session: ExecutionSession,
1283	device: Arc<Device>,
1284	next_epoch: u64,
1285	capture_active: bool,
1286	capture_generation: u64,
1287	/// Active deferred secret-lowering batch. While set, every recorded
1288	/// submission defers into this ordered batch instead of queueing.
1289	secret_scope: Option<SecretScopeState>,
1290	/// Live compose images allocated for UI layers.
1291	compose_images: RefCell<Vec<ComposeImageEntry>>,
1292	/// Measured matmul winners recorded by qualification, replayed only after
1293	/// full revalidation against the live registry and problem/device contract.
1294	matmul_route_cache: super::dna::provider::blas::MatmulRouteCache,
1295	/// `true` when the `.vkcache` GEMM section existed but failed its inner
1296	/// codec. A failed-load snapshot must never replace another writer's
1297	/// qualified observations, so persistence preserves that section verbatim.
1298	matmul_route_section_corrupt: bool,
1299	/// Active runtime-scoped precision override installed by
1300	/// [`crate::ml::PrecisionScope`]. Stored inside `RuntimeState` to keep
1301	/// `RuntimeHandle` a single pointer.
1302	precision_override: std::cell::Cell<Option<crate::ml::StoragePrecision>>,
1303}
1304
1305/// Classification metadata for one deferred node. The scope records whether a
1306/// command consumes secrets, records erasure, or retains public outputs —
1307/// never secret bytes, handles, or raw descriptor data.
1308#[derive(Clone, Copy)]
1309pub(crate) struct SecretScopeNode {
1310	pub(crate) uses_secret: bool,
1311	pub(crate) records_erasure: bool,
1312	pub(crate) retains_public: bool,
1313}
1314
1315struct DeferredSubmission {
1316	epoch: u64,
1317	command: RecordedCommandBuffer,
1318	deferred: DeferredRetirement,
1319	ticket: RetirementTicket,
1320}
1321
1322struct SecretScopeState {
1323	pending: Vec<DeferredSubmission>,
1324	nodes: Vec<SecretScopeNode>,
1325}
1326
1327/// Thread-affine shared access to the execution owner retained by its values.
1328#[derive(Clone)]
1329pub(crate) struct RuntimeHandle {
1330	state: Rc<RefCell<RuntimeState>>,
1331}
1332
1333/// Timestamp placement for one eager flush or checkpoint. `Borrowed` records a
1334/// caller-owned named-timer pair; the timer owns the reading, so the submission
1335/// event does not expose a duration.
1336enum FlushTiming {
1337	Untimed,
1338	Fresh,
1339	Borrowed(super::TimestampPair),
1340}
1341
1342/// Unique private value; only in-flight commands may share its storage lifetime.
1343/// No Clone, Debug, mapping, export, Matrix conversion or implicit erasure.
1344pub(crate) struct MlKemDeviceKey {
1345	runtime: RuntimeHandle,
1346	private: Arc<SecretBuffer>,
1347	public: Buffer,
1348	k: u32,
1349	ready: Event,
1350}
1351
1352/// Unique private value; only in-flight commands may share its storage lifetime.
1353/// No Clone, Debug, mapping, export, Matrix conversion or implicit erasure.
1354pub(crate) struct MlDsaDeviceKey {
1355	runtime: RuntimeHandle,
1356	private: Arc<SecretBuffer>,
1357	public: Buffer,
1358	parameter: u32,
1359	ready: Event,
1360}
1361
1362/// Unique private shared-secret value. Readiness retains its originating Runtime;
1363/// command references retain storage only, with no mapping or implicit erasure.
1364pub(crate) struct MlKemSharedSecret {
1365	runtime: RuntimeHandle,
1366	private: Arc<SecretBuffer>,
1367	ready: Event,
1368}
1369
1370/// Transactional ownership of one semantic operation's composite lowering.
1371///
1372/// Child operations retain executable work while their semantic identities are
1373/// suppressed. The outermost commit assigns every emitted node to the parent
1374/// contract; dropping an unfinished scope rolls back only its emitted work.
1375pub(crate) struct SemanticLoweringScope {
1376	runtime: RuntimeHandle,
1377	active: bool,
1378}
1379
1380/// Deferred secret-execution batch owned by one Runtime.
1381///
1382/// While this scope is active, recorded secret and ordinary submissions defer
1383/// into an ordered batch carrying secret classification metadata only — never
1384/// secret bytes. `commit` submits the batch in order; abandoning it frees the
1385/// recorded commands and fails their reserved completions without submission
1386/// or waiting.
1387pub(crate) struct SecretLoweringScope {
1388	runtime: RuntimeHandle,
1389	active: bool,
1390}
1391
1392impl SecretLoweringScope {
1393	/// Classification snapshot of the deferred nodes. Diagnostics may observe
1394	/// flags and order only; no secret bytes or native handles are exposed.
1395	pub(crate) fn nodes(&self) -> Vec<SecretScopeNode> {
1396		self
1397			.runtime
1398			.state
1399			.borrow()
1400			.secret_scope
1401			.as_ref()
1402			.map(|scope| scope.nodes.clone())
1403			.unwrap_or_default()
1404	}
1405
1406	/// Submit every deferred command in recorded order. Per-operation events
1407	/// and erasure tickets issued during the scope resolve through their own
1408	/// exact epochs; the returned event describes the final node.
1409	///
1410	/// On failure, unsubmitted nodes are freed and their completions failed;
1411	/// already-submitted nodes retire normally.
1412	pub(crate) fn commit(mut self) -> Result<Event> {
1413		let mut state = self.runtime.state.borrow_mut();
1414		let Some(scope) = state.secret_scope.take() else {
1415			return Err(Error::failed_precondition(
1416				"secret lowering scope is no longer active",
1417			));
1418		};
1419		self.active = false;
1420		let mut pending = scope.pending;
1421		if pending.is_empty() {
1422			return Err(Error::invalid_argument(
1423				"secret lowering scope recorded no submissions",
1424			));
1425		}
1426		let mut result = Ok(None);
1427		while let Some(item) = pending.first() {
1428			if let Err(error) = state.device.submit(&item.command, item.epoch) {
1429				result = Err(error);
1430				break;
1431			}
1432			state.next_epoch = item.epoch;
1433			let timing = item.command.timing();
1434			let ticket = item.ticket.clone();
1435			let item = pending.remove(0);
1436			if let Err(error) = state
1437				.retirement
1438				.retire_deferred(item.deferred, item.command, item.epoch)
1439			{
1440				result = Err(error);
1441				break;
1442			}
1443			result = Ok(Some(Event::new(
1444				state.device.clone(),
1445				item.epoch,
1446				ticket,
1447				timing,
1448			)));
1449		}
1450		for item in pending {
1451			item.deferred.fail();
1452			state.device.free(item.command);
1453		}
1454		result.and_then(|event| event.ok_or_else(|| Error::internal("secret batch produced no event")))
1455	}
1456}
1457
1458impl Drop for SecretLoweringScope {
1459	fn drop(&mut self) {
1460		if !self.active {
1461			return;
1462		}
1463		let mut state = self.runtime.state.borrow_mut();
1464		let Some(scope) = state.secret_scope.take() else {
1465			return;
1466		};
1467		for item in scope.pending {
1468			item.deferred.fail();
1469			state.device.free(item.command);
1470		}
1471	}
1472}
1473
1474impl Runtime {
1475	/// List every Vulkan device, including software CPU implementations.
1476	///
1477	/// Creates a temporary instance but no logical device, allocator or pipelines.
1478	/// A listed device may still fail OA capability admission. Ordinals are scoped
1479	/// to the current loader and ICD configuration, not stable across machines.
1480	///
1481	/// # Errors
1482	/// Returns backend initialization or enumeration errors.
1483	pub fn available_devices() -> Result<Vec<super::DeviceSummary>> {
1484		let instance = Instance::new(&[])?;
1485		DevicePhysical::enumerate(&instance)
1486	}
1487
1488	/// Return queried device facts and the allocated descriptor capacities.
1489	pub fn device_info(&self) -> crate::DeviceInfo {
1490		self.handle.device_info()
1491	}
1492
1493	/// Return runtime-lifetime fusion decision and decline counters.
1494	///
1495	/// Counts reflect fusion passes that already ran: eager work is fused when
1496	/// it is flushed and captured work when it is captured. This query does not
1497	/// flush, submit or wait, and plan replay does not change the counters.
1498	/// The record is a diagnostic; it never influences route selection.
1499	pub fn fusion_stats(&self) -> super::FusionStats {
1500		self.handle.fusion_stats()
1501	}
1502
1503	/// Begin explicit runtime configuration.
1504	pub fn builder() -> RuntimeBuilder {
1505		RuntimeBuilder::new()
1506	}
1507
1508	/// Create an runtime using one compute-capable Vulkan device.
1509	///
1510	/// # Errors
1511	///
1512	/// Returns an error when Vulkan cannot be loaded, no hardware device meets
1513	/// the compiled Core or Compatibility profile requirements,
1514	/// or logical-device creation fails.
1515	pub fn new() -> Result<Self> {
1516		Self::builder().build()
1517	}
1518
1519	/// Initialize this thread's default compute runtime before its first use.
1520	///
1521	/// Initialization is lazy and attempted again after a failure. The selected
1522	/// runtime remains thread-affine and is reused by later default operations.
1523	///
1524	/// # Errors
1525	///
1526	/// Returns the same backend or device-selection error as [`Runtime::new`].
1527	pub fn init_default() -> Result<()> {
1528		DEFAULT_RUNTIME.with(|slot| {
1529			if slot.borrow().is_none() {
1530				let runtime = Self::new()?;
1531				*slot.borrow_mut() = Some(runtime);
1532			}
1533			Ok(())
1534		})
1535	}
1536
1537	/// Install `runtime` as this thread's default compute runtime.
1538	///
1539	/// Replaces any runtime previously stored by [`Runtime::init_default`] or an
1540	/// earlier `set_default` call. The previous default is dropped after the
1541	/// new runtime is installed.
1542	pub fn set_default(runtime: Runtime) {
1543		DEFAULT_RUNTIME.with(|slot| {
1544			*slot.borrow_mut() = Some(runtime);
1545		});
1546	}
1547
1548	/// Return this thread's default compute runtime.
1549	///
1550	/// Initialization is lazy on first use and the returned handle clones the
1551	/// installed runtime, so it remains valid if the default is later replaced.
1552	///
1553	/// # Errors
1554	///
1555	/// Returns the same backend or device-selection error as [`Runtime::new`].
1556	pub fn current() -> Result<Self> {
1557		Self::init_default()?;
1558		DEFAULT_RUNTIME.with(|slot| {
1559			Ok(
1560				slot
1561					.borrow()
1562					.as_ref()
1563					.expect("default runtime initialized above")
1564					.clone(),
1565			)
1566		})
1567	}
1568
1569	/// Access this thread's lazily initialized default compute runtime.
1570	///
1571	/// # Errors
1572	///
1573	/// Returns an runtime initialization error or an error from `use_runtime`.
1574	pub fn with_default<T>(use_runtime: impl FnOnce(&Self) -> Result<T>) -> Result<T> {
1575		Self::init_default()?;
1576		DEFAULT_RUNTIME.with(|slot| {
1577			let selected = slot.borrow();
1578			let runtime = selected
1579				.as_ref()
1580				.expect("default runtime initialized above");
1581			use_runtime(runtime)
1582		})
1583	}
1584
1585	/// Return whether this Runtime has an executable graphics path.
1586	///
1587	/// Both profiles require enabled dynamic rendering and a graphics queue.
1588	/// Presentation additionally requires WSI support and
1589	/// per-surface present-support negotiation.
1590	pub fn has_graphics(&self) -> bool {
1591		self.handle.state.borrow().device.has_graphics_queue()
1592	}
1593
1594	/// Return whether this Runtime's device can calibrate its timestamp domain
1595	/// against a POSIX monotonic host clock.
1596	pub fn supports_clock_calibration(&self) -> bool {
1597		self
1598			.handle
1599			.state
1600			.borrow()
1601			.device
1602			.supports_clock_calibration()
1603	}
1604
1605	/// Sample paired device/host timestamps and retain the lowest-deviation
1606	/// pair.
1607	///
1608	/// `sample_count` selects the best of `[1, 1024]` quasi-simultaneous
1609	/// samples; recalibrate long-running traces periodically because a value
1610	/// farther than half a device-clock period from the sample is inherently
1611	/// ambiguous.
1612	///
1613	/// # Errors
1614	///
1615	/// Returns `InvalidArgument` when `sample_count` is outside `[1, 1024]`,
1616	/// `Unavailable` when the device lacks calibrated timestamps or usable
1617	/// domains, and a backend error when sampling fails.
1618	pub fn calibrate_clock(&self, sample_count: u32) -> Result<ClockCalibration> {
1619		self
1620			.handle
1621			.state
1622			.borrow()
1623			.device
1624			.calibrate_clock(sample_count)
1625	}
1626
1627	/// Create one SDL3 Vulkan surface borrowing this Runtime and window.
1628	pub fn new_presentation_surface<'window>(
1629		&self,
1630		window: &'window super::SdlWindow,
1631	) -> Result<super::PresentationSurface<'window>> {
1632		let state = self.handle.state.borrow();
1633		PresentationSurface::create(&state.device, window)
1634	}
1635
1636	pub fn owns_matrix(&self, matrix: &Matrix) -> bool {
1637		self.handle.same_as(matrix.runtime())
1638	}
1639
1640	pub(crate) fn same_as_handle(&self, handle: &RuntimeHandle) -> bool {
1641		self.handle.same_as(handle)
1642	}
1643
1644	pub(crate) fn begin_stable_resource_frame(&self) -> Result<()> {
1645		self.handle.begin_stable_resource_frame()
1646	}
1647
1648	pub(crate) fn seal_all_stable_resources_external(&self) -> Result<()> {
1649		self.handle.seal_all_stable_resources_external()
1650	}
1651
1652	pub(crate) fn seal_stable_resource_inputs(&self) -> Result<()> {
1653		self.handle.seal_stable_resource_inputs()
1654	}
1655
1656	pub(crate) fn end_stable_resource_frame(&self) {
1657		self.handle.end_stable_resource_frame();
1658	}
1659
1660	pub(crate) fn has_pending_work(&self) -> bool {
1661		self.handle.has_pending_work()
1662	}
1663
1664	pub(crate) fn abort_pending_work(&self) {
1665		self.handle.abort_pending_work();
1666	}
1667
1668	pub(crate) fn query_video_device_capabilities(
1669		&self,
1670	) -> Result<crate::video::VideoDeviceCapabilities> {
1671		self
1672			.handle
1673			.state
1674			.borrow()
1675			.device
1676			.video_device_capabilities()
1677	}
1678
1679	pub(crate) fn query_video_decode_capabilities(
1680		&self,
1681		profile: crate::video::VideoDecodeProfile,
1682	) -> Result<crate::video::VideoDecodeCapabilities> {
1683		self
1684			.handle
1685			.state
1686			.borrow()
1687			.device
1688			.video_decode_capabilities(profile)
1689	}
1690
1691	pub(crate) fn query_video_decode_formats(
1692		&self,
1693		profile: crate::video::VideoDecodeProfile,
1694	) -> Result<crate::video::VideoDecodeFormats> {
1695		self
1696			.handle
1697			.state
1698			.borrow()
1699			.device
1700			.video_decode_formats(profile)
1701	}
1702
1703	pub(crate) fn query_video_encode_capabilities(
1704		&self,
1705		profile: crate::video::VideoEncodeProfile,
1706	) -> Result<crate::video::VideoEncodeCapabilities> {
1707		self
1708			.handle
1709			.state
1710			.borrow()
1711			.device
1712			.video_encode_capabilities(profile)
1713	}
1714
1715	pub(crate) fn query_video_encode_formats(
1716		&self,
1717		profile: crate::video::VideoEncodeProfile,
1718	) -> Result<crate::video::VideoEncodeFormats> {
1719		self
1720			.handle
1721			.state
1722			.borrow()
1723			.device
1724			.video_encode_formats(profile)
1725	}
1726
1727	pub(super) fn build(
1728		selection: DeviceSelection,
1729		requirements: RuntimeRequirements,
1730		log_options: LogOptions,
1731		instance_extensions: Vec<String>,
1732	) -> Result<Self> {
1733		let logger = Logger::new(log_options)?;
1734		let log_selection = logger.select();
1735		let instance = Instance::new(&instance_extensions)?;
1736		if requirements.presentation && !instance.surface_enabled() {
1737			return Err(Error::invalid_argument(
1738				"presentation readiness requires Vulkan surface instance extensions",
1739			));
1740		}
1741		let physical_device = DevicePhysical::select(&instance, selection, &requirements)?;
1742		let device = Device::new(&instance, physical_device)?;
1743		let retirement = RetirementService::new(&device);
1744		device.log_identity();
1745		// Opt-in upfront compilation; the default stays lazy so optional
1746		// domains never enter a driver compiler during Runtime construction.
1747		if crate::EnvFlag::is_set("OA_SHADER_PRELOAD")
1748			&& let Err(error) = device.preload_pipelines()
1749		{
1750			crate::log_warn!(
1751				crate::LogComponent::RUNTIME,
1752				"embedded shader preload failed: {error}"
1753			);
1754		}
1755
1756		// Best-effort measured-route replay through the scoped `.vkcache`
1757		// envelope: a missing section is normal; a present but malformed one is
1758		// evidence worth surfacing while it is preserved for a later writer.
1759		// Either way the empty cache fails closed to structural routing — never
1760		// to a partially accepted record.
1761		let vkcache_scope = super::device::logical::vkcache::VkCacheScope::new(device.physical());
1762		let vkcache_path = vkcache_scope.path();
1763		let mut matmul_route_section_corrupt = false;
1764		let mut matmul_route_cache = super::dna::provider::blas::MatmulRouteCache::new();
1765		if vkcache_path.is_file() {
1766			match super::device::logical::vkcache::VkCacheFile::open(&vkcache_path, &vkcache_scope) {
1767				Ok(file) => {
1768					if let Some(section) =
1769						file.section(super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES)
1770					{
1771						match super::dna::provider::blas::MatmulRouteCache::from_bytes(&section.bytes) {
1772							Ok(cache) => matmul_route_cache = cache,
1773							Err(error) => {
1774								matmul_route_section_corrupt = true;
1775								crate::log_warn!(
1776									crate::LogComponent::RUNTIME,
1777									"discarding malformed vkcache matmul route section: {error}"
1778								);
1779							}
1780						}
1781					}
1782				}
1783				Err(error) => {
1784					crate::log_warn!(
1785						crate::LogComponent::RUNTIME,
1786						"discarding vkcache artifact for route replay: {error}"
1787					);
1788				}
1789			}
1790		}
1791		// Legacy migration: scope-matching records from the unscoped file merge
1792		// in; it stays on disk for other scopes and is never written again.
1793		let route_cache_path = super::dna::provider::blas::route_cache_path();
1794		if let Ok(legacy) = super::dna::provider::blas::MatmulRouteCache::load(&route_cache_path) {
1795			let (vendor_id, device_id, driver_id, driver_version) = vkcache_scope.device_route_scope();
1796			matmul_route_cache.merge_scope(&legacy, vendor_id, device_id, driver_id, driver_version);
1797		}
1798
1799		let handle = RuntimeHandle {
1800			state: Rc::new(RefCell::new(RuntimeState {
1801				retirement,
1802				session: ExecutionSession::new(),
1803				device,
1804				next_epoch: 0,
1805				capture_active: false,
1806				capture_generation: 0,
1807				secret_scope: None,
1808				compose_images: RefCell::new(Vec::new()),
1809				matmul_route_cache,
1810				matmul_route_section_corrupt,
1811				precision_override: std::cell::Cell::new(None),
1812			})),
1813		};
1814		Ok(Self {
1815			_log_selection: log_selection,
1816			logger,
1817			persistence: Rc::new(RuntimePersistence {
1818				handle: handle.clone(),
1819			}),
1820			handle,
1821			_not_send_sync: PhantomData,
1822		})
1823	}
1824
1825	/// Submit an explicit completion checkpoint to this runtime's compute queue.
1826	///
1827	/// Pending eager operations are submitted together as one batch. When no
1828	/// eager work is pending, an empty checkpoint is submitted. The returned
1829	/// event completes after that exact queue point. Dropping it does not wait.
1830	///
1831	/// # Errors
1832	///
1833	/// Returns an error when command recording, submission, or retirement fails,
1834	/// or when the runtime exhausts its timeline epoch space.
1835	pub fn checkpoint(&self) -> Result<Event> {
1836		self.handle.checkpoint(false)
1837	}
1838
1839	/// Submit pending eager work with one device timestamp pair around the batch.
1840	///
1841	/// Unlike [`Runtime::checkpoint`], this requires at least one pending operation;
1842	/// there is no meaningful device interval for an empty queue checkpoint.
1843	///
1844	/// # Errors
1845	///
1846	/// Returns the errors from [`Runtime::checkpoint`], `MissingCapability` when
1847	/// timestamps are unavailable, or `FailedPrecondition` for an empty batch.
1848	pub fn checkpoint_timed(&self) -> Result<Event> {
1849		self.handle.checkpoint(true)
1850	}
1851
1852	/// Submit pending eager work bracketed by a device [`Timer`]'s timestamps.
1853	///
1854	/// The timer must be initialized for `TimerDomain::Device` on this runtime
1855	/// and is single-flight: a new tagged submission is rejected while the
1856	/// previous one is pending. The returned event carries no timing; the
1857	/// elapsed device duration is committed through [`Timer::commit`].
1858	///
1859	/// Donor: `oa::Runtime::submit(oa::Timer*)` in
1860	/// `oacpp/source/cpp/lib/oa/runtime/runtime/runtime.cpp`.
1861	///
1862	/// # Errors
1863	///
1864	/// Returns the errors from [`Runtime::checkpoint_timed`], or
1865	/// `FailedPrecondition` when the timer is host-domain, uninitialized, or
1866	/// still pending, or `InvalidArgument` when it was initialized by another
1867	/// runtime.
1868	pub fn checkpoint_with_timer(&self, timer: &mut Timer) -> Result<Event> {
1869		let device = self.handle.state.borrow().device.clone();
1870		timer.prepare_device_submit(&device)?;
1871		let pair = timer
1872			.device_pair()
1873			.expect("device timer was checked")
1874			.clone();
1875		let event = self.handle.checkpoint_timed_with(&pair)?;
1876		timer.attach_event(event.clone());
1877		Ok(event)
1878	}
1879
1880	/// Create a device timestamp pair for a named [`Timer`].
1881	pub(crate) fn device_timestamp_pair(&self) -> Result<super::TimestampPair> {
1882		self
1883			.handle
1884			.state
1885			.borrow()
1886			.device
1887			.clone()
1888			.new_timestamp_pair()
1889	}
1890
1891	/// Capture an isolated operation sequence as an immutable execution plan.
1892	///
1893	/// Capture records but never submits or waits. The returned value may include
1894	/// matrices produced by the plan; those matrices become observable only after
1895	/// [`Runtime::submit`] is called for the returned plan.
1896	///
1897	/// # Errors
1898	///
1899	/// Returns an error when eager work is already pending, capture is nested, the
1900	/// closure fails, or the closure records no executable work.
1901	pub fn capture<T>(&self, capture: impl FnOnce() -> Result<T>) -> Result<(ExecutionPlan, T)> {
1902		let guard = CaptureGuard::begin(self.handle.clone())?;
1903		let output = capture()?;
1904		let plan = guard.finish(&[])?;
1905		Ok((plan, output))
1906	}
1907
1908	pub(crate) fn capture_with_initialized_state<T>(
1909		&self,
1910		state: &[&Matrix],
1911		capture: impl FnOnce() -> Result<T>,
1912	) -> Result<(ExecutionPlan, T)> {
1913		let snapshots = state
1914			.iter()
1915			.map(|value| {
1916				if !self.owns_matrix(value) {
1917					return Err(Error::invalid_argument(
1918						"capture state belongs to another runtime",
1919					));
1920				}
1921				value.storage().initialized_readiness()
1922			})
1923			.collect::<Result<Vec<_>>>()?;
1924		let result = self.capture(capture);
1925		for (value, previous) in state.iter().zip(snapshots) {
1926			previous.restore(value.storage());
1927		}
1928		result
1929	}
1930
1931	pub(crate) fn capture_observed_matrix(
1932		&self,
1933		capture: impl FnOnce() -> Result<Matrix>,
1934	) -> Result<(ExecutionPlan, Matrix)> {
1935		let guard = CaptureGuard::begin(self.handle.clone())?;
1936		let output = capture()?;
1937		let plan = guard.finish(&[&output])?;
1938		Ok((plan, output))
1939	}
1940
1941	pub(crate) fn capture_observed_training_matrix_preserving(
1942		&self,
1943		capture: impl FnOnce() -> Result<Matrix>,
1944	) -> Result<CaptureAttempt<Matrix>> {
1945		let guard = CaptureGuard::begin(self.handle.clone())?;
1946		let output = capture()?;
1947		Ok(match guard.finish_preserving(&[&output]) {
1948			Ok(plan) => CaptureAttempt::Captured {
1949				plan: Box::new(plan),
1950				output,
1951			},
1952			Err(error) => CaptureAttempt::Rejected { error, output },
1953		})
1954	}
1955
1956	/// Submit an immutable execution plan to its originating runtime.
1957	///
1958	/// Any pending eager batch is submitted first. The returned event identifies
1959	/// exact completion of this plan replay. Submission does not wait.
1960	///
1961	/// # Errors
1962	///
1963	/// Returns an error when the plan belongs to another runtime, capture is active,
1964	/// eager flushing fails, or command recording, submission, or retirement fails.
1965	pub fn submit(&self, plan: &ExecutionPlan) -> Result<Event> {
1966		self.handle.submit_plan(plan, false)
1967	}
1968
1969	/// Submit a plan with one device timestamp pair around its complete graph.
1970	///
1971	/// The returned event exposes the device duration through
1972	/// [`Event::try_device_duration`] and [`Event::device_duration`]. Timing adds
1973	/// instrumentation only to this replay and does not wait.
1974	///
1975	/// # Errors
1976	///
1977	/// Returns the errors from [`Runtime::submit`], or `MissingCapability` when the
1978	/// selected compute queue cannot provide timestamps.
1979	pub fn submit_timed(&self, plan: &ExecutionPlan) -> Result<Event> {
1980		self.handle.submit_plan(plan, true)
1981	}
1982
1983	/// Write one record through this runtime's logging session.
1984	///
1985	/// Filtered records return successfully without formatting or output.
1986	///
1987	/// # Errors
1988	///
1989	/// Returns the first retained console or file output failure, or an error if
1990	/// the logging session has already been closed.
1991	pub fn log(&self, level: LogLevel, component: LogComponent, text: impl AsRef<str>) -> Result<()> {
1992		self.logger.write_text(level, component, text.as_ref())
1993	}
1994
1995	/// Change this runtime logger's minimum severity.
1996	pub fn set_log_level(&self, level: LogLevel) {
1997		self.logger.set_level(level);
1998	}
1999
2000	/// Return this runtime logger's current minimum severity.
2001	pub fn log_level(&self) -> LogLevel {
2002		self.logger.level()
2003	}
2004
2005	/// Return the active log-file path when file output is enabled.
2006	pub fn log_path(&self) -> Option<std::path::PathBuf> {
2007		self.logger.path()
2008	}
2009
2010	/// Flush this runtime's logging session and report any retained sink failure.
2011	///
2012	/// # Errors
2013	///
2014	/// Returns the first console or file output failure.
2015	pub fn flush_log(&self) -> Result<()> {
2016		self.logger.flush()
2017	}
2018
2019	/// Explicitly close this runtime's logging session before releasing the runtime.
2020	///
2021	/// Existing values retain the execution services they require, but no longer
2022	/// have a selected runtime logging session after this call consumes `self`.
2023	///
2024	/// # Errors
2025	///
2026	/// Returns the first console or file flush failure.
2027	pub fn close(self) -> Result<()> {
2028		if crate::EnvFlag::is_set("OA_JIT_TRACE") {
2029			crate::log_info!(
2030				LogComponent::COMPUTE,
2031				"fusion census {}",
2032				self.fusion_stats()
2033			);
2034			let state = self.handle.state.borrow();
2035			let census = state.device.fusion_census();
2036			crate::log_info!(
2037				LogComponent::COMPUTE,
2038				"fusion host_ns {}",
2039				census.fusion_ns()
2040			);
2041			for stats in census.pair_diagnostics() {
2042				crate::log_info!(LogComponent::COMPUTE, "fusion pair {stats}");
2043			}
2044			for stats in census.merge_diagnostics() {
2045				crate::log_info!(LogComponent::COMPUTE, "fusion merge {stats}");
2046			}
2047		}
2048		crate::log_info!(LogComponent::OWNERSHIP, "closing Vulkan compute runtime");
2049		self.logger.close()
2050	}
2051
2052	pub(crate) fn handle(&self) -> RuntimeHandle {
2053		self.handle.clone()
2054	}
2055}
2056
2057impl Drop for RuntimePersistence {
2058	fn drop(&mut self) {
2059		// One Runtime-owned persistence point: gather subsystem snapshots while
2060		// the device is live, then merge them into the scoped `.vkcache`
2061		// envelope under its atomic writer policy. The cache is disposable
2062		// qualified state — a borrow, query or I/O failure never fails runtime
2063		// destruction and never replaces committed observations.
2064		let snapshot = self.handle.state.try_borrow().ok().map(|state| {
2065			let scope = super::device::logical::vkcache::VkCacheScope::new(state.device.physical());
2066			let driver = state.device.pipeline_cache_data();
2067			let jit = state.device.jit_section_updates();
2068			let (vendor_id, device_id, driver_id, driver_version) = scope.device_route_scope();
2069			let gemm = if state.matmul_route_section_corrupt {
2070				// The loaded section failed its inner codec; preserve whatever
2071				// qualified records it may still hold for another writer.
2072				None
2073			} else {
2074				Some(state.matmul_route_cache.serialize_scope(
2075					vendor_id,
2076					device_id,
2077					driver_id,
2078					driver_version,
2079				))
2080			};
2081			(scope, driver, gemm, jit)
2082		});
2083		let Some((scope, driver, gemm, jit)) = snapshot else {
2084			return;
2085		};
2086		let mut updates = Vec::with_capacity(2);
2087		if let Some(blob) = driver {
2088			updates.push(super::device::logical::vkcache::SectionUpdate::replace(
2089				super::device::logical::vkcache::SECTION_DRIVER_PIPELINE_CACHE,
2090				1,
2091				blob,
2092			));
2093		}
2094		match gemm {
2095			Some(Some(payload)) => {
2096				updates.push(super::device::logical::vkcache::SectionUpdate::replace(
2097					super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES,
2098					1,
2099					payload,
2100				));
2101			}
2102			Some(None) => {
2103				updates.push(super::device::logical::vkcache::SectionUpdate::remove(
2104					super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES,
2105				));
2106			}
2107			None => {}
2108		}
2109		updates.extend(jit);
2110		if updates.is_empty() {
2111			return;
2112		}
2113		let path = scope.path();
2114		if super::device::logical::vkcache::update(&path, &scope, &updates).is_ok() {
2115			// The scoped artifact committed; the legacy raw driver blob has
2116			// been imported or superseded and is never written again.
2117			let _ = crate::Filesystem::remove_file(
2118				&super::device::logical::pipeline::legacy_pipeline_cache_path(),
2119			);
2120		}
2121	}
2122}
2123
2124impl RuntimeHandle {
2125	pub(crate) fn device_info(&self) -> crate::DeviceInfo {
2126		self.state.borrow().device.device_info()
2127	}
2128
2129	/// Borrow the selected device for resource creation and admission checks.
2130	pub(crate) fn descriptor_write_count(&self) -> u64 {
2131		self.state.borrow().device.descriptor_write_count()
2132	}
2133
2134	pub(crate) fn device(&self) -> Arc<Device> {
2135		self.state.borrow().device.clone()
2136	}
2137
2138	/// Record one extension-kernel dispatch admitted through `oa::compute`.
2139	/// See [`ExecutionSession::record_extension`].
2140	pub(crate) fn record_extension(
2141		&self,
2142		kernel: &crate::compute::Kernel,
2143		buffers: &[BufferBinding<'_>],
2144		push_constants: &[PushConstant],
2145		workgroups: [u32; 3],
2146	) -> Result<()> {
2147		let mut state = self.state.borrow_mut();
2148		let device = state.device.clone();
2149		state
2150			.session
2151			.record_extension(&device, kernel, buffers, push_constants, workgroups)
2152	}
2153
2154	pub(in crate::runtime) fn fusion_stats(&self) -> super::FusionStats {
2155		self.state.borrow().device.fusion_census().snapshot()
2156	}
2157
2158	/// Add one captured plan's DNN partition outcomes to the fusion census.
2159	pub(in crate::runtime) fn record_dnn_partitions(&self, applied: u32, fallback: u32) {
2160		self
2161			.state
2162			.borrow()
2163			.device
2164			.fusion_census()
2165			.dnn(applied, fallback);
2166	}
2167
2168	/// The admission profile of the selected device — whether descriptor
2169	/// indices baked into fused op tapes are bound-slot positions
2170	/// (Compatibility) or global heap indices (Core).
2171	pub(in crate::runtime) fn execution_profile(&self) -> super::device::features::ExecutionProfile {
2172		self.state.borrow().device.physical().profile
2173	}
2174
2175	/// Snapshot the device facts matmul planning reads.
2176	///
2177	/// The contract records queried limits plus the *enabled* capability
2178	/// surface so candidate legality never claims a feature that device
2179	/// admission left disabled.
2180	pub(in crate::runtime) fn matmul_device_contract(
2181		&self,
2182	) -> super::dna::provider::blas::MatmulDeviceContract {
2183		super::dna::provider::blas::MatmulDeviceContract::from_device(
2184			self.state.borrow().device.as_ref(),
2185		)
2186	}
2187
2188	/// Whether the enabled device capability surface admits FP16-storage
2189	/// lowering (`shaderFloat16` + 16-bit storage-buffer access). Reports the
2190	/// device contract only — the caller decides how a request is resolved.
2191	pub(crate) fn fp16_storage_capable(&self) -> bool {
2192		self.matmul_device_contract().caps_mask & super::dna::provider::blas::CAP_F16_STORAGE != 0
2193	}
2194
2195	/// Return the active runtime-scoped precision override, if a
2196	/// [`crate::ml::PrecisionScope`] is entered on this runtime.
2197	pub(crate) fn precision_override(&self) -> Option<crate::ml::StoragePrecision> {
2198		self.state.borrow().precision_override.get()
2199	}
2200
2201	/// Install or restore the runtime-scoped precision override and return the
2202	/// previous value. Never submits or waits on Vulkan work.
2203	pub(crate) fn replace_precision_override(
2204		&self,
2205		override_value: Option<crate::ml::StoragePrecision>,
2206	) -> Option<crate::ml::StoragePrecision> {
2207		self
2208			.state
2209			.borrow()
2210			.precision_override
2211			.replace(override_value)
2212	}
2213
2214	/// Admits and lazily builds one kernel's pipeline against the live device
2215	/// contract — the donor's plan revalidation immediately before recording.
2216	/// Provider-fused dispatches introduce kernels that source nodes never
2217	/// required, so lowering must admit them here rather than inferring
2218	/// availability from source-node admission.
2219	pub(in crate::runtime) fn require_kernel(
2220		&self,
2221		kernel: super::dna::kernel::KernelId,
2222	) -> Result<()> {
2223		self.state.borrow().device.require_kernel(kernel)
2224	}
2225
2226	/// Measured winner recorded for one exact route key, if any.
2227	///
2228	/// Returns `None` when the donor's `OA_DISABLE_GEMM_ROUTE_CACHE` opt-out is
2229	/// set; the flag is read once, matching the donor's cached env semantics.
2230	pub(in crate::runtime) fn matmul_measured_route(
2231		&self,
2232		key: &super::dna::provider::blas::MatmulRouteKey,
2233	) -> Option<u64> {
2234		if super::dna::provider::blas::measured_route_cache_disabled() {
2235			return None;
2236		}
2237		self.state.borrow().matmul_route_cache.query(key)
2238	}
2239
2240	pub(crate) fn owns_event(&self, event: &Event) -> bool {
2241		event.comes_from(&self.state.borrow().device)
2242	}
2243
2244	pub(crate) fn upload_native_rgba_image(
2245		&self,
2246		storage: &Storage,
2247		width: u32,
2248		height: u32,
2249	) -> Result<Rc<NativeRgbaImage>> {
2250		// A new host-written capture buffer has no GPU producer. Do not wait
2251		// unrelated encode/preview work before uploading it. Device-produced
2252		// buffers still flush and wait for their exact producing event.
2253		if storage.needs_flush() {
2254			self.flush()?;
2255		}
2256		storage.wait_ready()?;
2257		let mut state = self.state.borrow_mut();
2258		let image = Rc::new(NativeRgbaImage::new(&state.device, width, height)?);
2259		let buffer = storage
2260			.buffer()
2261			.ok_or_else(|| {
2262				Error::failed_precondition("native Texture upload requires non-empty storage")
2263			})?
2264			.raw();
2265		let handle = image.handle;
2266		let command = state.device.record_compute_commands(|command| {
2267			let range = vk::ImageSubresourceRange::new()
2268				.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2269				.set_level_count(1)
2270				.set_layer_count(1);
2271			let to_transfer = vk::ImageMemoryBarrier2::new()
2272				.set_src_stage_mask(vk::PipelineStageFlagBits2::NONE)
2273				.set_dst_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2274				.set_dst_access_mask(vk::AccessFlagBits2::TRANSFER_WRITE_BIT)
2275				.set_old_layout(vk::ImageLayout::UNDEFINED)
2276				.set_new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
2277				.set_image(handle)
2278				.set_subresource_range(range);
2279			let barriers = [to_transfer];
2280			unsafe {
2281				state.device.pipeline_barrier(
2282					command,
2283					&(vk::DependencyInfo::new()
2284						.set_image_memory_barriers(&barriers)
2285						.map_err(Error::from)?),
2286				)?;
2287			}
2288			let copy = vk::BufferImageCopy::new()
2289				.set_image_subresource(
2290					vk::ImageSubresourceLayers::new()
2291						.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2292						.set_layer_count(1),
2293				)
2294				.set_image_extent(vk::Extent3D {
2295					width,
2296					height,
2297					depth: 1,
2298				});
2299			unsafe {
2300				state.device.cmd_copy_buffer_to_image(
2301					command,
2302					buffer,
2303					handle,
2304					vk::ImageLayout::TRANSFER_DST_OPTIMAL,
2305					&[copy],
2306				)
2307			}?;
2308			let to_read = vk::ImageMemoryBarrier2::new()
2309				.set_src_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2310				.set_src_access_mask(vk::AccessFlagBits2::TRANSFER_WRITE_BIT)
2311				.set_dst_stage_mask(vk::PipelineStageFlagBits2::ALL_COMMANDS_BIT)
2312				.set_dst_access_mask(vk::AccessFlagBits2::SHADER_SAMPLED_READ_BIT)
2313				.set_old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
2314				.set_new_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
2315				.set_image(handle)
2316				.set_subresource_range(range);
2317			let barriers = [to_read];
2318			unsafe {
2319				state.device.pipeline_barrier(
2320					command,
2321					&(vk::DependencyInfo::new()
2322						.set_image_memory_barriers(&barriers)
2323						.map_err(Error::from)?),
2324				)?;
2325			}
2326			Ok(())
2327		})?;
2328		let event = submit_recorded(&mut state, command)?;
2329		drop(state);
2330		event.wait()?;
2331		Ok(image)
2332	}
2333
2334	pub(crate) fn same_as(&self, other: &Self) -> bool {
2335		Rc::ptr_eq(&self.state, &other.state)
2336	}
2337
2338	/// Create a `GraphicsPipeline` for the vertex-color lit 3D renderer.
2339	pub(crate) fn create_graphics_pipeline(&self) -> Result<GraphicsPipeline> {
2340		self.state.borrow().device.create_graphics_pipeline()
2341	}
2342
2343	/// Allocate a host-visible persistently-mapped mesh buffer.
2344	pub(crate) fn allocate_mesh_buffer(
2345		&self,
2346		size: usize,
2347		usage: vk::BufferUsageFlags,
2348	) -> Result<MeshBuffer> {
2349		self.state.borrow().device.allocate_mesh_buffer(size, usage)
2350	}
2351
2352	/// Allocate one `RenderTarget` (color + depth + readback) for the 3D renderer.
2353	pub(crate) fn allocate_render_target(&self, width: u32, height: u32) -> Result<RenderTarget> {
2354		let state = self.state.borrow();
2355		RenderTarget::new(&state.device, width, height)
2356	}
2357
2358	/// Copy immutable command entry points before recording borrows RuntimeState.
2359	/// This retains no additional device owner or mutable execution state.
2360	pub(crate) fn ui_sync_commands(&self) -> super::SyncCommands {
2361		self.state.borrow().device.sync_commands().clone()
2362	}
2363
2364	/// Copy the dynamic-rendering dispatch table for UI raster recording.
2365	pub(crate) fn ui_rendering_commands(&self) -> super::RenderingCommands {
2366		self.state.borrow().device.rendering_commands()
2367	}
2368
2369	pub(crate) fn require_ui_bindings(&self) -> Result<()> {
2370		self.state.borrow().device.require_ui_bindings()
2371	}
2372
2373	pub(crate) fn prepare_ui_sources(&self) -> Result<()> {
2374		self.flush_impl(FlushTiming::Untimed)?;
2375		Ok(())
2376	}
2377
2378	pub(in crate::runtime) fn validate_ui_presentation(&self, device: &Arc<Device>) -> Result<()> {
2379		let state = self.state.borrow();
2380		if !Arc::ptr_eq(&state.device, device) {
2381			return Err(Error::invalid_argument(
2382				"UI and Presenter belong to different Runtimes",
2383			));
2384		}
2385		if device.physical().graphics_queue_family != Some(device.physical().compute_queue_family) {
2386			return Err(Error::missing_capability(
2387				"UI presentation requires the unified compute/graphics family selected by RuntimeRequirements::presentation",
2388			));
2389		}
2390		Ok(())
2391	}
2392
2393	pub(crate) fn ui_buffer_info(&self, storage: &Storage) -> Result<vk::DescriptorBufferInfo> {
2394		let state = self.state.borrow();
2395		if !storage.belongs_to(&state.device) {
2396			return Err(Error::invalid_argument(
2397				"UI source belongs to another Runtime",
2398			));
2399		}
2400		let buffer = storage
2401			.buffer()
2402			.ok_or_else(|| Error::invalid_argument("UI source is empty"))?;
2403		Ok(
2404			vk::DescriptorBufferInfo::new()
2405				.set_buffer(buffer.raw())
2406				.set_range(buffer.size()),
2407		)
2408	}
2409
2410	/// Run `f` while holding the primary pipeline-cache synchronization lock.
2411	///
2412	/// `f` receives the primary cache handle (`NULL` when no driver cache is
2413	/// present). Holding the lock across every `vkCreate*Pipelines` call inside
2414	/// `f` satisfies Vulkan's external-synchronization requirement for the
2415	/// shared cache.
2416	///
2417	/// # Errors
2418	/// Returns an error when the pipeline-creation lock is poisoned or `f`
2419	/// fails.
2420	pub(crate) fn with_pipeline_cache<T>(
2421		&self,
2422		f: impl FnOnce(vk::PipelineCache) -> Result<T>,
2423	) -> Result<T> {
2424		let state = self.state.borrow();
2425		let cache = state.device.pipeline_cache()?;
2426		f(cache.raw())
2427	}
2428
2429	/// Return retained shared ownership of the Vulkan device for command recording.
2430	pub(crate) fn raw_device(&self) -> Arc<vk::Device> {
2431		self.state.borrow().device.raw_arc()
2432	}
2433
2434	/// Create a device-local R8G8B8A8_UNORM color-attachment image and its view.
2435	/// Returns `(raw_image, view)`; the allocation and view are retired by
2436	/// `destroy_compose_image`.
2437	pub(crate) fn create_compose_image(
2438		&self,
2439		width: u32,
2440		height: u32,
2441	) -> Result<(vk::Image, vk::ImageView)> {
2442		let state = self.state.borrow();
2443		let device = &state.device;
2444		let image_info = vk::ImageCreateInfo::new()
2445			.set_image_type(vk::ImageType::_2D)
2446			.set_format(vk::Format::R8G8B8A8_UNORM)
2447			.set_extent(vk::Extent3D {
2448				width,
2449				height,
2450				depth: 1,
2451			})
2452			.set_mip_levels(1)
2453			.set_array_layers(1)
2454			.set_samples(vk::SampleCountFlagBits::_1_BIT)
2455			.set_tiling(vk::ImageTiling::OPTIMAL)
2456			.set_usage(
2457				vk::ImageUsageFlagBits::COLOR_ATTACHMENT_BIT
2458					| vk::ImageUsageFlagBits::TRANSFER_SRC_BIT
2459					| vk::ImageUsageFlagBits::TRANSFER_DST_BIT,
2460			)
2461			.set_sharing_mode(vk::SharingMode::EXCLUSIVE)
2462			.set_initial_layout(vk::ImageLayout::UNDEFINED);
2463		let alloc_info =
2464			vk::mem::AllocationCreateInfo::new().set_usage(vk::mem::MemoryUsage::PreferDevice);
2465		let (image, mut alloc) = unsafe {
2466			device
2467				.allocator()
2468				.with_allocator(|a| a.create_image_with_options(&image_info, &alloc_info))
2469		}
2470		.map_err(|source| Error::backend_failure("Vulkan", "UI compose image allocation", source))?
2471		.map_err(Error::from)?;
2472		let view_info = vk::ImageViewCreateInfo::new()
2473			.set_image(image)
2474			.set_view_type(vk::ImageViewType::_2D)
2475			.set_format(vk::Format::R8G8B8A8_UNORM)
2476			.set_subresource_range(
2477				vk::ImageSubresourceRange::new()
2478					.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2479					.set_level_count(1)
2480					.set_layer_count(1),
2481			);
2482		let view = match unsafe { device.create_image_view(&view_info, None) } {
2483			Ok(view) => view,
2484			Err(source) => {
2485				unsafe {
2486					device
2487						.allocator()
2488						.with_allocator(|a| a.destroy_image(image, &mut alloc))
2489				}??;
2490				return Err(Error::backend_failure(
2491					"Vulkan",
2492					"UI compose image view creation",
2493					source,
2494				));
2495			}
2496		};
2497		// The allocation and view live in the runtime registry; the UI layer
2498		// owns the image lifetime and calls destroy_compose_image.
2499		state
2500			.compose_images
2501			.borrow_mut()
2502			.push(ComposeImageEntry { image, view, alloc });
2503		Ok((image, view))
2504	}
2505
2506	/// Destroy the compose image, its view, and its allocation.
2507	pub(crate) fn destroy_compose_image(&self, raw_image: vk::Image) {
2508		if let Ok(state) = self.state.try_borrow() {
2509			let mut entries = state.compose_images.borrow_mut();
2510			if let Some(pos) = entries.iter().position(|e| e.image == raw_image) {
2511				let mut entry = entries.swap_remove(pos);
2512				unsafe {
2513					let _ = state.device.destroy_image_view(entry.view, None);
2514					let _ = state
2515						.device
2516						.allocator()
2517						.destroy_image(entry.image, &mut entry.alloc);
2518				}
2519			}
2520		}
2521	}
2522
2523	/// Return the bindless storage-buffer index for runtime-owned storage.
2524	pub(crate) fn storage_descriptor_index(&self, storage: &Storage) -> Result<u32> {
2525		let state = self.state.borrow();
2526		let buffer = storage
2527			.buffer()
2528			.ok_or_else(|| Error::invalid_argument("UI source storage must not be empty"))?;
2529		if !storage.belongs_to(&state.device) {
2530			return Err(Error::invalid_argument(
2531				"UI source storage belongs to a different Runtime",
2532			));
2533		}
2534		Ok(buffer.descriptor_index())
2535	}
2536
2537	/// Record one UI raster composition followed by an exact RGBA8 readback.
2538	///
2539	/// The pass records on the graphics pool: `record` draws into `image` as a
2540	/// color attachment, then the same command buffer transitions it to
2541	/// TRANSFER_SRC and copies it into the returned readback storage.
2542	/// This is the private Vulkan seam used by the backend-neutral UI API. The
2543	/// returned storage becomes host-observable after the returned event completes.
2544	pub(crate) fn submit_ui_readback(
2545		&self,
2546		image: vk::Image,
2547		width: u32,
2548		height: u32,
2549		record: impl FnOnce(&vk::Device, vk::CommandBuffer) -> Result<()>,
2550	) -> Result<(Event, Storage)> {
2551		let byte_len = usize::try_from(width)
2552			.ok()
2553			.and_then(|w| usize::try_from(height).ok().and_then(|h| w.checked_mul(h)))
2554			.and_then(|pixels| pixels.checked_mul(4))
2555			.ok_or_else(|| Error::out_of_range("UI readback byte count overflows usize"))?;
2556		let mut state = self.state.borrow_mut();
2557		let readback = Storage::new_from_bytes(&state.device, &vec![0_u8; byte_len])?;
2558		let readback_buffer = readback
2559			.buffer()
2560			.ok_or_else(|| Error::internal("non-empty UI readback has no Vulkan buffer"))?
2561			.raw();
2562		let device = state.device.clone();
2563		let command = device.record_presentation_commands(|command_buffer| {
2564			record(device.raw(), command_buffer)?;
2565			let range = vk::ImageSubresourceRange::new()
2566				.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2567				.set_level_count(1)
2568				.set_layer_count(1);
2569			let to_copy = vk::ImageMemoryBarrier2::new()
2570				.set_src_stage_mask(vk::PipelineStageFlagBits2::COLOR_ATTACHMENT_OUTPUT_BIT)
2571				.set_src_access_mask(vk::AccessFlagBits2::COLOR_ATTACHMENT_WRITE_BIT)
2572				.set_dst_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2573				.set_dst_access_mask(vk::AccessFlagBits2::TRANSFER_READ_BIT)
2574				.set_old_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
2575				.set_new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
2576				.set_image(image)
2577				.set_subresource_range(range);
2578			unsafe {
2579				device.pipeline_barrier(
2580					command_buffer,
2581					&(vk::DependencyInfo::new()
2582						.set_image_memory_barriers(std::slice::from_ref(&to_copy))
2583						.map_err(Error::from)?),
2584				)?;
2585				device.cmd_copy_image_to_buffer(
2586					command_buffer,
2587					image,
2588					vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
2589					readback_buffer,
2590					&[vk::BufferImageCopy::new()
2591						.set_image_subresource(
2592							vk::ImageSubresourceLayers::new()
2593								.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2594								.set_layer_count(1),
2595						)
2596						.set_image_extent(vk::Extent3D {
2597							width,
2598							height,
2599							depth: 1,
2600						})],
2601				)?;
2602			}
2603			Ok(())
2604		})?;
2605		let event = submit_recorded(&mut state, command)?;
2606		readback.mark_submitted(event.clone());
2607		Ok((event, readback))
2608	}
2609
2610	/// Record one mesh draw into `target` and submit it on the graphics queue.
2611	///
2612	/// `push_data` is raw push-constant bytes; `push_stages` selects which
2613	/// shader stages are visible to those bytes.
2614	#[allow(clippy::too_many_arguments)]
2615	pub(crate) fn record_and_submit_mesh_frame(
2616		&self,
2617		target: &mut RenderTarget,
2618		vertex_buf: &MeshBuffer,
2619		index_buf: &MeshBuffer,
2620		index_count: u32,
2621		clear_color: [f32; 4],
2622		push_data: &[u8],
2623		push_stages: vk::ShaderStageFlags,
2624		pipeline: vk::Pipeline,
2625		pipeline_layout: vk::PipelineLayout,
2626		descriptor_sets: &[vk::DescriptorSet],
2627	) -> Result<Event> {
2628		let mut state = self.state.borrow_mut();
2629		let command = state.device.record_mesh_frame(
2630			target,
2631			vertex_buf.raw(),
2632			index_buf.raw(),
2633			index_count,
2634			clear_color,
2635			push_data,
2636			push_stages,
2637			pipeline,
2638			pipeline_layout,
2639			descriptor_sets,
2640		)?;
2641		submit_recorded(&mut state, command)
2642	}
2643
2644	/// Record one vertexless graphics frame and submit it on the graphics queue.
2645	///
2646	/// No vertex or index buffers are bound; the vertex shader derives
2647	/// geometry from `SV_VertexID` (fullscreen-triangle pipelines such as the
2648	/// canvas grid).
2649	#[allow(clippy::too_many_arguments)]
2650	pub(crate) fn record_and_submit_vertexless_frame(
2651		&self,
2652		target: &mut RenderTarget,
2653		vertex_count: u32,
2654		clear_color: [f32; 4],
2655		push_data: &[u8],
2656		push_stages: vk::ShaderStageFlags,
2657		pipeline: vk::Pipeline,
2658		pipeline_layout: vk::PipelineLayout,
2659		descriptor_sets: &[vk::DescriptorSet],
2660	) -> Result<Event> {
2661		let mut state = self.state.borrow_mut();
2662		let command = state.device.record_vertexless_frame(
2663			target,
2664			vertex_count,
2665			clear_color,
2666			push_data,
2667			push_stages,
2668			pipeline,
2669			pipeline_layout,
2670			descriptor_sets,
2671		)?;
2672		submit_recorded(&mut state, command)
2673	}
2674
2675	/// Record one scene frame (multiple draws) and submit it on the graphics queue.
2676	///
2677	/// `draws` is sorted so that opaque entries come before blend entries by the
2678	/// caller. Both opaque and blend commands share `pipeline_layout`; the device
2679	/// function switches to `blend_pipeline` for entries with `is_blend == true`.
2680	#[allow(clippy::too_many_arguments)]
2681	pub(crate) fn record_and_submit_scene_frame(
2682		&self,
2683		target: &mut RenderTarget,
2684		vertex_buf: &MeshBuffer,
2685		index_buf: &MeshBuffer,
2686		clear_color: [f32; 4],
2687		push_stages: vk::ShaderStageFlags,
2688		pipeline: vk::Pipeline,
2689		blend_pipeline: vk::Pipeline,
2690		pipeline_layout: vk::PipelineLayout,
2691		scene_set: vk::DescriptorSet,
2692		draws: &[SceneDrawCmd],
2693	) -> Result<Event> {
2694		let mut state = self.state.borrow_mut();
2695		let command = state.device.record_scene_frame(
2696			target,
2697			vertex_buf.raw(),
2698			index_buf.raw(),
2699			clear_color,
2700			push_stages,
2701			pipeline,
2702			blend_pipeline,
2703			pipeline_layout,
2704			scene_set,
2705			draws,
2706		)?;
2707		submit_recorded(&mut state, command)
2708	}
2709
2710	/// Create the flat-color material Vulkan pipeline, borrowing the device.
2711	pub(crate) fn create_flat_color_pipeline(&self) -> Result<GraphicsPipeline> {
2712		self.state.borrow().device.create_flat_color_pipeline()
2713	}
2714
2715	/// Create the procedural canvas-grid Vulkan pipeline, borrowing the device.
2716	pub(crate) fn create_canvas_grid_pipeline(&self) -> Result<GraphicsPipeline> {
2717		self.state.borrow().device.create_canvas_grid_pipeline()
2718	}
2719
2720	/// Create the owned descriptor set layouts for the unlit pipeline.
2721	pub(crate) fn create_unlit_descriptor_layouts(&self) -> Result<UnlitDescriptorLayouts> {
2722		self.state.borrow().device.create_unlit_descriptor_layouts()
2723	}
2724
2725	pub(crate) fn create_unlit_descriptor_arena(
2726		&self,
2727		layout: vk::DescriptorSetLayout,
2728		set_count: u32,
2729	) -> Result<UnlitDescriptorArena> {
2730		self
2731			.state
2732			.borrow()
2733			.device
2734			.create_unlit_descriptor_arena(layout, set_count)
2735	}
2736
2737	/// Create the owned descriptor set layouts for the Surface pipeline.
2738	pub(crate) fn create_surface_descriptor_layouts(&self) -> Result<SurfaceDescriptorLayouts> {
2739		self
2740			.state
2741			.borrow()
2742			.device
2743			.create_surface_descriptor_layouts()
2744	}
2745
2746	pub(crate) fn create_surface_descriptor_arena(
2747		&self,
2748		scene_layout: vk::DescriptorSetLayout,
2749		material_layout: vk::DescriptorSetLayout,
2750		set_count: u32,
2751		max_materials_per_slot: u32,
2752	) -> Result<SurfaceDescriptorArena> {
2753		self.state.borrow().device.create_surface_descriptor_arena(
2754			scene_layout,
2755			material_layout,
2756			set_count,
2757			max_materials_per_slot,
2758		)
2759	}
2760
2761	/// Create the unlit textured Vulkan pipeline, borrowing the device.
2762	pub(crate) fn create_unlit_pipeline(
2763		&self,
2764		sampler_layout: vk::DescriptorSetLayout,
2765	) -> Result<GraphicsPipeline> {
2766		self
2767			.state
2768			.borrow()
2769			.device
2770			.create_unlit_pipeline(sampler_layout)
2771	}
2772
2773	/// Create the Surface PBR Vulkan pipeline, borrowing the device.
2774	pub(crate) fn create_surface_pipeline(
2775		&self,
2776		scene_layout: vk::DescriptorSetLayout,
2777		material_layout: vk::DescriptorSetLayout,
2778	) -> Result<GraphicsPipeline> {
2779		self
2780			.state
2781			.borrow()
2782			.device
2783			.create_surface_pipeline(scene_layout, material_layout)
2784	}
2785
2786	/// Create the Surface transparent-blend pipeline, borrowing the device.
2787	///
2788	/// Reuses the `layout` from the opaque Surface pipeline so the
2789	/// descriptor sets remain compatible.
2790	pub(crate) fn create_surface_blend_pipeline(
2791		&self,
2792		layout: vk::PipelineLayout,
2793	) -> Result<GraphicsPipeline> {
2794		self
2795			.state
2796			.borrow()
2797			.device
2798			.create_surface_blend_pipeline(layout)
2799	}
2800
2801	pub(crate) fn create_storage(&self, bytes: &[u8]) -> Result<Storage> {
2802		let mut state = self.state.borrow_mut();
2803		let device = state.device.clone();
2804		state.session.create_storage(&device, bytes)
2805	}
2806
2807	pub(crate) fn validate_storage_owner(&self, storage: &Storage) -> Result<()> {
2808		if !storage.belongs_to(&self.state.borrow().device) {
2809			return Err(Error::invalid_argument(
2810				"storage belongs to a different Runtime",
2811			));
2812		}
2813		Ok(())
2814	}
2815
2816	pub(crate) fn create_output_storage(&self, byte_len: usize) -> Result<Storage> {
2817		let mut state = self.state.borrow_mut();
2818		let device = state.device.clone();
2819		state.session.create_output_storage(&device, byte_len)
2820	}
2821
2822	pub(crate) fn begin_stable_resource_frame(&self) -> Result<()> {
2823		self
2824			.state
2825			.borrow_mut()
2826			.session
2827			.begin_stable_resource_frame()
2828	}
2829
2830	pub(crate) fn seal_all_stable_resources_external(&self) -> Result<()> {
2831		self
2832			.state
2833			.borrow_mut()
2834			.session
2835			.seal_all_stable_resources_external()
2836	}
2837
2838	pub(crate) fn seal_stable_resource_inputs(&self) -> Result<()> {
2839		self
2840			.state
2841			.borrow_mut()
2842			.session
2843			.seal_stable_resource_inputs()
2844	}
2845
2846	pub(crate) fn end_stable_resource_frame(&self) {
2847		self.state.borrow_mut().session.end_stable_resource_frame();
2848	}
2849
2850	pub(crate) fn has_pending_work(&self) -> bool {
2851		!self.state.borrow().session.is_empty()
2852	}
2853
2854	pub(crate) fn abort_pending_work(&self) {
2855		self.state.borrow_mut().session.abort();
2856	}
2857
2858	pub(super) fn create_alias_arena(&self, size: usize) -> Result<Buffer> {
2859		let device = self.state.borrow().device.clone();
2860		Buffer::host_visible_alias_arena(&device, size)
2861	}
2862
2863	pub(super) fn release_stable_transient_resources(&self, retired: &[Buffer]) {
2864		self
2865			.state
2866			.borrow_mut()
2867			.session
2868			.release_stable_transient_resources(retired);
2869	}
2870
2871	pub(crate) fn capture_active(&self) -> bool {
2872		self.state.borrow().capture_active
2873	}
2874
2875	pub(crate) fn capture_generation(&self) -> Option<u64> {
2876		let state = self.state.borrow();
2877		state.capture_active.then_some(state.capture_generation)
2878	}
2879
2880	pub(crate) fn begin_semantic_lowering(&self) -> Result<SemanticLoweringScope> {
2881		self.state.borrow_mut().session.begin_semantic_lowering()?;
2882		Ok(SemanticLoweringScope {
2883			runtime: self.clone(),
2884			active: true,
2885		})
2886	}
2887
2888	/// Begin a deferred secret-lowering batch. While the returned scope is
2889	/// active, every recorded submission on this runtime defers into the
2890	/// scope's ordered batch instead of queueing; `commit` submits it in
2891	/// order and `Drop` abandons it without submission or waiting.
2892	pub(crate) fn begin_secret_lowering(&self) -> Result<SecretLoweringScope> {
2893		{
2894			let state = self.state.borrow();
2895			if state.capture_active {
2896				return Err(Error::failed_precondition(
2897					"secret lowering cannot begin during capture",
2898				));
2899			}
2900			if state.secret_scope.is_some() {
2901				return Err(Error::failed_precondition(
2902					"a secret lowering scope is already active",
2903				));
2904			}
2905		}
2906		let mut state = self.state.borrow_mut();
2907		state.secret_scope = Some(SecretScopeState {
2908			pending: Vec::new(),
2909			nodes: Vec::new(),
2910		});
2911		Ok(SecretLoweringScope {
2912			runtime: self.clone(),
2913			active: true,
2914		})
2915	}
2916
2917	#[cfg_attr(
2918		not(test),
2919		expect(
2920			dead_code,
2921			reason = "private PQC ownership substrate; no secret algorithm is admitted"
2922		)
2923	)]
2924	pub(super) fn allocate_secret_buffer(&self, bytes: usize) -> Result<SecretBuffer> {
2925		let state = self.state.borrow();
2926		if state.capture_active {
2927			return Err(Error::failed_precondition(
2928				"secret allocation cannot enter capture",
2929			));
2930		}
2931		SecretBuffer::new(&state.device, bytes)
2932	}
2933
2934	#[cfg_attr(
2935		not(test),
2936		expect(
2937			dead_code,
2938			reason = "private PQC ownership substrate; no secret algorithm is admitted"
2939		)
2940	)]
2941	pub(super) fn erase_secret_buffer(
2942		&self,
2943		secret: SecretBuffer,
2944		final_consumer: &Event,
2945	) -> Result<SecretErasure> {
2946		{
2947			let state = self.state.borrow();
2948			if state.capture_active {
2949				return Err(Error::failed_precondition(
2950					"secret erasure cannot enter capture",
2951				));
2952			}
2953			if !secret.belongs_to(&state.device) || !final_consumer.comes_from(&state.device) {
2954				return Err(Error::invalid_argument(
2955					"secret erasure requires its originating Runtime",
2956				));
2957			}
2958		}
2959		// Flush only at this explicit execution boundary. Queue submission waits
2960		// on the preceding runtime epoch, including the exact final consumer.
2961		self.flush_impl(FlushTiming::Untimed)?;
2962		let mut state = self.state.borrow_mut();
2963		let (command, witness) = secret.record_erasure()?;
2964		let event = submit_recorded(&mut state, command)?;
2965		Ok(SecretErasure::new(event, witness))
2966	}
2967
2968	#[cfg_attr(
2969		not(test),
2970		expect(
2971			dead_code,
2972			reason = "private entropy execution; no secret algorithm is admitted"
2973		)
2974	)]
2975	pub(super) fn consume_secret_entropy<const N: usize>(
2976		&self,
2977		entropy: crate::crypto::entropy::Entropy<N>,
2978		consumer: impl FnOnce(&Arc<Device>, vk::CommandBuffer, SecretBinding<'_>) -> Result<()>,
2979	) -> Result<SecretErasure> {
2980		if self.state.borrow().capture_active {
2981			return Err(Error::failed_precondition(
2982				"secret entropy cannot enter capture",
2983			));
2984		}
2985		self.flush_impl(FlushTiming::Untimed)?;
2986		entropy.consume(|bytes| {
2987			let mut state = self.state.borrow_mut();
2988			let secret = SecretBuffer::new(&state.device, N)?;
2989			let (command, witness) = secret.record_entropy_consumer(bytes, consumer)?;
2990			let event = submit_recorded(&mut state, command)?;
2991			Ok(SecretErasure::new(event, witness))
2992		})
2993	}
2994
2995	/// Private qualification route, not public long-lived key generation.
2996	/// Returns only the public encoding and exact erasure of seed/private storage.
2997	#[cfg_attr(
2998		not(test),
2999		expect(dead_code, reason = "ML-KEM secret operation admission is planned")
3000	)]
3001	pub(super) fn prove_mlkem_keygen(
3002		&self,
3003		k: u32,
3004		entropy: crate::crypto::entropy::Entropy<64>,
3005	) -> Result<(Buffer, SecretErasure)> {
3006		if !(2..=4).contains(&k) {
3007			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3008		}
3009		if self.state.borrow().capture_active {
3010			return Err(Error::failed_precondition(
3011				"ML-KEM secret execution cannot enter capture",
3012			));
3013		}
3014		self
3015			.state
3016			.borrow()
3017			.device
3018			.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemKeygenU8)?;
3019		self.flush_impl(FlushTiming::Untimed)?;
3020		entropy.consume(|bytes| {
3021			let mut state = self.state.borrow_mut();
3022			let public = Buffer::host_visible_storage(
3023				&state.device,
3024				usize::try_from(384 * k + 32)
3025					.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?,
3026			)?;
3027			let private = SecretBuffer::new(
3028				&state.device,
3029				usize::try_from(768 * k + 96)
3030					.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?,
3031			)?;
3032			let seed = SecretBuffer::new(&state.device, 64)?;
3033			let (command, witness) = seed.record_mlkem_keygen(bytes, private, &public, k)?;
3034			let event = submit_recorded(&mut state, command)?;
3035			Ok((public, SecretErasure::new(event, witness)))
3036		})
3037	}
3038
3039	/// Private asynchronous keygen: key readiness and entropy erasure are exact
3040	/// evidence from the same submission. Secret storage never leaves this module.
3041	pub(super) fn generate_mlkem_key(
3042		&self,
3043		k: u32,
3044		entropy: crate::crypto::entropy::Entropy<64>,
3045	) -> Result<(MlKemDeviceKey, SecretErasure)> {
3046		if !(2..=4).contains(&k) {
3047			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3048		}
3049		{
3050			let state = self.state.borrow();
3051			if state.capture_active {
3052				return Err(Error::failed_precondition(
3053					"ML-KEM secret execution cannot enter capture",
3054				));
3055			}
3056			state
3057				.device
3058				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemKeygenU8)?;
3059		}
3060		self.flush_impl(FlushTiming::Untimed)?;
3061		entropy.consume(|bytes| {
3062			let mut state = self.state.borrow_mut();
3063			let public = Buffer::host_visible_storage(
3064				&state.device,
3065				usize::try_from(384 * k + 32)
3066					.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?,
3067			)?;
3068			let private = Arc::new(SecretBuffer::new(
3069				&state.device,
3070				usize::try_from(768 * k + 96)
3071					.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?,
3072			)?);
3073			let seed = SecretBuffer::new(&state.device, 64)?;
3074			let (command, witness) = seed.record_mlkem_retained_keygen(bytes, &private, &public, k)?;
3075			let ready = submit_recorded(&mut state, command)?;
3076			let erasure = SecretErasure::new(ready.clone(), witness);
3077			Ok((
3078				MlKemDeviceKey {
3079					runtime: self.clone(),
3080					private,
3081					public,
3082					k,
3083					ready,
3084				},
3085				erasure,
3086			))
3087		})
3088	}
3089
3090	/// Import caller-supplied FIPS 203 decapsulation-key bytes. The encapsulation
3091	/// key embedded in dk supplies the public transport through a fresh exclusive
3092	/// buffer. Import reports an upload boundary, not a key-validity proof.
3093	pub(super) fn import_mlkem_key(
3094		&self,
3095		k: u32,
3096		decapsulation_key: &[u8],
3097	) -> Result<(MlKemDeviceKey, SecretErasure)> {
3098		if !(2..=4).contains(&k) {
3099			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3100		}
3101		let private_len = usize::try_from(768 * k + 96)
3102			.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?;
3103		let public_len = usize::try_from(384 * k + 32)
3104			.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?;
3105		if decapsulation_key.len() != private_len {
3106			return Err(Error::invalid_argument(
3107				"ML-KEM decapsulation-key extent mismatch",
3108			));
3109		}
3110		{
3111			let state = self.state.borrow();
3112			if state.capture_active {
3113				return Err(Error::failed_precondition(
3114					"ML-KEM secret execution cannot enter capture",
3115				));
3116			}
3117		}
3118		self.flush_impl(FlushTiming::Untimed)?;
3119		let mut state = self.state.borrow_mut();
3120		let public = Buffer::host_visible_storage(&state.device, public_len)?;
3121		// FIPS 203 dk is dkPKE (384k) || ek (384k+32) || H(ek) || z; the ek
3122		// range is public material by construction.
3123		let ek_offset = usize::try_from(384 * k)
3124			.map_err(|_| Error::invalid_argument("ML-KEM public offset overflow"))?;
3125		public.write(0, &decapsulation_key[ek_offset..ek_offset + public_len])?;
3126		let private = Arc::new(SecretBuffer::new(&state.device, private_len)?);
3127		let (command, witness) = private.record_secret_import(decapsulation_key, |_, _| Ok(()))?;
3128		let ready = submit_recorded(&mut state, command)?;
3129		let erasure = SecretErasure::new(ready.clone(), witness);
3130		Ok((
3131			MlKemDeviceKey {
3132				runtime: self.clone(),
3133				private,
3134				public,
3135				k,
3136				ready,
3137			},
3138			erasure,
3139		))
3140	}
3141
3142	/// Explicit consuming boundary. Submission order includes key generation
3143	/// and all previous consumers; failure leaves storage quarantined.
3144	pub(super) fn erase_mlkem_key(&self, key: MlKemDeviceKey) -> Result<SecretErasure> {
3145		{
3146			let state = self.state.borrow();
3147			if state.capture_active {
3148				return Err(Error::failed_precondition(
3149					"ML-KEM secret erasure cannot enter capture",
3150				));
3151			}
3152			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3153				|| !key.private.belongs_to(&state.device)
3154				|| !key.ready.comes_from(&state.device)
3155			{
3156				return Err(Error::invalid_argument(
3157					"ML-KEM key requires its originating Runtime",
3158				));
3159			}
3160		}
3161		self.flush_impl(FlushTiming::Untimed)?;
3162		let mut state = self.state.borrow_mut();
3163		let (command, witness) = key.private.record_retained_erasure()?;
3164		let event = submit_recorded(&mut state, command)?;
3165		Ok(SecretErasure::new(event, witness))
3166	}
3167
3168	pub(super) fn generate_mldsa_key(
3169		&self,
3170		parameter: u32,
3171		entropy: crate::crypto::entropy::Entropy<32>,
3172	) -> Result<(MlDsaDeviceKey, SecretErasure)> {
3173		let (seed_len, public_len, private_len) =
3174			super::dna::kernel::KernelId::mldsa_keygen_layout(parameter)
3175				.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3176		{
3177			let state = self.state.borrow();
3178			if state.capture_active {
3179				return Err(Error::failed_precondition(
3180					"ML-DSA secret execution cannot enter capture",
3181				));
3182			}
3183			state
3184				.device
3185				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaKeygenU8)?;
3186		}
3187		self.flush_impl(FlushTiming::Untimed)?;
3188		entropy.consume(|bytes| {
3189			let mut state = self.state.borrow_mut();
3190			let public = Buffer::host_visible_storage(
3191				&state.device,
3192				usize::try_from(public_len)
3193					.map_err(|_| Error::invalid_argument("ML-DSA public extent overflow"))?,
3194			)?;
3195			let private = Arc::new(SecretBuffer::new(
3196				&state.device,
3197				usize::try_from(private_len)
3198					.map_err(|_| Error::invalid_argument("ML-DSA private extent overflow"))?,
3199			)?);
3200			let seed = SecretBuffer::new(
3201				&state.device,
3202				usize::try_from(seed_len)
3203					.map_err(|_| Error::invalid_argument("ML-DSA seed extent overflow"))?,
3204			)?;
3205			let (command, witness) =
3206				seed.record_mldsa_retained_keygen(bytes, &private, &public, parameter)?;
3207			let ready = submit_recorded(&mut state, command)?;
3208			let erasure = SecretErasure::new(ready.clone(), witness);
3209			Ok((
3210				MlDsaDeviceKey {
3211					runtime: self.clone(),
3212					private,
3213					public,
3214					parameter,
3215					ready,
3216				},
3217				erasure,
3218			))
3219		})
3220	}
3221
3222	/// Import caller-supplied FIPS 204 signing-key bytes with their public key.
3223	/// The public value is copied into fresh exclusive storage in the same
3224	/// submission, so later caller-side mutation cannot alias the retained key.
3225	/// Import reports an upload boundary, not a key-pair consistency proof.
3226	pub(super) fn import_mldsa_key(
3227		&self,
3228		parameter: u32,
3229		secret_key: &[u8],
3230		public_key: &Buffer,
3231	) -> Result<(MlDsaDeviceKey, SecretErasure)> {
3232		let (_, public_len, private_len) = super::dna::kernel::KernelId::mldsa_keygen_layout(parameter)
3233			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3234		let private_len = usize::try_from(private_len)
3235			.map_err(|_| Error::invalid_argument("ML-DSA private extent overflow"))?;
3236		let public_len = usize::try_from(public_len)
3237			.map_err(|_| Error::invalid_argument("ML-DSA public extent overflow"))?;
3238		if secret_key.len() != private_len || public_key.byte_len() != public_len {
3239			return Err(Error::invalid_argument("ML-DSA key extent mismatch"));
3240		}
3241		{
3242			let state = self.state.borrow();
3243			if state.capture_active {
3244				return Err(Error::failed_precondition(
3245					"ML-DSA secret execution cannot enter capture",
3246				));
3247			}
3248			if !public_key.belongs_to(&state.device) {
3249				return Err(Error::invalid_argument(
3250					"ML-DSA public key requires the same Runtime device",
3251				));
3252			}
3253		}
3254		self.flush_impl(FlushTiming::Untimed)?;
3255		let mut state = self.state.borrow_mut();
3256		let public = Buffer::host_visible_storage(&state.device, public_len)?;
3257		let private = Arc::new(SecretBuffer::new(&state.device, private_len)?);
3258		let (command, witness) = private.record_secret_import(secret_key, |device, command| {
3259			// SAFETY: both public buffers are live, disjoint, equally sized and
3260			// carry transfer usage; the barrier above already orders the copy.
3261			unsafe {
3262				device.cmd_copy_buffer(
3263					command,
3264					public_key.raw(),
3265					public.raw(),
3266					&[vk::BufferCopy::new().set_size(public_len as u64)],
3267				)?;
3268			}
3269			Ok(())
3270		})?;
3271		let ready = submit_recorded(&mut state, command)?;
3272		let erasure = SecretErasure::new(ready.clone(), witness);
3273		Ok((
3274			MlDsaDeviceKey {
3275				runtime: self.clone(),
3276				private,
3277				public,
3278				parameter,
3279				ready,
3280			},
3281			erasure,
3282		))
3283	}
3284
3285	/// Explicit consuming boundary. Submission order includes key generation
3286	/// and all previous consumers; failure leaves storage quarantined.
3287	pub(super) fn erase_mldsa_key(&self, key: MlDsaDeviceKey) -> Result<SecretErasure> {
3288		{
3289			let state = self.state.borrow();
3290			if state.capture_active {
3291				return Err(Error::failed_precondition(
3292					"ML-DSA secret erasure cannot enter capture",
3293				));
3294			}
3295			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3296				|| !key.private.belongs_to(&state.device)
3297				|| !key.public.belongs_to(&state.device)
3298				|| !key.ready.comes_from(&state.device)
3299			{
3300				return Err(Error::invalid_argument(
3301					"ML-DSA key requires its originating Runtime",
3302				));
3303			}
3304		}
3305		self.flush_impl(FlushTiming::Untimed)?;
3306		let mut state = self.state.borrow_mut();
3307		let (command, witness) = key.private.record_retained_erasure()?;
3308		let event = submit_recorded(&mut state, command)?;
3309		Ok(SecretErasure::new(event, witness))
3310	}
3311
3312	/// Private FIPS 204 internal-mu interface. The 64-byte public representative
3313	/// is already H(tr || M', 64); raw messages require separate framing.
3314	/// Returns public signature storage (zero on failure), a public success word,
3315	/// and exact entropy-erasure completion. No rejection count is exposed.
3316	#[cfg_attr(
3317		not(test),
3318		expect(dead_code, reason = "private ML-DSA signing integration")
3319	)]
3320	pub(super) fn sign_mldsa_mu(
3321		&self,
3322		key: &MlDsaDeviceKey,
3323		mu: &Buffer,
3324		entropy: crate::crypto::entropy::Entropy<32>,
3325	) -> Result<(Buffer, Buffer, SecretErasure)> {
3326		let (seed_len, _, mu_len, sig_len) =
3327			super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3328				.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3329		{
3330			let state = self.state.borrow();
3331			if state.capture_active {
3332				return Err(Error::failed_precondition(
3333					"ML-DSA secret execution cannot enter capture",
3334				));
3335			}
3336			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3337				|| !key.private.belongs_to(&state.device)
3338				|| !key.public.belongs_to(&state.device)
3339				|| !key.ready.comes_from(&state.device)
3340				|| !mu.belongs_to(&state.device)
3341				|| mu.size() != mu_len
3342			{
3343				return Err(Error::invalid_argument(
3344					"ML-DSA signing ownership or mu extent mismatch",
3345				));
3346			}
3347			state
3348				.device
3349				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3350		}
3351		self.flush_impl(FlushTiming::Untimed)?;
3352		entropy.consume(|bytes| {
3353			let mut state = self.state.borrow_mut();
3354			let signature = Buffer::host_visible_storage(
3355				&state.device,
3356				usize::try_from((sig_len + 3) & !3)
3357					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3358			)?;
3359			let status = Buffer::host_visible_storage(&state.device, 4)?;
3360			let seed = SecretBuffer::new(
3361				&state.device,
3362				usize::try_from(seed_len)
3363					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3364			)?;
3365			let (command, witness) = seed.record_mldsa_sign(
3366				bytes,
3367				&key.private,
3368				[mu, &signature, &status],
3369				key.parameter,
3370			)?;
3371			let event = submit_recorded(&mut state, command)?;
3372			Ok((signature, status, SecretErasure::new(event, witness)))
3373		})
3374	}
3375
3376	/// Private pure ML-DSA signing. Message/context storage is public, packed
3377	/// and padded to at least one complete word; lengths exclude padding.
3378	/// The device forms H(tr || 0 || context length || context || message, 64).
3379	/// No host key readback, internal-message mode or prehash mode is implied.
3380	pub(super) fn sign_mldsa_message(
3381		&self,
3382		key: &MlDsaDeviceKey,
3383		message: &Buffer,
3384		context: &Buffer,
3385		lengths: [u32; 2],
3386		entropy: crate::crypto::entropy::Entropy<32>,
3387	) -> Result<(Buffer, Buffer, SecretErasure)> {
3388		let (seed_len, _, _, sig_len) = super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3389			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3390		if lengths[1] > 255 {
3391			return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
3392		}
3393		let extents = lengths.map(|length| length.checked_add(3).map(|n| u64::from((n & !3).max(4))));
3394		let [Some(message_extent), Some(context_extent)] = extents else {
3395			return Err(Error::invalid_argument("ML-DSA input extent overflow"));
3396		};
3397		{
3398			let state = self.state.borrow();
3399			if state.capture_active {
3400				return Err(Error::failed_precondition(
3401					"ML-DSA secret execution cannot enter capture",
3402				));
3403			}
3404			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3405				|| !key.private.belongs_to(&state.device)
3406				|| !key.public.belongs_to(&state.device)
3407				|| !key.ready.comes_from(&state.device)
3408				|| !message.belongs_to(&state.device)
3409				|| !context.belongs_to(&state.device)
3410				|| message.size() != message_extent
3411				|| context.size() != context_extent
3412				|| message.raw() == context.raw()
3413			{
3414				return Err(Error::invalid_argument(
3415					"ML-DSA signing ownership, alias or input extent mismatch",
3416				));
3417			}
3418			state
3419				.device
3420				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaMuU8)?;
3421			state
3422				.device
3423				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3424		}
3425		self.flush_impl(FlushTiming::Untimed)?;
3426		entropy.consume(|bytes| {
3427			let mut state = self.state.borrow_mut();
3428			let signature = Buffer::host_visible_storage(
3429				&state.device,
3430				usize::try_from((sig_len + 3) & !3)
3431					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3432			)?;
3433			let status = Buffer::host_visible_storage(&state.device, 4)?;
3434			let seed = SecretBuffer::new(
3435				&state.device,
3436				usize::try_from(seed_len)
3437					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3438			)?;
3439			let (command, witness) = seed.record_mldsa_sign_message(
3440				bytes,
3441				&key.private,
3442				&key.public,
3443				[message, context, &signature, &status],
3444				key.parameter,
3445				lengths,
3446			)?;
3447			let event = submit_recorded(&mut state, command)?;
3448			Ok((signature, status, SecretErasure::new(event, witness)))
3449		})
3450	}
3451
3452	/// Private HashML-DSA framing for a precomputed public digest. The generated
3453	/// NIST hash identity fixes its length and OID. This does not compute the
3454	/// prehash, admit a FIPS-validated module or imply full hash-family coverage.
3455	pub(super) fn sign_mldsa_prehashed(
3456		&self,
3457		key: &MlDsaDeviceKey,
3458		digest: &Buffer,
3459		context: &Buffer,
3460		algorithm: u32,
3461		context_length: u32,
3462		entropy: crate::crypto::entropy::Entropy<32>,
3463	) -> Result<(Buffer, Buffer, SecretErasure)> {
3464		let (seed_len, _, _, sig_len) = super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3465			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3466		if context_length > 255 {
3467			return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
3468		}
3469		let digest_extent = super::dna::kernel::KernelId::mldsa_prehash_bytes(algorithm)
3470			.ok_or_else(|| Error::invalid_argument("ML-DSA prehash identity is unknown"))?;
3471		let context_extent = u64::from(((context_length + 3) & !3).max(4));
3472		{
3473			let state = self.state.borrow();
3474			if state.capture_active {
3475				return Err(Error::failed_precondition(
3476					"ML-DSA secret execution cannot enter capture",
3477				));
3478			}
3479			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3480				|| !key.private.belongs_to(&state.device)
3481				|| !key.public.belongs_to(&state.device)
3482				|| !key.ready.comes_from(&state.device)
3483				|| !digest.belongs_to(&state.device)
3484				|| !context.belongs_to(&state.device)
3485				|| digest.size() != digest_extent
3486				|| context.size() != context_extent
3487				|| digest.raw() == context.raw()
3488			{
3489				return Err(Error::invalid_argument(
3490					"ML-DSA signing ownership, alias or input extent mismatch",
3491				));
3492			}
3493			state
3494				.device
3495				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaMuU8)?;
3496			state
3497				.device
3498				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3499		}
3500		self.flush_impl(FlushTiming::Untimed)?;
3501		entropy.consume(|bytes| {
3502			let mut state = self.state.borrow_mut();
3503			let signature = Buffer::host_visible_storage(
3504				&state.device,
3505				usize::try_from((sig_len + 3) & !3)
3506					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3507			)?;
3508			let status = Buffer::host_visible_storage(&state.device, 4)?;
3509			let seed = SecretBuffer::new(
3510				&state.device,
3511				usize::try_from(seed_len)
3512					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3513			)?;
3514			let (command, witness) = seed.record_mldsa_sign_prehashed(
3515				bytes,
3516				&key.private,
3517				&key.public,
3518				[digest, context, &signature, &status],
3519				key.parameter,
3520				algorithm,
3521				context_length,
3522			)?;
3523			let event = submit_recorded(&mut state, command)?;
3524			Ok((signature, status, SecretErasure::new(event, witness)))
3525		})
3526	}
3527
3528	fn validate_mlkem_key(&self, key: &MlKemDeviceKey) -> Result<()> {
3529		let state = self.state.borrow();
3530		if state.capture_active {
3531			return Err(Error::failed_precondition(
3532				"ML-KEM secret execution cannot enter capture",
3533			));
3534		}
3535		if !Rc::ptr_eq(&key.runtime.state, &self.state)
3536			|| !key.private.belongs_to(&state.device)
3537			|| !key.public.belongs_to(&state.device)
3538			|| !key.ready.comes_from(&state.device)
3539		{
3540			return Err(Error::invalid_argument(
3541				"ML-KEM key requires its originating Runtime",
3542			));
3543		}
3544		Ok(())
3545	}
3546
3547	/// Private retained-key route; external encapsulation keys are not admitted.
3548	/// Status is public key canonicality, never ciphertext rejection.
3549	#[cfg_attr(
3550		not(test),
3551		expect(dead_code, reason = "private ML-KEM shared-secret integration")
3552	)]
3553	pub(super) fn encapsulate_mlkem(
3554		&self,
3555		key: &MlKemDeviceKey,
3556		entropy: crate::crypto::entropy::Entropy<32>,
3557	) -> Result<(MlKemSharedSecret, Buffer, Buffer, SecretErasure)> {
3558		self.validate_mlkem_key(key)?;
3559		self.encapsulate_mlkem_public(key.k, &key.public, entropy)
3560	}
3561
3562	/// Private external-public-key qualification route. Canonicality is checked
3563	/// on device before the KEM formula; status never reports ciphertext rejection.
3564	pub(super) fn encapsulate_mlkem_public(
3565		&self,
3566		k: u32,
3567		public: &Buffer,
3568		entropy: crate::crypto::entropy::Entropy<32>,
3569	) -> Result<(MlKemSharedSecret, Buffer, Buffer, SecretErasure)> {
3570		if !(2..=4).contains(&k) {
3571			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3572		}
3573		{
3574			let state = self.state.borrow();
3575			if state.capture_active {
3576				return Err(Error::failed_precondition(
3577					"ML-KEM secret encapsulation cannot enter capture",
3578				));
3579			}
3580			if !public.belongs_to(&state.device) || public.size() != u64::from(384 * k + 32) {
3581				return Err(Error::invalid_argument(
3582					"ML-KEM public-key ownership or extent mismatch",
3583				));
3584			}
3585		}
3586		self
3587			.state
3588			.borrow()
3589			.device
3590			.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemEncapsU8)?;
3591		self.flush_impl(FlushTiming::Untimed)?;
3592		entropy.consume(|bytes| {
3593			let mut state = self.state.borrow_mut();
3594			let ciphertext_size = 32 * if k == 4 { 11 * k + 5 } else { 10 * k + 4 };
3595			let ciphertext = Buffer::host_visible_storage(
3596				&state.device,
3597				usize::try_from(ciphertext_size)
3598					.map_err(|_| Error::invalid_argument("ML-KEM ciphertext extent overflow"))?,
3599			)?;
3600			let status = Buffer::host_visible_storage(&state.device, 4)?;
3601			let private = Arc::new(SecretBuffer::new(&state.device, 32)?);
3602			let seed = SecretBuffer::new(&state.device, 32)?;
3603			let (command, witness) =
3604				seed.record_mlkem_encaps(bytes, public, &private, &ciphertext, &status, k)?;
3605			let ready = submit_recorded(&mut state, command)?;
3606			let erasure = SecretErasure::new(ready.clone(), witness);
3607			Ok((
3608				MlKemSharedSecret {
3609					runtime: self.clone(),
3610					private,
3611					ready,
3612				},
3613				ciphertext,
3614				status,
3615				erasure,
3616			))
3617		})
3618	}
3619
3620	/// Retained generated keys only. A malformed ciphertext of the correct size
3621	/// follows implicit rejection entirely on device; no rejection flag escapes.
3622	pub(super) fn decapsulate_mlkem(
3623		&self,
3624		key: &MlKemDeviceKey,
3625		ciphertext: &Buffer,
3626	) -> Result<(MlKemSharedSecret, SecretErasure)> {
3627		self.validate_mlkem_key(key)?;
3628		let expected = u64::from(
3629			32 * if key.k == 4 {
3630				11 * key.k + 5
3631			} else {
3632				10 * key.k + 4
3633			},
3634		);
3635		{
3636			let state = self.state.borrow();
3637			if !ciphertext.belongs_to(&state.device) || ciphertext.size() != expected {
3638				return Err(Error::invalid_argument(
3639					"ML-KEM ciphertext ownership or extent mismatch",
3640				));
3641			}
3642			state
3643				.device
3644				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemDecapsU8)?;
3645		}
3646		self.flush_impl(FlushTiming::Untimed)?;
3647		let mut state = self.state.borrow_mut();
3648		let private = Arc::new(SecretBuffer::new(&state.device, 32)?);
3649		let (command, witness) = key
3650			.private
3651			.record_mlkem_decaps(ciphertext, &private, key.k)?;
3652		let ready = submit_recorded(&mut state, command)?;
3653		let erasure = SecretErasure::new(ready.clone(), witness);
3654		Ok((
3655			MlKemSharedSecret {
3656				runtime: self.clone(),
3657				private,
3658				ready,
3659			},
3660			erasure,
3661		))
3662	}
3663
3664	pub(super) fn erase_mlkem_shared_secret(
3665		&self,
3666		secret: MlKemSharedSecret,
3667	) -> Result<SecretErasure> {
3668		{
3669			let state = self.state.borrow();
3670			if state.capture_active {
3671				return Err(Error::failed_precondition(
3672					"ML-KEM secret erasure cannot enter capture",
3673				));
3674			}
3675			if !Rc::ptr_eq(&secret.runtime.state, &self.state)
3676				|| !secret.private.belongs_to(&state.device)
3677				|| !secret.ready.comes_from(&state.device)
3678			{
3679				return Err(Error::invalid_argument(
3680					"ML-KEM shared secret requires its originating Runtime",
3681				));
3682			}
3683		}
3684		self.flush_impl(FlushTiming::Untimed)?;
3685		let mut state = self.state.borrow_mut();
3686		let (command, witness) = secret.private.record_retained_erasure()?;
3687		let event = submit_recorded(&mut state, command)?;
3688		Ok(SecretErasure::new(event, witness))
3689	}
3690
3691	/// Declassification boundary: the shared secret stays private while a
3692	/// keyed hash absorbs public info and emits only public derived bytes.
3693	pub(super) fn derive_mlkem_shared_secret(
3694		&self,
3695		secret: &MlKemSharedSecret,
3696		info: &Buffer,
3697		info_len: u32,
3698		output_len: u32,
3699	) -> Result<(Buffer, SecretErasure)> {
3700		{
3701			let state = self.state.borrow();
3702			if state.capture_active {
3703				return Err(Error::failed_precondition(
3704					"ML-KEM shared-secret derivation cannot enter capture",
3705				));
3706			}
3707			if !Rc::ptr_eq(&secret.runtime.state, &self.state)
3708				|| !secret.private.belongs_to(&state.device)
3709				|| !secret.ready.comes_from(&state.device)
3710			{
3711				return Err(Error::invalid_argument(
3712					"ML-KEM shared secret requires its originating Runtime",
3713				));
3714			}
3715			if !info.belongs_to(&state.device) {
3716				return Err(Error::invalid_argument(
3717					"ML-KEM derivation info requires the originating device",
3718				));
3719			}
3720			state
3721				.device
3722				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemSharedDeriveU8)?;
3723		}
3724		self.flush_impl(FlushTiming::Untimed)?;
3725		let mut state = self.state.borrow_mut();
3726		let output = Buffer::host_visible_storage(
3727			&state.device,
3728			usize::try_from(output_len)
3729				.map_err(|_| Error::invalid_argument("ML-KEM derivation extent overflow"))?,
3730		)?;
3731		let (command, witness) = secret
3732			.private
3733			.record_shared_derive(info, &output, info_len, output_len)?;
3734		let event = submit_recorded(&mut state, command)?;
3735		Ok((output, SecretErasure::new(event, witness)))
3736	}
3737
3738	pub(crate) fn checkpoint(&self, timed: bool) -> Result<Event> {
3739		self.checkpoint_impl(if timed {
3740			FlushTiming::Fresh
3741		} else {
3742			FlushTiming::Untimed
3743		})
3744	}
3745
3746	/// Checkpoint with a caller-owned timestamp pair. The pair is retained
3747	/// through command retirement but not exposed on the returned event.
3748	pub(crate) fn checkpoint_timed_with(&self, pair: &super::TimestampPair) -> Result<Event> {
3749		self.checkpoint_impl(FlushTiming::Borrowed(pair.clone()))
3750	}
3751
3752	fn checkpoint_impl(&self, timing: FlushTiming) -> Result<Event> {
3753		let timed = !matches!(timing, FlushTiming::Untimed);
3754		if let Some(event) = self.flush_impl(timing)? {
3755			return Ok(event);
3756		}
3757		if timed {
3758			return Err(Error::failed_precondition(
3759				"timed checkpoint requires pending eager work",
3760			));
3761		}
3762		let mut state = self.state.borrow_mut();
3763		let command = state.device.record_empty()?;
3764		submit_recorded(&mut state, command)
3765	}
3766
3767	pub(crate) fn record_semantic(
3768		&self,
3769		dispatch: ComputeDispatch<'_>,
3770		semantic: SemanticDispatch<'_>,
3771	) -> Result<()> {
3772		let mut state = self.state.borrow_mut();
3773		let device = state.device.clone();
3774		state.session.record_semantic(&device, dispatch, semantic)
3775	}
3776
3777	pub(crate) fn compute_shared_memory_bytes(&self) -> u32 {
3778		self.state.borrow().device.compute_shared_memory_bytes()
3779	}
3780
3781	pub(crate) fn uses_compatibility_profile(&self) -> bool {
3782		self.state.borrow().device.physical().profile
3783			== super::device::features::ExecutionProfile::Compatibility
3784	}
3785
3786	pub(crate) fn linear_dispatch_grid(&self, count: u32, group_size: u32) -> Result<[u32; 3]> {
3787		self
3788			.state
3789			.borrow()
3790			.device
3791			.linear_dispatch_grid(count, group_size)
3792	}
3793
3794	/// Queried per-dimension compute dispatch group limits of the selected device.
3795	pub(crate) fn max_compute_work_group_count(&self) -> [u32; 3] {
3796		self.state.borrow().device.max_compute_work_group_count()
3797	}
3798
3799	pub(crate) fn record_optional_semantic(
3800		&self,
3801		dispatch: ComputeDispatch<'_>,
3802		semantic: OptionalSemanticDispatch<'_>,
3803	) -> Result<()> {
3804		let mut state = self.state.borrow_mut();
3805		let device = state.device.clone();
3806		state
3807			.session
3808			.record_optional_semantic(&device, dispatch, semantic)
3809	}
3810
3811	pub(crate) fn record_fused_semantic(
3812		&self,
3813		dispatch: ComputeDispatch<'_>,
3814		semantics: &[SemanticDispatch<'_>],
3815	) -> Result<()> {
3816		let mut state = self.state.borrow_mut();
3817		let device = state.device.clone();
3818		state
3819			.session
3820			.record_fused_semantic(&device, dispatch, semantics)
3821	}
3822
3823	pub(crate) fn record_split_semantic(
3824		&self,
3825		dispatches: &[ComputeDispatch<'_>],
3826		semantic: SemanticDispatch<'_>,
3827	) -> Result<()> {
3828		let mut state = self.state.borrow_mut();
3829		let device = state.device.clone();
3830		state
3831			.session
3832			.record_split_semantic(&device, dispatches, semantic)
3833	}
3834
3835	pub(crate) fn record_split_optional_semantic(
3836		&self,
3837		dispatches: &[ComputeDispatch<'_>],
3838		semantic: OptionalSemanticDispatch<'_>,
3839	) -> Result<()> {
3840		let mut state = self.state.borrow_mut();
3841		let device = state.device.clone();
3842		state
3843			.session
3844			.record_split_optional_semantic(&device, dispatches, semantic)
3845	}
3846
3847	pub(crate) fn record_audio_semantic(
3848		&self,
3849		dispatch: ComputeDispatch<'_>,
3850		semantic: AudioSemanticDispatch<'_>,
3851	) -> Result<()> {
3852		let mut state = self.state.borrow_mut();
3853		let device = state.device.clone();
3854		state
3855			.session
3856			.record_audio_semantic(&device, dispatch, semantic)
3857	}
3858
3859	pub(crate) fn record_image_semantic(
3860		&self,
3861		dispatch: ComputeDispatch<'_>,
3862		semantic: ImageSemanticDispatch<'_>,
3863	) -> Result<()> {
3864		let mut state = self.state.borrow_mut();
3865		let device = state.device.clone();
3866		state
3867			.session
3868			.record_image_semantic(&device, dispatch, semantic)
3869	}
3870
3871	pub(crate) fn record_image_split_semantic(
3872		&self,
3873		dispatches: &[ComputeDispatch<'_>],
3874		semantic: ImageSemanticDispatch<'_>,
3875	) -> Result<()> {
3876		let mut state = self.state.borrow_mut();
3877		let device = state.device.clone();
3878		state
3879			.session
3880			.record_image_split_semantic(&device, dispatches, semantic)
3881	}
3882
3883	pub(crate) fn record_audio_split_semantic(
3884		&self,
3885		dispatches: &[ComputeDispatch<'_>],
3886		semantic: AudioSemanticDispatch<'_>,
3887	) -> Result<()> {
3888		let mut state = self.state.borrow_mut();
3889		let device = state.device.clone();
3890		state
3891			.session
3892			.record_audio_split_semantic(&device, dispatches, semantic)
3893	}
3894
3895	pub(crate) fn attach_semantic_autograd(
3896		&self,
3897		matrix_value: u64,
3898		sequence: u64,
3899	) -> Result<Option<(super::SemanticOpId, u64)>> {
3900		self
3901			.state
3902			.borrow_mut()
3903			.session
3904			.attach_autograd(matrix_value, sequence)
3905	}
3906
3907	pub(crate) fn semantic_operation_count(&self) -> usize {
3908		self.state.borrow().session.semantic_operation_count()
3909	}
3910
3911	pub(crate) fn complete_semantic_autograd(
3912		&self,
3913		forward: super::SemanticOpId,
3914		sequence: u64,
3915		generation: u64,
3916		backward_first: usize,
3917	) -> Result<()> {
3918		self
3919			.state
3920			.borrow_mut()
3921			.session
3922			.complete_autograd(forward, sequence, generation, backward_first)
3923	}
3924
3925	pub(crate) fn flush(&self) -> Result<Option<Event>> {
3926		self.flush_impl(FlushTiming::Untimed)
3927	}
3928
3929	fn flush_impl(&self, timing: FlushTiming) -> Result<Option<Event>> {
3930		let mut state = self.state.borrow_mut();
3931		if state.capture_active {
3932			return Err(Error::failed_precondition(
3933				"cannot submit eager work while execution capture is active",
3934			));
3935		}
3936		let device = state.device.clone();
3937		let Some(pending) = state.session.take(&device, &[])? else {
3938			return Ok(None);
3939		};
3940		let runs = pending.graph.queue_runs();
3941		if runs.len() > 1 {
3942			let start = state.next_epoch;
3943			let completion = (|| {
3944				if matches!(timing, FlushTiming::Borrowed(_)) {
3945					return Err(Error::missing_capability(
3946						"borrowed timing requires a single queue family",
3947					));
3948				}
3949				let timed = matches!(timing, FlushTiming::Fresh);
3950				let mut commands = RecordedBatch::new(&device);
3951				for run in runs {
3952					let command = device
3953						.record_reusable_graph_range(&pending.graph, run.nodes)?
3954						.submission();
3955					commands.push(if timed {
3956						device.time_reusable_command(command)?
3957					} else {
3958						command
3959					});
3960				}
3961				submit_recorded_batch(&mut state, commands, timed)
3962			})();
3963			return match completion {
3964				Ok(event) => {
3965					pending.mark_submitted(&event);
3966					Ok(Some(event))
3967				}
3968				Err(error) => {
3969					if state.next_epoch != start {
3970						pending.graph.invalidate_video_owners();
3971					}
3972					pending.mark_failed();
3973					Err(error)
3974				}
3975			};
3976		}
3977		let borrowed = matches!(timing, FlushTiming::Borrowed(_));
3978		let recorded = match timing {
3979			FlushTiming::Untimed => state.device.record_compute_graph(&pending.graph),
3980			FlushTiming::Fresh => state.device.record_timed_compute_graph(&pending.graph),
3981			FlushTiming::Borrowed(pair) => state
3982				.device
3983				.record_timed_compute_graph_with(&pending.graph, pair),
3984		};
3985		let recorded = recorded.map(|mut command| {
3986			if borrowed {
3987				command.suppress_event_timing();
3988			}
3989			command
3990		});
3991		match recorded {
3992			Ok(command) => match submit_recorded(&mut state, command) {
3993				Ok(event) => {
3994					pending.mark_submitted(&event);
3995					Ok(Some(event))
3996				}
3997				Err(error) => {
3998					pending.mark_failed();
3999					Err(error)
4000				}
4001			},
4002			Err(error) => {
4003				pending.mark_failed();
4004				Err(error)
4005			}
4006		}
4007	}
4008
4009	fn submit_plan(&self, plan: &ExecutionPlan, timed: bool) -> Result<Event> {
4010		if !plan.belongs_to(self) {
4011			return Err(Error::invalid_argument(
4012				"execution plan belongs to another runtime",
4013			));
4014		}
4015		self.flush()?;
4016		let mut state = self.state.borrow_mut();
4017		let ranges = match plan.submission_ranges(&state.device) {
4018			Ok(ranges) => ranges,
4019			Err(error) => {
4020				plan.mark_failed();
4021				return Err(error);
4022			}
4023		};
4024		// One submission range maps to one command buffer; ranges are
4025		// bounded by queue runs, so each command stays on one queue family.
4026		// Recording against the full graph keeps both sides of every
4027		// cross-family ownership transfer — the producer range emits the
4028		// release and the consumer range's first hazard emits the acquire.
4029		let start = state.next_epoch;
4030		let completion = (|| {
4031			plan.graph().validate_video_owners()?;
4032			let mut commands = RecordedBatch::new(&state.device);
4033			if plan.graph().has_video() {
4034				for range in ranges {
4035					commands.push(
4036						state
4037							.device
4038							.record_fresh_graph_range(plan.graph(), range, timed)?,
4039					);
4040				}
4041				plan.count_command_recording();
4042			} else if ranges.len() > plan.graph().queue_runs().len() {
4043				for range in ranges {
4044					let command = state
4045						.device
4046						.record_reusable_graph_range(plan.graph(), range)?
4047						.submission();
4048					commands.push(if timed {
4049						state.device.time_reusable_command(command)?
4050					} else {
4051						command
4052					});
4053				}
4054			} else {
4055				for command in plan.reusable_commands(&state.device)? {
4056					commands.push(if timed {
4057						state.device.time_reusable_command(command)?
4058					} else {
4059						command
4060					});
4061				}
4062			}
4063			submit_recorded_batch(&mut state, commands, timed)
4064		})();
4065		match completion {
4066			Ok(event) => {
4067				plan.mark_submitted(&event);
4068				Ok(event)
4069			}
4070			Err(error) => {
4071				if state.next_epoch != start {
4072					plan.graph().invalidate_video_owners();
4073				}
4074				plan.mark_failed();
4075				Err(error)
4076			}
4077		}
4078	}
4079}
4080
4081impl SemanticLoweringScope {
4082	/// Record one private physical dispatch owned by this composite lowering.
4083	pub(crate) fn record_physical(&self, dispatch: ComputeDispatch<'_>) -> Result<()> {
4084		let mut state = self.runtime.state.borrow_mut();
4085		let device = state.device.clone();
4086		state.session.record_physical_lowering(&device, dispatch)
4087	}
4088
4089	pub(crate) fn commit(mut self, semantic: SemanticDispatch<'_>) -> Result<()> {
4090		let result = self
4091			.runtime
4092			.state
4093			.borrow_mut()
4094			.session
4095			.finish_semantic_lowering(semantic);
4096		self.active = false;
4097		result.map(|_| ())
4098	}
4099
4100	pub(crate) fn commit_optional(mut self, semantic: OptionalSemanticDispatch<'_>) -> Result<()> {
4101		let result = self
4102			.runtime
4103			.state
4104			.borrow_mut()
4105			.session
4106			.finish_optional_semantic_lowering(semantic);
4107		self.active = false;
4108		result.map(|_| ())
4109	}
4110
4111	pub(crate) fn commit_quant(mut self, semantic: QuantSemanticDispatch<'_>) -> Result<()> {
4112		let result = self
4113			.runtime
4114			.state
4115			.borrow_mut()
4116			.session
4117			.finish_quant_semantic_lowering(semantic);
4118		self.active = false;
4119		result.map(|_| ())
4120	}
4121}
4122
4123impl Drop for SemanticLoweringScope {
4124	fn drop(&mut self) {
4125		if !self.active {
4126			return;
4127		}
4128		self
4129			.runtime
4130			.state
4131			.borrow_mut()
4132			.session
4133			.cancel_semantic_lowering();
4134	}
4135}
4136
4137struct CaptureGuard {
4138	runtime: RuntimeHandle,
4139	active: bool,
4140	/// Heap descriptor writes issued before capture began; the delta at
4141	/// finish is this plan's binding cost (OA-CC-21 census).
4142	descriptor_writes_before: u64,
4143}
4144
4145/// Movable private recording transaction used by stateful domain sessions.
4146pub(crate) struct RecordingTransaction {
4147	guard: Option<CaptureGuard>,
4148}
4149
4150impl RecordingTransaction {
4151	pub(crate) fn begin(runtime: RuntimeHandle) -> Result<Self> {
4152		Ok(Self {
4153			guard: Some(CaptureGuard::begin(runtime)?),
4154		})
4155	}
4156
4157	pub(crate) fn submit(mut self, timed: bool) -> Result<Event> {
4158		let guard = self.guard.take().expect("recording transaction guard");
4159		let runtime = guard.runtime.clone();
4160		let plan = guard.finish(&[])?;
4161		runtime.submit_plan(&plan, timed)
4162	}
4163}
4164
4165impl CaptureGuard {
4166	fn begin(runtime: RuntimeHandle) -> Result<Self> {
4167		{
4168			let mut state = runtime.state.borrow_mut();
4169			if state.capture_active {
4170				return Err(Error::failed_precondition(
4171					"nested execution capture is not supported",
4172				));
4173			}
4174			if !state.session.is_empty() {
4175				return Err(Error::failed_precondition(
4176					"pending eager work must be submitted before execution capture",
4177				));
4178			}
4179			state.session.begin_capture()?;
4180			state.capture_active = true;
4181			state.capture_generation = state.capture_generation.wrapping_add(1).max(1);
4182		}
4183		let descriptor_writes_before = runtime.descriptor_write_count();
4184		Ok(Self {
4185			runtime,
4186			active: true,
4187			descriptor_writes_before,
4188		})
4189	}
4190
4191	fn finish(mut self, observed_outputs: &[&Matrix]) -> Result<ExecutionPlan> {
4192		let pending = {
4193			let mut state = self.runtime.state.borrow_mut();
4194			let device = state.device.clone();
4195			let pending = match state.session.take(&device, observed_outputs) {
4196				Ok(pending) => pending,
4197				Err(error) => {
4198					state.session.abort_capture();
4199					state.capture_active = false;
4200					self.active = false;
4201					return Err(error);
4202				}
4203			};
4204			state.session.end_capture();
4205			state.capture_active = false;
4206			self.active = false;
4207			pending
4208		};
4209		let Some(pending) = pending else {
4210			return Err(Error::failed_precondition(
4211				"execution capture recorded no executable work",
4212			));
4213		};
4214		pending.mark_captured();
4215		let mut plan = ExecutionPlan::new(self.runtime.clone(), pending, false)?;
4216		plan.set_descriptor_write_count(
4217			self
4218				.runtime
4219				.descriptor_write_count()
4220				.saturating_sub(self.descriptor_writes_before),
4221		);
4222		Ok(plan)
4223	}
4224
4225	fn finish_preserving(mut self, observed_outputs: &[&Matrix]) -> Result<ExecutionPlan> {
4226		let pending = {
4227			let mut state = self.runtime.state.borrow_mut();
4228			let pending = state.session.snapshot(&state.device, observed_outputs);
4229			state.capture_active = false;
4230			self.active = false;
4231			state.session.end_capture();
4232			pending?
4233		};
4234		let Some(pending) = pending else {
4235			return Err(Error::failed_precondition(
4236				"execution capture recorded no executable work",
4237			));
4238		};
4239		let mut plan = ExecutionPlan::new(self.runtime.clone(), pending, true)?;
4240		plan.set_descriptor_write_count(
4241			self
4242				.runtime
4243				.descriptor_write_count()
4244				.saturating_sub(self.descriptor_writes_before),
4245		);
4246		plan.validate_training_replay_safety()?;
4247		let mut state = self.runtime.state.borrow_mut();
4248		plan.precompile(&state.device)?;
4249		state.session.commit_captured_snapshot()?;
4250		Ok(plan)
4251	}
4252}
4253
4254impl Drop for CaptureGuard {
4255	fn drop(&mut self) {
4256		if !self.active {
4257			return;
4258		}
4259		let mut state = self.runtime.state.borrow_mut();
4260		state.session.abort_capture();
4261		state.capture_active = false;
4262	}
4263}
4264
4265fn require_immediate_batch(state: &RuntimeState) -> Result<()> {
4266	if state.capture_active || state.secret_scope.is_some() {
4267		return Err(Error::failed_precondition(
4268			"an immediate command batch requires an runtime outside capture and secret lowering",
4269		));
4270	}
4271	Ok(())
4272}
4273
4274/// Submit a fully recorded batch through the runtime timeline and publish
4275/// its last exact epoch. A failed submit leaves the remaining commands in
4276/// the batch guard, which frees them without submitting.
4277fn submit_recorded_batch(
4278	state: &mut RuntimeState,
4279	batch: RecordedBatch,
4280	timed: bool,
4281) -> Result<Event> {
4282	submit_recorded_batch_with(state, batch, timed, submit_recorded)
4283}
4284
4285fn submit_recorded_batch_with(
4286	state: &mut RuntimeState,
4287	mut batch: RecordedBatch,
4288	timed: bool,
4289	mut submit: impl FnMut(&mut RuntimeState, RecordedCommandBuffer) -> Result<Event>,
4290) -> Result<Event> {
4291	require_immediate_batch(state)?;
4292	if !batch.belongs_to(&state.device) {
4293		return Err(Error::invalid_argument(
4294			"command batch belongs to another runtime",
4295		));
4296	}
4297	let count = u64::try_from(batch.len())
4298		.ok()
4299		.filter(|count| *count != 0)
4300		.ok_or_else(|| Error::invalid_argument("command batch must be nonempty"))?;
4301	state
4302		.next_epoch
4303		.checked_add(count)
4304		.ok_or_else(|| Error::resource_exhausted("Vulkan submission epoch exhausted"))?;
4305	let mut statuses = Vec::new();
4306	let mut receipts = Vec::new();
4307	let first_command = batch.next().expect("nonempty command batch");
4308	statuses.extend(first_command.decode_statuses.iter().cloned());
4309	receipts.extend(first_command.encode_receipts.iter().cloned());
4310	let mut completion = submit(state, first_command)?;
4311	let first = timed.then(|| completion.clone());
4312	while let Some(command) = batch.next() {
4313		statuses.extend(command.decode_statuses.iter().cloned());
4314		receipts.extend(command.encode_receipts.iter().cloned());
4315		completion = submit(state, command)?;
4316	}
4317	if let Some(first) = first {
4318		completion.set_timing_start(&first);
4319	}
4320	completion.set_decode_statuses(statuses);
4321	completion.set_encode_receipts(receipts);
4322	Ok(completion)
4323}
4324
4325fn submit_recorded(state: &mut RuntimeState, command: RecordedCommandBuffer) -> Result<Event> {
4326	if let Some(scope) = &mut state.secret_scope {
4327		let index = u64::try_from(scope.pending.len())
4328			.ok()
4329			.and_then(|index| index.checked_add(1));
4330		let Some(epoch) = index.and_then(|index| state.next_epoch.checked_add(index)) else {
4331			state.device.free(command);
4332			return Err(Error::resource_exhausted(
4333				"Vulkan submission epoch exhausted",
4334			));
4335		};
4336		if let Err(error) = state.retirement.prepare() {
4337			state.device.free(command);
4338			return Err(error);
4339		}
4340		let (deferred, ticket) = state.retirement.reserve();
4341		let node = SecretScopeNode {
4342			uses_secret: command.has_secret_use(),
4343			records_erasure: command.has_secret_erasure(),
4344			retains_public: command.has_public_resources(),
4345		};
4346		scope.nodes.push(node);
4347		let timing = command.timing();
4348		scope.pending.push(DeferredSubmission {
4349			epoch,
4350			command,
4351			deferred,
4352			ticket: ticket.clone(),
4353		});
4354		return Ok(Event::new(state.device.clone(), epoch, ticket, timing));
4355	}
4356	let Some(epoch) = state.next_epoch.checked_add(1) else {
4357		state.device.free(command);
4358		return Err(Error::resource_exhausted(
4359			"Vulkan submission epoch exhausted",
4360		));
4361	};
4362	if let Err(error) = state.retirement.prepare() {
4363		state.device.free(command);
4364		return Err(error);
4365	}
4366	if let Err(error) = state.device.submit(&command, epoch) {
4367		state.device.free(command);
4368		return Err(error);
4369	}
4370	let timing = command.timing();
4371	state.next_epoch = epoch;
4372	let retirement = state.retirement.retire(command, epoch)?;
4373	Ok(Event::new(state.device.clone(), epoch, retirement, timing))
4374}
4375
4376#[cfg(test)]
4377#[path = "../../../../test/rs/runtime/secret_runtime_unit.rs"]
4378mod secret_tests;
4379
4380#[cfg(test)]
4381#[path = "../../../../test/rs/runtime/device_owner_unit.rs"]
4382mod device_owner_tests;
4383
4384#[cfg(test)]
4385#[path = "../../../../test/rs/runtime/jit_chain_unit.rs"]
4386mod jit_chain_tests;
4387
4388#[cfg(test)]
4389#[path = "../../../../test/rs/runtime/recorded_batch_unit.rs"]
4390mod recorded_batch_tests;