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	/// Active deferred secret-lowering batch. While set, every recorded
1287	/// submission defers into this ordered batch instead of queueing.
1288	secret_scope: Option<SecretScopeState>,
1289	/// Live compose images allocated for UI layers.
1290	compose_images: RefCell<Vec<ComposeImageEntry>>,
1291	/// Measured matmul winners recorded by qualification, replayed only after
1292	/// full revalidation against the live registry and problem/device contract.
1293	matmul_route_cache: super::dna::provider::blas::MatmulRouteCache,
1294	/// `true` when the `.vkcache` GEMM section existed but failed its inner
1295	/// codec. A failed-load snapshot must never replace another writer's
1296	/// qualified observations, so persistence preserves that section verbatim.
1297	matmul_route_section_corrupt: bool,
1298}
1299
1300/// Classification metadata for one deferred node. The scope records whether a
1301/// command consumes secrets, records erasure, or retains public outputs —
1302/// never secret bytes, handles, or raw descriptor data.
1303#[derive(Clone, Copy)]
1304pub(crate) struct SecretScopeNode {
1305	pub(crate) uses_secret: bool,
1306	pub(crate) records_erasure: bool,
1307	pub(crate) retains_public: bool,
1308}
1309
1310struct DeferredSubmission {
1311	epoch: u64,
1312	command: RecordedCommandBuffer,
1313	deferred: DeferredRetirement,
1314	ticket: RetirementTicket,
1315}
1316
1317struct SecretScopeState {
1318	pending: Vec<DeferredSubmission>,
1319	nodes: Vec<SecretScopeNode>,
1320}
1321
1322/// Thread-affine shared access to the execution owner retained by its values.
1323#[derive(Clone)]
1324pub(crate) struct RuntimeHandle {
1325	state: Rc<RefCell<RuntimeState>>,
1326}
1327
1328/// Timestamp placement for one eager flush or checkpoint. `Borrowed` records a
1329/// caller-owned named-timer pair; the timer owns the reading, so the submission
1330/// event does not expose a duration.
1331enum FlushTiming {
1332	Untimed,
1333	Fresh,
1334	Borrowed(super::TimestampPair),
1335}
1336
1337/// Unique private value; only in-flight commands may share its storage lifetime.
1338/// No Clone, Debug, mapping, export, Matrix conversion or implicit erasure.
1339pub(crate) struct MlKemDeviceKey {
1340	runtime: RuntimeHandle,
1341	private: Arc<SecretBuffer>,
1342	public: Buffer,
1343	k: u32,
1344	ready: Event,
1345}
1346
1347/// Unique private value; only in-flight commands may share its storage lifetime.
1348/// No Clone, Debug, mapping, export, Matrix conversion or implicit erasure.
1349pub(crate) struct MlDsaDeviceKey {
1350	runtime: RuntimeHandle,
1351	private: Arc<SecretBuffer>,
1352	public: Buffer,
1353	parameter: u32,
1354	ready: Event,
1355}
1356
1357/// Unique private shared-secret value. Readiness retains its originating Runtime;
1358/// command references retain storage only, with no mapping or implicit erasure.
1359pub(crate) struct MlKemSharedSecret {
1360	runtime: RuntimeHandle,
1361	private: Arc<SecretBuffer>,
1362	ready: Event,
1363}
1364
1365/// Transactional ownership of one semantic operation's composite lowering.
1366///
1367/// Child operations retain executable work while their semantic identities are
1368/// suppressed. The outermost commit assigns every emitted node to the parent
1369/// contract; dropping an unfinished scope rolls back only its emitted work.
1370pub(crate) struct SemanticLoweringScope {
1371	runtime: RuntimeHandle,
1372	active: bool,
1373}
1374
1375/// Deferred secret-execution batch owned by one Runtime.
1376///
1377/// While this scope is active, recorded secret and ordinary submissions defer
1378/// into an ordered batch carrying secret classification metadata only — never
1379/// secret bytes. `commit` submits the batch in order; abandoning it frees the
1380/// recorded commands and fails their reserved completions without submission
1381/// or waiting.
1382pub(crate) struct SecretLoweringScope {
1383	runtime: RuntimeHandle,
1384	active: bool,
1385}
1386
1387impl SecretLoweringScope {
1388	/// Classification snapshot of the deferred nodes. Diagnostics may observe
1389	/// flags and order only; no secret bytes or native handles are exposed.
1390	pub(crate) fn nodes(&self) -> Vec<SecretScopeNode> {
1391		self
1392			.runtime
1393			.state
1394			.borrow()
1395			.secret_scope
1396			.as_ref()
1397			.map(|scope| scope.nodes.clone())
1398			.unwrap_or_default()
1399	}
1400
1401	/// Submit every deferred command in recorded order. Per-operation events
1402	/// and erasure tickets issued during the scope resolve through their own
1403	/// exact epochs; the returned event describes the final node.
1404	///
1405	/// On failure, unsubmitted nodes are freed and their completions failed;
1406	/// already-submitted nodes retire normally.
1407	pub(crate) fn commit(mut self) -> Result<Event> {
1408		let mut state = self.runtime.state.borrow_mut();
1409		let Some(scope) = state.secret_scope.take() else {
1410			return Err(Error::failed_precondition(
1411				"secret lowering scope is no longer active",
1412			));
1413		};
1414		self.active = false;
1415		let mut pending = scope.pending;
1416		if pending.is_empty() {
1417			return Err(Error::invalid_argument(
1418				"secret lowering scope recorded no submissions",
1419			));
1420		}
1421		let mut result = Ok(None);
1422		while let Some(item) = pending.first() {
1423			if let Err(error) = state.device.submit(&item.command, item.epoch) {
1424				result = Err(error);
1425				break;
1426			}
1427			state.next_epoch = item.epoch;
1428			let timing = item.command.timing();
1429			let ticket = item.ticket.clone();
1430			let item = pending.remove(0);
1431			if let Err(error) = state
1432				.retirement
1433				.retire_deferred(item.deferred, item.command, item.epoch)
1434			{
1435				result = Err(error);
1436				break;
1437			}
1438			result = Ok(Some(Event::new(
1439				state.device.clone(),
1440				item.epoch,
1441				ticket,
1442				timing,
1443			)));
1444		}
1445		for item in pending {
1446			item.deferred.fail();
1447			state.device.free(item.command);
1448		}
1449		result.and_then(|event| event.ok_or_else(|| Error::internal("secret batch produced no event")))
1450	}
1451}
1452
1453impl Drop for SecretLoweringScope {
1454	fn drop(&mut self) {
1455		if !self.active {
1456			return;
1457		}
1458		let mut state = self.runtime.state.borrow_mut();
1459		let Some(scope) = state.secret_scope.take() else {
1460			return;
1461		};
1462		for item in scope.pending {
1463			item.deferred.fail();
1464			state.device.free(item.command);
1465		}
1466	}
1467}
1468
1469impl Runtime {
1470	/// List every Vulkan device, including software CPU implementations.
1471	///
1472	/// Creates a temporary instance but no logical device, allocator or pipelines.
1473	/// A listed device may still fail OA capability admission. Ordinals are scoped
1474	/// to the current loader and ICD configuration, not stable across machines.
1475	///
1476	/// # Errors
1477	/// Returns backend initialization or enumeration errors.
1478	pub fn available_devices() -> Result<Vec<super::DeviceSummary>> {
1479		let instance = Instance::new(&[])?;
1480		DevicePhysical::enumerate(&instance)
1481	}
1482
1483	/// Return queried device facts and the allocated descriptor capacities.
1484	pub fn device_info(&self) -> crate::DeviceInfo {
1485		self.handle.device_info()
1486	}
1487
1488	/// Return runtime-lifetime fusion decision and decline counters.
1489	///
1490	/// Counts reflect fusion passes that already ran: eager work is fused when
1491	/// it is flushed and captured work when it is captured. This query does not
1492	/// flush, submit or wait, and plan replay does not change the counters.
1493	/// The record is a diagnostic; it never influences route selection.
1494	pub fn fusion_stats(&self) -> super::FusionStats {
1495		self.handle.fusion_stats()
1496	}
1497
1498	/// Begin explicit runtime configuration.
1499	pub fn builder() -> RuntimeBuilder {
1500		RuntimeBuilder::new()
1501	}
1502
1503	/// Create an runtime using one compute-capable Vulkan device.
1504	///
1505	/// # Errors
1506	///
1507	/// Returns an error when Vulkan cannot be loaded, no hardware device meets
1508	/// the compiled Core or Compatibility profile requirements,
1509	/// or logical-device creation fails.
1510	pub fn new() -> Result<Self> {
1511		Self::builder().build()
1512	}
1513
1514	/// Initialize this thread's default compute runtime before its first use.
1515	///
1516	/// Initialization is lazy and attempted again after a failure. The selected
1517	/// runtime remains thread-affine and is reused by later default operations.
1518	///
1519	/// # Errors
1520	///
1521	/// Returns the same backend or device-selection error as [`Runtime::new`].
1522	pub fn init_default() -> Result<()> {
1523		DEFAULT_RUNTIME.with(|slot| {
1524			if slot.borrow().is_none() {
1525				let runtime = Self::new()?;
1526				*slot.borrow_mut() = Some(runtime);
1527			}
1528			Ok(())
1529		})
1530	}
1531
1532	/// Install `runtime` as this thread's default compute runtime.
1533	///
1534	/// Replaces any runtime previously stored by [`Runtime::init_default`] or an
1535	/// earlier `set_default` call. The previous default is dropped after the
1536	/// new runtime is installed.
1537	pub fn set_default(runtime: Runtime) {
1538		DEFAULT_RUNTIME.with(|slot| {
1539			*slot.borrow_mut() = Some(runtime);
1540		});
1541	}
1542
1543	/// Return this thread's default compute runtime.
1544	///
1545	/// Initialization is lazy on first use and the returned handle clones the
1546	/// installed runtime, so it remains valid if the default is later replaced.
1547	///
1548	/// # Errors
1549	///
1550	/// Returns the same backend or device-selection error as [`Runtime::new`].
1551	pub fn current() -> Result<Self> {
1552		Self::init_default()?;
1553		DEFAULT_RUNTIME.with(|slot| {
1554			Ok(
1555				slot
1556					.borrow()
1557					.as_ref()
1558					.expect("default runtime initialized above")
1559					.clone(),
1560			)
1561		})
1562	}
1563
1564	/// Access this thread's lazily initialized default compute runtime.
1565	///
1566	/// # Errors
1567	///
1568	/// Returns an runtime initialization error or an error from `use_runtime`.
1569	pub fn with_default<T>(use_runtime: impl FnOnce(&Self) -> Result<T>) -> Result<T> {
1570		Self::init_default()?;
1571		DEFAULT_RUNTIME.with(|slot| {
1572			let selected = slot.borrow();
1573			let runtime = selected
1574				.as_ref()
1575				.expect("default runtime initialized above");
1576			use_runtime(runtime)
1577		})
1578	}
1579
1580	/// Return whether this Runtime has an executable graphics path.
1581	///
1582	/// Both profiles require enabled dynamic rendering and a graphics queue.
1583	/// Presentation additionally requires WSI support and
1584	/// per-surface present-support negotiation.
1585	pub fn has_graphics(&self) -> bool {
1586		self.handle.state.borrow().device.has_graphics_queue()
1587	}
1588
1589	/// Return whether this Runtime's device can calibrate its timestamp domain
1590	/// against a POSIX monotonic host clock.
1591	pub fn supports_clock_calibration(&self) -> bool {
1592		self
1593			.handle
1594			.state
1595			.borrow()
1596			.device
1597			.supports_clock_calibration()
1598	}
1599
1600	/// Sample paired device/host timestamps and retain the lowest-deviation
1601	/// pair.
1602	///
1603	/// `sample_count` selects the best of `[1, 1024]` quasi-simultaneous
1604	/// samples; recalibrate long-running traces periodically because a value
1605	/// farther than half a device-clock period from the sample is inherently
1606	/// ambiguous.
1607	///
1608	/// # Errors
1609	///
1610	/// Returns `InvalidArgument` when `sample_count` is outside `[1, 1024]`,
1611	/// `Unavailable` when the device lacks calibrated timestamps or usable
1612	/// domains, and a backend error when sampling fails.
1613	pub fn calibrate_clock(&self, sample_count: u32) -> Result<ClockCalibration> {
1614		self
1615			.handle
1616			.state
1617			.borrow()
1618			.device
1619			.calibrate_clock(sample_count)
1620	}
1621
1622	/// Create one SDL3 Vulkan surface borrowing this Runtime and window.
1623	pub fn new_presentation_surface<'window>(
1624		&self,
1625		window: &'window super::SdlWindow,
1626	) -> Result<super::PresentationSurface<'window>> {
1627		let state = self.handle.state.borrow();
1628		PresentationSurface::create(&state.device, window)
1629	}
1630
1631	pub fn owns_matrix(&self, matrix: &Matrix) -> bool {
1632		self.handle.same_as(matrix.runtime())
1633	}
1634
1635	pub(crate) fn same_as_handle(&self, handle: &RuntimeHandle) -> bool {
1636		self.handle.same_as(handle)
1637	}
1638
1639	pub(crate) fn begin_stable_resource_frame(&self) -> Result<()> {
1640		self.handle.begin_stable_resource_frame()
1641	}
1642
1643	pub(crate) fn seal_all_stable_resources_external(&self) -> Result<()> {
1644		self.handle.seal_all_stable_resources_external()
1645	}
1646
1647	pub(crate) fn seal_stable_resource_inputs(&self) -> Result<()> {
1648		self.handle.seal_stable_resource_inputs()
1649	}
1650
1651	pub(crate) fn end_stable_resource_frame(&self) {
1652		self.handle.end_stable_resource_frame();
1653	}
1654
1655	pub(crate) fn has_pending_work(&self) -> bool {
1656		self.handle.has_pending_work()
1657	}
1658
1659	pub(crate) fn abort_pending_work(&self) {
1660		self.handle.abort_pending_work();
1661	}
1662
1663	pub(crate) fn query_video_device_capabilities(
1664		&self,
1665	) -> Result<crate::video::VideoDeviceCapabilities> {
1666		self
1667			.handle
1668			.state
1669			.borrow()
1670			.device
1671			.video_device_capabilities()
1672	}
1673
1674	pub(crate) fn query_video_decode_capabilities(
1675		&self,
1676		profile: crate::video::VideoDecodeProfile,
1677	) -> Result<crate::video::VideoDecodeCapabilities> {
1678		self
1679			.handle
1680			.state
1681			.borrow()
1682			.device
1683			.video_decode_capabilities(profile)
1684	}
1685
1686	pub(crate) fn query_video_decode_formats(
1687		&self,
1688		profile: crate::video::VideoDecodeProfile,
1689	) -> Result<crate::video::VideoDecodeFormats> {
1690		self
1691			.handle
1692			.state
1693			.borrow()
1694			.device
1695			.video_decode_formats(profile)
1696	}
1697
1698	pub(crate) fn query_video_encode_capabilities(
1699		&self,
1700		profile: crate::video::VideoEncodeProfile,
1701	) -> Result<crate::video::VideoEncodeCapabilities> {
1702		self
1703			.handle
1704			.state
1705			.borrow()
1706			.device
1707			.video_encode_capabilities(profile)
1708	}
1709
1710	pub(crate) fn query_video_encode_formats(
1711		&self,
1712		profile: crate::video::VideoEncodeProfile,
1713	) -> Result<crate::video::VideoEncodeFormats> {
1714		self
1715			.handle
1716			.state
1717			.borrow()
1718			.device
1719			.video_encode_formats(profile)
1720	}
1721
1722	pub(super) fn build(
1723		selection: DeviceSelection,
1724		requirements: RuntimeRequirements,
1725		log_options: LogOptions,
1726		instance_extensions: Vec<String>,
1727	) -> Result<Self> {
1728		let logger = Logger::new(log_options)?;
1729		let log_selection = logger.select();
1730		let instance = Instance::new(&instance_extensions)?;
1731		if requirements.presentation && !instance.surface_enabled() {
1732			return Err(Error::invalid_argument(
1733				"presentation readiness requires Vulkan surface instance extensions",
1734			));
1735		}
1736		let physical_device = DevicePhysical::select(&instance, selection, &requirements)?;
1737		let device = Device::new(&instance, physical_device)?;
1738		let retirement = RetirementService::new(&device);
1739		device.log_identity();
1740		// Opt-in upfront compilation; the default stays lazy so optional
1741		// domains never enter a driver compiler during Runtime construction.
1742		if crate::EnvFlag::is_set("OA_SHADER_PRELOAD")
1743			&& let Err(error) = device.preload_pipelines()
1744		{
1745			crate::log_warn!(
1746				crate::LogComponent::RUNTIME,
1747				"embedded shader preload failed: {error}"
1748			);
1749		}
1750
1751		// Best-effort measured-route replay through the scoped `.vkcache`
1752		// envelope: a missing section is normal; a present but malformed one is
1753		// evidence worth surfacing while it is preserved for a later writer.
1754		// Either way the empty cache fails closed to structural routing — never
1755		// to a partially accepted record.
1756		let vkcache_scope = super::device::logical::vkcache::VkCacheScope::new(device.physical());
1757		let vkcache_path = vkcache_scope.path();
1758		let mut matmul_route_section_corrupt = false;
1759		let mut matmul_route_cache = super::dna::provider::blas::MatmulRouteCache::new();
1760		if vkcache_path.is_file() {
1761			match super::device::logical::vkcache::VkCacheFile::open(&vkcache_path, &vkcache_scope) {
1762				Ok(file) => {
1763					if let Some(section) =
1764						file.section(super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES)
1765					{
1766						match super::dna::provider::blas::MatmulRouteCache::from_bytes(&section.bytes) {
1767							Ok(cache) => matmul_route_cache = cache,
1768							Err(error) => {
1769								matmul_route_section_corrupt = true;
1770								crate::log_warn!(
1771									crate::LogComponent::RUNTIME,
1772									"discarding malformed vkcache matmul route section: {error}"
1773								);
1774							}
1775						}
1776					}
1777				}
1778				Err(error) => {
1779					crate::log_warn!(
1780						crate::LogComponent::RUNTIME,
1781						"discarding vkcache artifact for route replay: {error}"
1782					);
1783				}
1784			}
1785		}
1786		// Legacy migration: scope-matching records from the unscoped file merge
1787		// in; it stays on disk for other scopes and is never written again.
1788		let route_cache_path = super::dna::provider::blas::route_cache_path();
1789		if let Ok(legacy) = super::dna::provider::blas::MatmulRouteCache::load(&route_cache_path) {
1790			let (vendor_id, device_id, driver_id, driver_version) = vkcache_scope.device_route_scope();
1791			matmul_route_cache.merge_scope(&legacy, vendor_id, device_id, driver_id, driver_version);
1792		}
1793
1794		let handle = RuntimeHandle {
1795			state: Rc::new(RefCell::new(RuntimeState {
1796				retirement,
1797				session: ExecutionSession::new(),
1798				device,
1799				next_epoch: 0,
1800				capture_active: false,
1801				secret_scope: None,
1802				compose_images: RefCell::new(Vec::new()),
1803				matmul_route_cache,
1804				matmul_route_section_corrupt,
1805			})),
1806		};
1807		Ok(Self {
1808			_log_selection: log_selection,
1809			logger,
1810			persistence: Rc::new(RuntimePersistence {
1811				handle: handle.clone(),
1812			}),
1813			handle,
1814			_not_send_sync: PhantomData,
1815		})
1816	}
1817
1818	/// Submit an explicit completion checkpoint to this runtime's compute queue.
1819	///
1820	/// Pending eager operations are submitted together as one batch. When no
1821	/// eager work is pending, an empty checkpoint is submitted. The returned
1822	/// event completes after that exact queue point. Dropping it does not wait.
1823	///
1824	/// # Errors
1825	///
1826	/// Returns an error when command recording, submission, or retirement fails,
1827	/// or when the runtime exhausts its timeline epoch space.
1828	pub fn checkpoint(&self) -> Result<Event> {
1829		self.handle.checkpoint(false)
1830	}
1831
1832	/// Submit pending eager work with one device timestamp pair around the batch.
1833	///
1834	/// Unlike [`Runtime::checkpoint`], this requires at least one pending operation;
1835	/// there is no meaningful device interval for an empty queue checkpoint.
1836	///
1837	/// # Errors
1838	///
1839	/// Returns the errors from [`Runtime::checkpoint`], `MissingCapability` when
1840	/// timestamps are unavailable, or `FailedPrecondition` for an empty batch.
1841	pub fn checkpoint_timed(&self) -> Result<Event> {
1842		self.handle.checkpoint(true)
1843	}
1844
1845	/// Submit pending eager work bracketed by a device [`Timer`]'s timestamps.
1846	///
1847	/// The timer must be initialized for `TimerDomain::Device` on this runtime
1848	/// and is single-flight: a new tagged submission is rejected while the
1849	/// previous one is pending. The returned event carries no timing; the
1850	/// elapsed device duration is committed through [`Timer::commit`].
1851	///
1852	/// Donor: `oa::Runtime::submit(oa::Timer*)` in
1853	/// `oacpp/source/cpp/lib/oa/runtime/runtime/runtime.cpp`.
1854	///
1855	/// # Errors
1856	///
1857	/// Returns the errors from [`Runtime::checkpoint_timed`], or
1858	/// `FailedPrecondition` when the timer is host-domain, uninitialized, or
1859	/// still pending, or `InvalidArgument` when it was initialized by another
1860	/// runtime.
1861	pub fn checkpoint_with_timer(&self, timer: &mut Timer) -> Result<Event> {
1862		let device = self.handle.state.borrow().device.clone();
1863		timer.prepare_device_submit(&device)?;
1864		let pair = timer
1865			.device_pair()
1866			.expect("device timer was checked")
1867			.clone();
1868		let event = self.handle.checkpoint_timed_with(&pair)?;
1869		timer.attach_event(event.clone());
1870		Ok(event)
1871	}
1872
1873	/// Create a device timestamp pair for a named [`Timer`].
1874	pub(crate) fn device_timestamp_pair(&self) -> Result<super::TimestampPair> {
1875		self
1876			.handle
1877			.state
1878			.borrow()
1879			.device
1880			.clone()
1881			.new_timestamp_pair()
1882	}
1883
1884	/// Capture an isolated operation sequence as an immutable execution plan.
1885	///
1886	/// Capture records but never submits or waits. The returned value may include
1887	/// matrices produced by the plan; those matrices become observable only after
1888	/// [`Runtime::submit`] is called for the returned plan.
1889	///
1890	/// # Errors
1891	///
1892	/// Returns an error when eager work is already pending, capture is nested, the
1893	/// closure fails, or the closure records no executable work.
1894	pub fn capture<T>(&self, capture: impl FnOnce() -> Result<T>) -> Result<(ExecutionPlan, T)> {
1895		let guard = CaptureGuard::begin(self.handle.clone())?;
1896		let output = capture()?;
1897		let plan = guard.finish(&[])?;
1898		Ok((plan, output))
1899	}
1900
1901	pub(crate) fn capture_with_initialized_state<T>(
1902		&self,
1903		state: &[&Matrix],
1904		capture: impl FnOnce() -> Result<T>,
1905	) -> Result<(ExecutionPlan, T)> {
1906		let snapshots = state
1907			.iter()
1908			.map(|value| {
1909				if !self.owns_matrix(value) {
1910					return Err(Error::invalid_argument(
1911						"capture state belongs to another runtime",
1912					));
1913				}
1914				value.storage().initialized_readiness()
1915			})
1916			.collect::<Result<Vec<_>>>()?;
1917		let result = self.capture(capture);
1918		for (value, previous) in state.iter().zip(snapshots) {
1919			previous.restore(value.storage());
1920		}
1921		result
1922	}
1923
1924	pub(crate) fn capture_observed_matrix(
1925		&self,
1926		capture: impl FnOnce() -> Result<Matrix>,
1927	) -> Result<(ExecutionPlan, Matrix)> {
1928		let guard = CaptureGuard::begin(self.handle.clone())?;
1929		let output = capture()?;
1930		let plan = guard.finish(&[&output])?;
1931		Ok((plan, output))
1932	}
1933
1934	pub(crate) fn capture_observed_training_matrix_preserving(
1935		&self,
1936		capture: impl FnOnce() -> Result<Matrix>,
1937	) -> Result<CaptureAttempt<Matrix>> {
1938		let guard = CaptureGuard::begin(self.handle.clone())?;
1939		let output = capture()?;
1940		Ok(match guard.finish_preserving(&[&output]) {
1941			Ok(plan) => CaptureAttempt::Captured {
1942				plan: Box::new(plan),
1943				output,
1944			},
1945			Err(error) => CaptureAttempt::Rejected { error, output },
1946		})
1947	}
1948
1949	/// Submit an immutable execution plan to its originating runtime.
1950	///
1951	/// Any pending eager batch is submitted first. The returned event identifies
1952	/// exact completion of this plan replay. Submission does not wait.
1953	///
1954	/// # Errors
1955	///
1956	/// Returns an error when the plan belongs to another runtime, capture is active,
1957	/// eager flushing fails, or command recording, submission, or retirement fails.
1958	pub fn submit(&self, plan: &ExecutionPlan) -> Result<Event> {
1959		self.handle.submit_plan(plan, false)
1960	}
1961
1962	/// Submit a plan with one device timestamp pair around its complete graph.
1963	///
1964	/// The returned event exposes the device duration through
1965	/// [`Event::try_device_duration`] and [`Event::device_duration`]. Timing adds
1966	/// instrumentation only to this replay and does not wait.
1967	///
1968	/// # Errors
1969	///
1970	/// Returns the errors from [`Runtime::submit`], or `MissingCapability` when the
1971	/// selected compute queue cannot provide timestamps.
1972	pub fn submit_timed(&self, plan: &ExecutionPlan) -> Result<Event> {
1973		self.handle.submit_plan(plan, true)
1974	}
1975
1976	/// Write one record through this runtime's logging session.
1977	///
1978	/// Filtered records return successfully without formatting or output.
1979	///
1980	/// # Errors
1981	///
1982	/// Returns the first retained console or file output failure, or an error if
1983	/// the logging session has already been closed.
1984	pub fn log(&self, level: LogLevel, component: LogComponent, text: impl AsRef<str>) -> Result<()> {
1985		self.logger.write_text(level, component, text.as_ref())
1986	}
1987
1988	/// Change this runtime logger's minimum severity.
1989	pub fn set_log_level(&self, level: LogLevel) {
1990		self.logger.set_level(level);
1991	}
1992
1993	/// Return this runtime logger's current minimum severity.
1994	pub fn log_level(&self) -> LogLevel {
1995		self.logger.level()
1996	}
1997
1998	/// Return the active log-file path when file output is enabled.
1999	pub fn log_path(&self) -> Option<std::path::PathBuf> {
2000		self.logger.path()
2001	}
2002
2003	/// Flush this runtime's logging session and report any retained sink failure.
2004	///
2005	/// # Errors
2006	///
2007	/// Returns the first console or file output failure.
2008	pub fn flush_log(&self) -> Result<()> {
2009		self.logger.flush()
2010	}
2011
2012	/// Explicitly close this runtime's logging session before releasing the runtime.
2013	///
2014	/// Existing values retain the execution services they require, but no longer
2015	/// have a selected runtime logging session after this call consumes `self`.
2016	///
2017	/// # Errors
2018	///
2019	/// Returns the first console or file flush failure.
2020	pub fn close(self) -> Result<()> {
2021		if crate::EnvFlag::is_set("OA_JIT_TRACE") {
2022			crate::log_info!(
2023				LogComponent::COMPUTE,
2024				"fusion census {}",
2025				self.fusion_stats()
2026			);
2027			let state = self.handle.state.borrow();
2028			let census = state.device.fusion_census();
2029			crate::log_info!(
2030				LogComponent::COMPUTE,
2031				"fusion host_ns {}",
2032				census.fusion_ns()
2033			);
2034			for stats in census.pair_diagnostics() {
2035				crate::log_info!(LogComponent::COMPUTE, "fusion pair {stats}");
2036			}
2037			for stats in census.merge_diagnostics() {
2038				crate::log_info!(LogComponent::COMPUTE, "fusion merge {stats}");
2039			}
2040		}
2041		crate::log_info!(LogComponent::OWNERSHIP, "closing Vulkan compute runtime");
2042		self.logger.close()
2043	}
2044
2045	pub(crate) fn handle(&self) -> RuntimeHandle {
2046		self.handle.clone()
2047	}
2048}
2049
2050impl Drop for RuntimePersistence {
2051	fn drop(&mut self) {
2052		// One Runtime-owned persistence point: gather subsystem snapshots while
2053		// the device is live, then merge them into the scoped `.vkcache`
2054		// envelope under its atomic writer policy. The cache is disposable
2055		// qualified state — a borrow, query or I/O failure never fails runtime
2056		// destruction and never replaces committed observations.
2057		let snapshot = self.handle.state.try_borrow().ok().map(|state| {
2058			let scope = super::device::logical::vkcache::VkCacheScope::new(state.device.physical());
2059			let driver = state.device.pipeline_cache_data();
2060			let jit = state.device.jit_section_updates();
2061			let (vendor_id, device_id, driver_id, driver_version) = scope.device_route_scope();
2062			let gemm = if state.matmul_route_section_corrupt {
2063				// The loaded section failed its inner codec; preserve whatever
2064				// qualified records it may still hold for another writer.
2065				None
2066			} else {
2067				Some(state.matmul_route_cache.serialize_scope(
2068					vendor_id,
2069					device_id,
2070					driver_id,
2071					driver_version,
2072				))
2073			};
2074			(scope, driver, gemm, jit)
2075		});
2076		let Some((scope, driver, gemm, jit)) = snapshot else {
2077			return;
2078		};
2079		let mut updates = Vec::with_capacity(2);
2080		if let Some(blob) = driver {
2081			updates.push(super::device::logical::vkcache::SectionUpdate::replace(
2082				super::device::logical::vkcache::SECTION_DRIVER_PIPELINE_CACHE,
2083				1,
2084				blob,
2085			));
2086		}
2087		match gemm {
2088			Some(Some(payload)) => {
2089				updates.push(super::device::logical::vkcache::SectionUpdate::replace(
2090					super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES,
2091					1,
2092					payload,
2093				));
2094			}
2095			Some(None) => {
2096				updates.push(super::device::logical::vkcache::SectionUpdate::remove(
2097					super::device::logical::vkcache::SECTION_GEMM_MEASURED_ROUTES,
2098				));
2099			}
2100			None => {}
2101		}
2102		updates.extend(jit);
2103		if updates.is_empty() {
2104			return;
2105		}
2106		let path = scope.path();
2107		if super::device::logical::vkcache::update(&path, &scope, &updates).is_ok() {
2108			// The scoped artifact committed; the legacy raw driver blob has
2109			// been imported or superseded and is never written again.
2110			let _ = crate::Filesystem::remove_file(
2111				&super::device::logical::pipeline::legacy_pipeline_cache_path(),
2112			);
2113		}
2114	}
2115}
2116
2117impl RuntimeHandle {
2118	pub(crate) fn device_info(&self) -> crate::DeviceInfo {
2119		self.state.borrow().device.device_info()
2120	}
2121
2122	/// Borrow the selected device for resource creation and admission checks.
2123	pub(crate) fn descriptor_write_count(&self) -> u64 {
2124		self.state.borrow().device.descriptor_write_count()
2125	}
2126
2127	pub(crate) fn device(&self) -> Arc<Device> {
2128		self.state.borrow().device.clone()
2129	}
2130
2131	/// Record one extension-kernel dispatch admitted through `oa::compute`.
2132	/// See [`ExecutionSession::record_extension`].
2133	pub(crate) fn record_extension(
2134		&self,
2135		kernel: &crate::compute::Kernel,
2136		buffers: &[BufferBinding<'_>],
2137		push_constants: &[PushConstant],
2138		workgroups: [u32; 3],
2139	) -> Result<()> {
2140		let mut state = self.state.borrow_mut();
2141		let device = state.device.clone();
2142		state
2143			.session
2144			.record_extension(&device, kernel, buffers, push_constants, workgroups)
2145	}
2146
2147	pub(in crate::runtime) fn fusion_stats(&self) -> super::FusionStats {
2148		self.state.borrow().device.fusion_census().snapshot()
2149	}
2150
2151	/// Add one captured plan's DNN partition outcomes to the fusion census.
2152	pub(in crate::runtime) fn record_dnn_partitions(&self, applied: u32, fallback: u32) {
2153		self
2154			.state
2155			.borrow()
2156			.device
2157			.fusion_census()
2158			.dnn(applied, fallback);
2159	}
2160
2161	/// The admission profile of the selected device — whether descriptor
2162	/// indices baked into fused op tapes are bound-slot positions
2163	/// (Compatibility) or global heap indices (Core).
2164	pub(in crate::runtime) fn execution_profile(&self) -> super::device::features::ExecutionProfile {
2165		self.state.borrow().device.physical().profile
2166	}
2167
2168	/// Snapshot the device facts matmul planning reads.
2169	///
2170	/// The contract records queried limits plus the *enabled* capability
2171	/// surface so candidate legality never claims a feature that device
2172	/// admission left disabled.
2173	pub(in crate::runtime) fn matmul_device_contract(
2174		&self,
2175	) -> super::dna::provider::blas::MatmulDeviceContract {
2176		super::dna::provider::blas::MatmulDeviceContract::from_device(
2177			self.state.borrow().device.as_ref(),
2178		)
2179	}
2180
2181	/// Admits and lazily builds one kernel's pipeline against the live device
2182	/// contract — the donor's plan revalidation immediately before recording.
2183	/// Provider-fused dispatches introduce kernels that source nodes never
2184	/// required, so lowering must admit them here rather than inferring
2185	/// availability from source-node admission.
2186	pub(in crate::runtime) fn require_kernel(
2187		&self,
2188		kernel: super::dna::kernel::KernelId,
2189	) -> Result<()> {
2190		self.state.borrow().device.require_kernel(kernel)
2191	}
2192
2193	/// Measured winner recorded for one exact route key, if any.
2194	///
2195	/// Returns `None` when the donor's `OA_DISABLE_GEMM_ROUTE_CACHE` opt-out is
2196	/// set; the flag is read once, matching the donor's cached env semantics.
2197	pub(in crate::runtime) fn matmul_measured_route(
2198		&self,
2199		key: &super::dna::provider::blas::MatmulRouteKey,
2200	) -> Option<u64> {
2201		if super::dna::provider::blas::measured_route_cache_disabled() {
2202			return None;
2203		}
2204		self.state.borrow().matmul_route_cache.query(key)
2205	}
2206
2207	pub(crate) fn owns_event(&self, event: &Event) -> bool {
2208		event.comes_from(&self.state.borrow().device)
2209	}
2210
2211	pub(crate) fn upload_native_rgba_image(
2212		&self,
2213		storage: &Storage,
2214		width: u32,
2215		height: u32,
2216	) -> Result<Rc<NativeRgbaImage>> {
2217		// A new host-written capture buffer has no GPU producer. Do not wait
2218		// unrelated encode/preview work before uploading it. Device-produced
2219		// buffers still flush and wait for their exact producing event.
2220		if storage.needs_flush() {
2221			self.flush()?;
2222		}
2223		storage.wait_ready()?;
2224		let mut state = self.state.borrow_mut();
2225		let image = Rc::new(NativeRgbaImage::new(&state.device, width, height)?);
2226		let buffer = storage
2227			.buffer()
2228			.ok_or_else(|| {
2229				Error::failed_precondition("native Texture upload requires non-empty storage")
2230			})?
2231			.raw();
2232		let handle = image.handle;
2233		let command = state.device.record_compute_commands(|command| {
2234			let range = vk::ImageSubresourceRange::new()
2235				.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2236				.set_level_count(1)
2237				.set_layer_count(1);
2238			let to_transfer = vk::ImageMemoryBarrier2::new()
2239				.set_src_stage_mask(vk::PipelineStageFlagBits2::NONE)
2240				.set_dst_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2241				.set_dst_access_mask(vk::AccessFlagBits2::TRANSFER_WRITE_BIT)
2242				.set_old_layout(vk::ImageLayout::UNDEFINED)
2243				.set_new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
2244				.set_image(handle)
2245				.set_subresource_range(range);
2246			let barriers = [to_transfer];
2247			unsafe {
2248				state.device.pipeline_barrier(
2249					command,
2250					&(vk::DependencyInfo::new()
2251						.set_image_memory_barriers(&barriers)
2252						.map_err(Error::from)?),
2253				)?;
2254			}
2255			let copy = vk::BufferImageCopy::new()
2256				.set_image_subresource(
2257					vk::ImageSubresourceLayers::new()
2258						.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2259						.set_layer_count(1),
2260				)
2261				.set_image_extent(vk::Extent3D {
2262					width,
2263					height,
2264					depth: 1,
2265				});
2266			unsafe {
2267				state.device.cmd_copy_buffer_to_image(
2268					command,
2269					buffer,
2270					handle,
2271					vk::ImageLayout::TRANSFER_DST_OPTIMAL,
2272					&[copy],
2273				)
2274			}?;
2275			let to_read = vk::ImageMemoryBarrier2::new()
2276				.set_src_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2277				.set_src_access_mask(vk::AccessFlagBits2::TRANSFER_WRITE_BIT)
2278				.set_dst_stage_mask(vk::PipelineStageFlagBits2::ALL_COMMANDS_BIT)
2279				.set_dst_access_mask(vk::AccessFlagBits2::SHADER_SAMPLED_READ_BIT)
2280				.set_old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
2281				.set_new_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)
2282				.set_image(handle)
2283				.set_subresource_range(range);
2284			let barriers = [to_read];
2285			unsafe {
2286				state.device.pipeline_barrier(
2287					command,
2288					&(vk::DependencyInfo::new()
2289						.set_image_memory_barriers(&barriers)
2290						.map_err(Error::from)?),
2291				)?;
2292			}
2293			Ok(())
2294		})?;
2295		let event = submit_recorded(&mut state, command)?;
2296		drop(state);
2297		event.wait()?;
2298		Ok(image)
2299	}
2300
2301	pub(crate) fn same_as(&self, other: &Self) -> bool {
2302		Rc::ptr_eq(&self.state, &other.state)
2303	}
2304
2305	/// Create a `GraphicsPipeline` for the vertex-color lit 3D renderer.
2306	pub(crate) fn create_graphics_pipeline(&self) -> Result<GraphicsPipeline> {
2307		self.state.borrow().device.create_graphics_pipeline()
2308	}
2309
2310	/// Allocate a host-visible persistently-mapped mesh buffer.
2311	pub(crate) fn allocate_mesh_buffer(
2312		&self,
2313		size: usize,
2314		usage: vk::BufferUsageFlags,
2315	) -> Result<MeshBuffer> {
2316		self.state.borrow().device.allocate_mesh_buffer(size, usage)
2317	}
2318
2319	/// Allocate one `RenderTarget` (color + depth + readback) for the 3D renderer.
2320	pub(crate) fn allocate_render_target(&self, width: u32, height: u32) -> Result<RenderTarget> {
2321		let state = self.state.borrow();
2322		RenderTarget::new(&state.device, width, height)
2323	}
2324
2325	/// Copy immutable command entry points before recording borrows RuntimeState.
2326	/// This retains no additional device owner or mutable execution state.
2327	pub(crate) fn ui_sync_commands(&self) -> super::SyncCommands {
2328		self.state.borrow().device.sync_commands().clone()
2329	}
2330
2331	/// Copy the dynamic-rendering dispatch table for UI raster recording.
2332	pub(crate) fn ui_rendering_commands(&self) -> super::RenderingCommands {
2333		self.state.borrow().device.rendering_commands()
2334	}
2335
2336	pub(crate) fn require_ui_bindings(&self) -> Result<()> {
2337		self.state.borrow().device.require_ui_bindings()
2338	}
2339
2340	pub(crate) fn prepare_ui_sources(&self) -> Result<()> {
2341		self.flush_impl(FlushTiming::Untimed)?;
2342		Ok(())
2343	}
2344
2345	pub(in crate::runtime) fn validate_ui_presentation(&self, device: &Arc<Device>) -> Result<()> {
2346		let state = self.state.borrow();
2347		if !Arc::ptr_eq(&state.device, device) {
2348			return Err(Error::invalid_argument(
2349				"UI and Presenter belong to different Runtimes",
2350			));
2351		}
2352		if device.physical().graphics_queue_family != Some(device.physical().compute_queue_family) {
2353			return Err(Error::missing_capability(
2354				"UI presentation requires the unified compute/graphics family selected by RuntimeRequirements::presentation",
2355			));
2356		}
2357		Ok(())
2358	}
2359
2360	pub(crate) fn ui_buffer_info(&self, storage: &Storage) -> Result<vk::DescriptorBufferInfo> {
2361		let state = self.state.borrow();
2362		if !storage.belongs_to(&state.device) {
2363			return Err(Error::invalid_argument(
2364				"UI source belongs to another Runtime",
2365			));
2366		}
2367		let buffer = storage
2368			.buffer()
2369			.ok_or_else(|| Error::invalid_argument("UI source is empty"))?;
2370		Ok(
2371			vk::DescriptorBufferInfo::new()
2372				.set_buffer(buffer.raw())
2373				.set_range(buffer.size()),
2374		)
2375	}
2376
2377	/// Run `f` while holding the primary pipeline-cache synchronization lock.
2378	///
2379	/// `f` receives the primary cache handle (`NULL` when no driver cache is
2380	/// present). Holding the lock across every `vkCreate*Pipelines` call inside
2381	/// `f` satisfies Vulkan's external-synchronization requirement for the
2382	/// shared cache.
2383	///
2384	/// # Errors
2385	/// Returns an error when the pipeline-creation lock is poisoned or `f`
2386	/// fails.
2387	pub(crate) fn with_pipeline_cache<T>(
2388		&self,
2389		f: impl FnOnce(vk::PipelineCache) -> Result<T>,
2390	) -> Result<T> {
2391		let state = self.state.borrow();
2392		let cache = state.device.pipeline_cache()?;
2393		f(cache.raw())
2394	}
2395
2396	/// Return retained shared ownership of the Vulkan device for command recording.
2397	pub(crate) fn raw_device(&self) -> Arc<vk::Device> {
2398		self.state.borrow().device.raw_arc()
2399	}
2400
2401	/// Create a device-local R8G8B8A8_UNORM color-attachment image and its view.
2402	/// Returns `(raw_image, view)`; the allocation and view are retired by
2403	/// `destroy_compose_image`.
2404	pub(crate) fn create_compose_image(
2405		&self,
2406		width: u32,
2407		height: u32,
2408	) -> Result<(vk::Image, vk::ImageView)> {
2409		let state = self.state.borrow();
2410		let device = &state.device;
2411		let image_info = vk::ImageCreateInfo::new()
2412			.set_image_type(vk::ImageType::_2D)
2413			.set_format(vk::Format::R8G8B8A8_UNORM)
2414			.set_extent(vk::Extent3D {
2415				width,
2416				height,
2417				depth: 1,
2418			})
2419			.set_mip_levels(1)
2420			.set_array_layers(1)
2421			.set_samples(vk::SampleCountFlagBits::_1_BIT)
2422			.set_tiling(vk::ImageTiling::OPTIMAL)
2423			.set_usage(
2424				vk::ImageUsageFlagBits::COLOR_ATTACHMENT_BIT
2425					| vk::ImageUsageFlagBits::TRANSFER_SRC_BIT
2426					| vk::ImageUsageFlagBits::TRANSFER_DST_BIT,
2427			)
2428			.set_sharing_mode(vk::SharingMode::EXCLUSIVE)
2429			.set_initial_layout(vk::ImageLayout::UNDEFINED);
2430		let alloc_info =
2431			vk::mem::AllocationCreateInfo::new().set_usage(vk::mem::MemoryUsage::PreferDevice);
2432		let (image, mut alloc) = unsafe {
2433			device
2434				.allocator()
2435				.with_allocator(|a| a.create_image_with_options(&image_info, &alloc_info))
2436		}
2437		.map_err(|source| Error::backend_failure("Vulkan", "UI compose image allocation", source))?
2438		.map_err(Error::from)?;
2439		let view_info = vk::ImageViewCreateInfo::new()
2440			.set_image(image)
2441			.set_view_type(vk::ImageViewType::_2D)
2442			.set_format(vk::Format::R8G8B8A8_UNORM)
2443			.set_subresource_range(
2444				vk::ImageSubresourceRange::new()
2445					.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2446					.set_level_count(1)
2447					.set_layer_count(1),
2448			);
2449		let view = match unsafe { device.create_image_view(&view_info, None) } {
2450			Ok(view) => view,
2451			Err(source) => {
2452				unsafe {
2453					device
2454						.allocator()
2455						.with_allocator(|a| a.destroy_image(image, &mut alloc))
2456				}??;
2457				return Err(Error::backend_failure(
2458					"Vulkan",
2459					"UI compose image view creation",
2460					source,
2461				));
2462			}
2463		};
2464		// The allocation and view live in the runtime registry; the UI layer
2465		// owns the image lifetime and calls destroy_compose_image.
2466		state
2467			.compose_images
2468			.borrow_mut()
2469			.push(ComposeImageEntry { image, view, alloc });
2470		Ok((image, view))
2471	}
2472
2473	/// Destroy the compose image, its view, and its allocation.
2474	pub(crate) fn destroy_compose_image(&self, raw_image: vk::Image) {
2475		if let Ok(state) = self.state.try_borrow() {
2476			let mut entries = state.compose_images.borrow_mut();
2477			if let Some(pos) = entries.iter().position(|e| e.image == raw_image) {
2478				let mut entry = entries.swap_remove(pos);
2479				unsafe {
2480					let _ = state.device.destroy_image_view(entry.view, None);
2481					let _ = state
2482						.device
2483						.allocator()
2484						.destroy_image(entry.image, &mut entry.alloc);
2485				}
2486			}
2487		}
2488	}
2489
2490	/// Return the bindless storage-buffer index for runtime-owned storage.
2491	pub(crate) fn storage_descriptor_index(&self, storage: &Storage) -> Result<u32> {
2492		let state = self.state.borrow();
2493		let buffer = storage
2494			.buffer()
2495			.ok_or_else(|| Error::invalid_argument("UI source storage must not be empty"))?;
2496		if !storage.belongs_to(&state.device) {
2497			return Err(Error::invalid_argument(
2498				"UI source storage belongs to a different Runtime",
2499			));
2500		}
2501		Ok(buffer.descriptor_index())
2502	}
2503
2504	/// Record one UI raster composition followed by an exact RGBA8 readback.
2505	///
2506	/// The pass records on the graphics pool: `record` draws into `image` as a
2507	/// color attachment, then the same command buffer transitions it to
2508	/// TRANSFER_SRC and copies it into the returned readback storage.
2509	/// This is the private Vulkan seam used by the backend-neutral UI API. The
2510	/// returned storage becomes host-observable after the returned event completes.
2511	pub(crate) fn submit_ui_readback(
2512		&self,
2513		image: vk::Image,
2514		width: u32,
2515		height: u32,
2516		record: impl FnOnce(&vk::Device, vk::CommandBuffer) -> Result<()>,
2517	) -> Result<(Event, Storage)> {
2518		let byte_len = usize::try_from(width)
2519			.ok()
2520			.and_then(|w| usize::try_from(height).ok().and_then(|h| w.checked_mul(h)))
2521			.and_then(|pixels| pixels.checked_mul(4))
2522			.ok_or_else(|| Error::out_of_range("UI readback byte count overflows usize"))?;
2523		let mut state = self.state.borrow_mut();
2524		let readback = Storage::new_from_bytes(&state.device, &vec![0_u8; byte_len])?;
2525		let readback_buffer = readback
2526			.buffer()
2527			.ok_or_else(|| Error::internal("non-empty UI readback has no Vulkan buffer"))?
2528			.raw();
2529		let device = state.device.clone();
2530		let command = device.record_presentation_commands(|command_buffer| {
2531			record(device.raw(), command_buffer)?;
2532			let range = vk::ImageSubresourceRange::new()
2533				.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2534				.set_level_count(1)
2535				.set_layer_count(1);
2536			let to_copy = vk::ImageMemoryBarrier2::new()
2537				.set_src_stage_mask(vk::PipelineStageFlagBits2::COLOR_ATTACHMENT_OUTPUT_BIT)
2538				.set_src_access_mask(vk::AccessFlagBits2::COLOR_ATTACHMENT_WRITE_BIT)
2539				.set_dst_stage_mask(vk::PipelineStageFlagBits2::COPY_BIT)
2540				.set_dst_access_mask(vk::AccessFlagBits2::TRANSFER_READ_BIT)
2541				.set_old_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
2542				.set_new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
2543				.set_image(image)
2544				.set_subresource_range(range);
2545			unsafe {
2546				device.pipeline_barrier(
2547					command_buffer,
2548					&(vk::DependencyInfo::new()
2549						.set_image_memory_barriers(std::slice::from_ref(&to_copy))
2550						.map_err(Error::from)?),
2551				)?;
2552				device.cmd_copy_image_to_buffer(
2553					command_buffer,
2554					image,
2555					vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
2556					readback_buffer,
2557					&[vk::BufferImageCopy::new()
2558						.set_image_subresource(
2559							vk::ImageSubresourceLayers::new()
2560								.set_aspect_mask(vk::ImageAspectFlagBits::COLOR_BIT)
2561								.set_layer_count(1),
2562						)
2563						.set_image_extent(vk::Extent3D {
2564							width,
2565							height,
2566							depth: 1,
2567						})],
2568				)?;
2569			}
2570			Ok(())
2571		})?;
2572		let event = submit_recorded(&mut state, command)?;
2573		readback.mark_submitted(event.clone());
2574		Ok((event, readback))
2575	}
2576
2577	/// Record one mesh draw into `target` and submit it on the graphics queue.
2578	///
2579	/// `push_data` is raw push-constant bytes; `push_stages` selects which
2580	/// shader stages are visible to those bytes.
2581	#[allow(clippy::too_many_arguments)]
2582	pub(crate) fn record_and_submit_mesh_frame(
2583		&self,
2584		target: &mut RenderTarget,
2585		vertex_buf: &MeshBuffer,
2586		index_buf: &MeshBuffer,
2587		index_count: u32,
2588		clear_color: [f32; 4],
2589		push_data: &[u8],
2590		push_stages: vk::ShaderStageFlags,
2591		pipeline: vk::Pipeline,
2592		pipeline_layout: vk::PipelineLayout,
2593		descriptor_sets: &[vk::DescriptorSet],
2594	) -> Result<Event> {
2595		let mut state = self.state.borrow_mut();
2596		let command = state.device.record_mesh_frame(
2597			target,
2598			vertex_buf.raw(),
2599			index_buf.raw(),
2600			index_count,
2601			clear_color,
2602			push_data,
2603			push_stages,
2604			pipeline,
2605			pipeline_layout,
2606			descriptor_sets,
2607		)?;
2608		submit_recorded(&mut state, command)
2609	}
2610
2611	/// Record one vertexless graphics frame and submit it on the graphics queue.
2612	///
2613	/// No vertex or index buffers are bound; the vertex shader derives
2614	/// geometry from `SV_VertexID` (fullscreen-triangle pipelines such as the
2615	/// canvas grid).
2616	#[allow(clippy::too_many_arguments)]
2617	pub(crate) fn record_and_submit_vertexless_frame(
2618		&self,
2619		target: &mut RenderTarget,
2620		vertex_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_vertexless_frame(
2630			target,
2631			vertex_count,
2632			clear_color,
2633			push_data,
2634			push_stages,
2635			pipeline,
2636			pipeline_layout,
2637			descriptor_sets,
2638		)?;
2639		submit_recorded(&mut state, command)
2640	}
2641
2642	/// Record one scene frame (multiple draws) and submit it on the graphics queue.
2643	///
2644	/// `draws` is sorted so that opaque entries come before blend entries by the
2645	/// caller. Both opaque and blend commands share `pipeline_layout`; the device
2646	/// function switches to `blend_pipeline` for entries with `is_blend == true`.
2647	#[allow(clippy::too_many_arguments)]
2648	pub(crate) fn record_and_submit_scene_frame(
2649		&self,
2650		target: &mut RenderTarget,
2651		vertex_buf: &MeshBuffer,
2652		index_buf: &MeshBuffer,
2653		clear_color: [f32; 4],
2654		push_stages: vk::ShaderStageFlags,
2655		pipeline: vk::Pipeline,
2656		blend_pipeline: vk::Pipeline,
2657		pipeline_layout: vk::PipelineLayout,
2658		scene_set: vk::DescriptorSet,
2659		draws: &[SceneDrawCmd],
2660	) -> Result<Event> {
2661		let mut state = self.state.borrow_mut();
2662		let command = state.device.record_scene_frame(
2663			target,
2664			vertex_buf.raw(),
2665			index_buf.raw(),
2666			clear_color,
2667			push_stages,
2668			pipeline,
2669			blend_pipeline,
2670			pipeline_layout,
2671			scene_set,
2672			draws,
2673		)?;
2674		submit_recorded(&mut state, command)
2675	}
2676
2677	/// Create the flat-color material Vulkan pipeline, borrowing the device.
2678	pub(crate) fn create_flat_color_pipeline(&self) -> Result<GraphicsPipeline> {
2679		self.state.borrow().device.create_flat_color_pipeline()
2680	}
2681
2682	/// Create the procedural canvas-grid Vulkan pipeline, borrowing the device.
2683	pub(crate) fn create_canvas_grid_pipeline(&self) -> Result<GraphicsPipeline> {
2684		self.state.borrow().device.create_canvas_grid_pipeline()
2685	}
2686
2687	/// Create the owned descriptor set layouts for the unlit pipeline.
2688	pub(crate) fn create_unlit_descriptor_layouts(&self) -> Result<UnlitDescriptorLayouts> {
2689		self.state.borrow().device.create_unlit_descriptor_layouts()
2690	}
2691
2692	pub(crate) fn create_unlit_descriptor_arena(
2693		&self,
2694		layout: vk::DescriptorSetLayout,
2695		set_count: u32,
2696	) -> Result<UnlitDescriptorArena> {
2697		self
2698			.state
2699			.borrow()
2700			.device
2701			.create_unlit_descriptor_arena(layout, set_count)
2702	}
2703
2704	/// Create the owned descriptor set layouts for the Surface pipeline.
2705	pub(crate) fn create_surface_descriptor_layouts(&self) -> Result<SurfaceDescriptorLayouts> {
2706		self
2707			.state
2708			.borrow()
2709			.device
2710			.create_surface_descriptor_layouts()
2711	}
2712
2713	pub(crate) fn create_surface_descriptor_arena(
2714		&self,
2715		scene_layout: vk::DescriptorSetLayout,
2716		material_layout: vk::DescriptorSetLayout,
2717		set_count: u32,
2718		max_materials_per_slot: u32,
2719	) -> Result<SurfaceDescriptorArena> {
2720		self.state.borrow().device.create_surface_descriptor_arena(
2721			scene_layout,
2722			material_layout,
2723			set_count,
2724			max_materials_per_slot,
2725		)
2726	}
2727
2728	/// Create the unlit textured Vulkan pipeline, borrowing the device.
2729	pub(crate) fn create_unlit_pipeline(
2730		&self,
2731		sampler_layout: vk::DescriptorSetLayout,
2732	) -> Result<GraphicsPipeline> {
2733		self
2734			.state
2735			.borrow()
2736			.device
2737			.create_unlit_pipeline(sampler_layout)
2738	}
2739
2740	/// Create the Surface PBR Vulkan pipeline, borrowing the device.
2741	pub(crate) fn create_surface_pipeline(
2742		&self,
2743		scene_layout: vk::DescriptorSetLayout,
2744		material_layout: vk::DescriptorSetLayout,
2745	) -> Result<GraphicsPipeline> {
2746		self
2747			.state
2748			.borrow()
2749			.device
2750			.create_surface_pipeline(scene_layout, material_layout)
2751	}
2752
2753	/// Create the Surface transparent-blend pipeline, borrowing the device.
2754	///
2755	/// Reuses the `layout` from the opaque Surface pipeline so the
2756	/// descriptor sets remain compatible.
2757	pub(crate) fn create_surface_blend_pipeline(
2758		&self,
2759		layout: vk::PipelineLayout,
2760	) -> Result<GraphicsPipeline> {
2761		self
2762			.state
2763			.borrow()
2764			.device
2765			.create_surface_blend_pipeline(layout)
2766	}
2767
2768	pub(crate) fn create_storage(&self, bytes: &[u8]) -> Result<Storage> {
2769		let mut state = self.state.borrow_mut();
2770		let device = state.device.clone();
2771		state.session.create_storage(&device, bytes)
2772	}
2773
2774	pub(crate) fn validate_storage_owner(&self, storage: &Storage) -> Result<()> {
2775		if !storage.belongs_to(&self.state.borrow().device) {
2776			return Err(Error::invalid_argument(
2777				"storage belongs to a different Runtime",
2778			));
2779		}
2780		Ok(())
2781	}
2782
2783	pub(crate) fn create_output_storage(&self, byte_len: usize) -> Result<Storage> {
2784		let mut state = self.state.borrow_mut();
2785		let device = state.device.clone();
2786		state.session.create_output_storage(&device, byte_len)
2787	}
2788
2789	pub(crate) fn begin_stable_resource_frame(&self) -> Result<()> {
2790		self
2791			.state
2792			.borrow_mut()
2793			.session
2794			.begin_stable_resource_frame()
2795	}
2796
2797	pub(crate) fn seal_all_stable_resources_external(&self) -> Result<()> {
2798		self
2799			.state
2800			.borrow_mut()
2801			.session
2802			.seal_all_stable_resources_external()
2803	}
2804
2805	pub(crate) fn seal_stable_resource_inputs(&self) -> Result<()> {
2806		self
2807			.state
2808			.borrow_mut()
2809			.session
2810			.seal_stable_resource_inputs()
2811	}
2812
2813	pub(crate) fn end_stable_resource_frame(&self) {
2814		self.state.borrow_mut().session.end_stable_resource_frame();
2815	}
2816
2817	pub(crate) fn has_pending_work(&self) -> bool {
2818		!self.state.borrow().session.is_empty()
2819	}
2820
2821	pub(crate) fn abort_pending_work(&self) {
2822		self.state.borrow_mut().session.abort();
2823	}
2824
2825	pub(super) fn create_alias_arena(&self, size: usize) -> Result<Buffer> {
2826		let device = self.state.borrow().device.clone();
2827		Buffer::host_visible_alias_arena(&device, size)
2828	}
2829
2830	pub(super) fn release_stable_transient_resources(&self, retired: &[Buffer]) {
2831		self
2832			.state
2833			.borrow_mut()
2834			.session
2835			.release_stable_transient_resources(retired);
2836	}
2837
2838	pub(crate) fn capture_active(&self) -> bool {
2839		self.state.borrow().capture_active
2840	}
2841
2842	pub(crate) fn begin_semantic_lowering(&self) -> Result<SemanticLoweringScope> {
2843		self.state.borrow_mut().session.begin_semantic_lowering()?;
2844		Ok(SemanticLoweringScope {
2845			runtime: self.clone(),
2846			active: true,
2847		})
2848	}
2849
2850	/// Begin a deferred secret-lowering batch. While the returned scope is
2851	/// active, every recorded submission on this runtime defers into the
2852	/// scope's ordered batch instead of queueing; `commit` submits it in
2853	/// order and `Drop` abandons it without submission or waiting.
2854	pub(crate) fn begin_secret_lowering(&self) -> Result<SecretLoweringScope> {
2855		{
2856			let state = self.state.borrow();
2857			if state.capture_active {
2858				return Err(Error::failed_precondition(
2859					"secret lowering cannot begin during capture",
2860				));
2861			}
2862			if state.secret_scope.is_some() {
2863				return Err(Error::failed_precondition(
2864					"a secret lowering scope is already active",
2865				));
2866			}
2867		}
2868		let mut state = self.state.borrow_mut();
2869		state.secret_scope = Some(SecretScopeState {
2870			pending: Vec::new(),
2871			nodes: Vec::new(),
2872		});
2873		Ok(SecretLoweringScope {
2874			runtime: self.clone(),
2875			active: true,
2876		})
2877	}
2878
2879	#[cfg_attr(
2880		not(test),
2881		expect(
2882			dead_code,
2883			reason = "private PQC ownership substrate; no secret algorithm is admitted"
2884		)
2885	)]
2886	pub(super) fn allocate_secret_buffer(&self, bytes: usize) -> Result<SecretBuffer> {
2887		let state = self.state.borrow();
2888		if state.capture_active {
2889			return Err(Error::failed_precondition(
2890				"secret allocation cannot enter capture",
2891			));
2892		}
2893		SecretBuffer::new(&state.device, bytes)
2894	}
2895
2896	#[cfg_attr(
2897		not(test),
2898		expect(
2899			dead_code,
2900			reason = "private PQC ownership substrate; no secret algorithm is admitted"
2901		)
2902	)]
2903	pub(super) fn erase_secret_buffer(
2904		&self,
2905		secret: SecretBuffer,
2906		final_consumer: &Event,
2907	) -> Result<SecretErasure> {
2908		{
2909			let state = self.state.borrow();
2910			if state.capture_active {
2911				return Err(Error::failed_precondition(
2912					"secret erasure cannot enter capture",
2913				));
2914			}
2915			if !secret.belongs_to(&state.device) || !final_consumer.comes_from(&state.device) {
2916				return Err(Error::invalid_argument(
2917					"secret erasure requires its originating Runtime",
2918				));
2919			}
2920		}
2921		// Flush only at this explicit execution boundary. Queue submission waits
2922		// on the preceding runtime epoch, including the exact final consumer.
2923		self.flush_impl(FlushTiming::Untimed)?;
2924		let mut state = self.state.borrow_mut();
2925		let (command, witness) = secret.record_erasure()?;
2926		let event = submit_recorded(&mut state, command)?;
2927		Ok(SecretErasure::new(event, witness))
2928	}
2929
2930	#[cfg_attr(
2931		not(test),
2932		expect(
2933			dead_code,
2934			reason = "private entropy execution; no secret algorithm is admitted"
2935		)
2936	)]
2937	pub(super) fn consume_secret_entropy<const N: usize>(
2938		&self,
2939		entropy: crate::crypto::entropy::Entropy<N>,
2940		consumer: impl FnOnce(&Arc<Device>, vk::CommandBuffer, SecretBinding<'_>) -> Result<()>,
2941	) -> Result<SecretErasure> {
2942		if self.state.borrow().capture_active {
2943			return Err(Error::failed_precondition(
2944				"secret entropy cannot enter capture",
2945			));
2946		}
2947		self.flush_impl(FlushTiming::Untimed)?;
2948		entropy.consume(|bytes| {
2949			let mut state = self.state.borrow_mut();
2950			let secret = SecretBuffer::new(&state.device, N)?;
2951			let (command, witness) = secret.record_entropy_consumer(bytes, consumer)?;
2952			let event = submit_recorded(&mut state, command)?;
2953			Ok(SecretErasure::new(event, witness))
2954		})
2955	}
2956
2957	/// Private qualification route, not public long-lived key generation.
2958	/// Returns only the public encoding and exact erasure of seed/private storage.
2959	#[cfg_attr(
2960		not(test),
2961		expect(dead_code, reason = "ML-KEM secret operation admission is planned")
2962	)]
2963	pub(super) fn prove_mlkem_keygen(
2964		&self,
2965		k: u32,
2966		entropy: crate::crypto::entropy::Entropy<64>,
2967	) -> Result<(Buffer, SecretErasure)> {
2968		if !(2..=4).contains(&k) {
2969			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
2970		}
2971		if self.state.borrow().capture_active {
2972			return Err(Error::failed_precondition(
2973				"ML-KEM secret execution cannot enter capture",
2974			));
2975		}
2976		self
2977			.state
2978			.borrow()
2979			.device
2980			.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemKeygenU8)?;
2981		self.flush_impl(FlushTiming::Untimed)?;
2982		entropy.consume(|bytes| {
2983			let mut state = self.state.borrow_mut();
2984			let public = Buffer::host_visible_storage(
2985				&state.device,
2986				usize::try_from(384 * k + 32)
2987					.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?,
2988			)?;
2989			let private = SecretBuffer::new(
2990				&state.device,
2991				usize::try_from(768 * k + 96)
2992					.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?,
2993			)?;
2994			let seed = SecretBuffer::new(&state.device, 64)?;
2995			let (command, witness) = seed.record_mlkem_keygen(bytes, private, &public, k)?;
2996			let event = submit_recorded(&mut state, command)?;
2997			Ok((public, SecretErasure::new(event, witness)))
2998		})
2999	}
3000
3001	/// Private asynchronous keygen: key readiness and entropy erasure are exact
3002	/// evidence from the same submission. Secret storage never leaves this module.
3003	pub(super) fn generate_mlkem_key(
3004		&self,
3005		k: u32,
3006		entropy: crate::crypto::entropy::Entropy<64>,
3007	) -> Result<(MlKemDeviceKey, SecretErasure)> {
3008		if !(2..=4).contains(&k) {
3009			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3010		}
3011		{
3012			let state = self.state.borrow();
3013			if state.capture_active {
3014				return Err(Error::failed_precondition(
3015					"ML-KEM secret execution cannot enter capture",
3016				));
3017			}
3018			state
3019				.device
3020				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemKeygenU8)?;
3021		}
3022		self.flush_impl(FlushTiming::Untimed)?;
3023		entropy.consume(|bytes| {
3024			let mut state = self.state.borrow_mut();
3025			let public = Buffer::host_visible_storage(
3026				&state.device,
3027				usize::try_from(384 * k + 32)
3028					.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?,
3029			)?;
3030			let private = Arc::new(SecretBuffer::new(
3031				&state.device,
3032				usize::try_from(768 * k + 96)
3033					.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?,
3034			)?);
3035			let seed = SecretBuffer::new(&state.device, 64)?;
3036			let (command, witness) = seed.record_mlkem_retained_keygen(bytes, &private, &public, k)?;
3037			let ready = submit_recorded(&mut state, command)?;
3038			let erasure = SecretErasure::new(ready.clone(), witness);
3039			Ok((
3040				MlKemDeviceKey {
3041					runtime: self.clone(),
3042					private,
3043					public,
3044					k,
3045					ready,
3046				},
3047				erasure,
3048			))
3049		})
3050	}
3051
3052	/// Import caller-supplied FIPS 203 decapsulation-key bytes. The encapsulation
3053	/// key embedded in dk supplies the public transport through a fresh exclusive
3054	/// buffer. Import reports an upload boundary, not a key-validity proof.
3055	pub(super) fn import_mlkem_key(
3056		&self,
3057		k: u32,
3058		decapsulation_key: &[u8],
3059	) -> Result<(MlKemDeviceKey, SecretErasure)> {
3060		if !(2..=4).contains(&k) {
3061			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3062		}
3063		let private_len = usize::try_from(768 * k + 96)
3064			.map_err(|_| Error::invalid_argument("ML-KEM private extent overflow"))?;
3065		let public_len = usize::try_from(384 * k + 32)
3066			.map_err(|_| Error::invalid_argument("ML-KEM public extent overflow"))?;
3067		if decapsulation_key.len() != private_len {
3068			return Err(Error::invalid_argument(
3069				"ML-KEM decapsulation-key extent mismatch",
3070			));
3071		}
3072		{
3073			let state = self.state.borrow();
3074			if state.capture_active {
3075				return Err(Error::failed_precondition(
3076					"ML-KEM secret execution cannot enter capture",
3077				));
3078			}
3079		}
3080		self.flush_impl(FlushTiming::Untimed)?;
3081		let mut state = self.state.borrow_mut();
3082		let public = Buffer::host_visible_storage(&state.device, public_len)?;
3083		// FIPS 203 dk is dkPKE (384k) || ek (384k+32) || H(ek) || z; the ek
3084		// range is public material by construction.
3085		let ek_offset = usize::try_from(384 * k)
3086			.map_err(|_| Error::invalid_argument("ML-KEM public offset overflow"))?;
3087		public.write(0, &decapsulation_key[ek_offset..ek_offset + public_len])?;
3088		let private = Arc::new(SecretBuffer::new(&state.device, private_len)?);
3089		let (command, witness) = private.record_secret_import(decapsulation_key, |_, _| Ok(()))?;
3090		let ready = submit_recorded(&mut state, command)?;
3091		let erasure = SecretErasure::new(ready.clone(), witness);
3092		Ok((
3093			MlKemDeviceKey {
3094				runtime: self.clone(),
3095				private,
3096				public,
3097				k,
3098				ready,
3099			},
3100			erasure,
3101		))
3102	}
3103
3104	/// Explicit consuming boundary. Submission order includes key generation
3105	/// and all previous consumers; failure leaves storage quarantined.
3106	pub(super) fn erase_mlkem_key(&self, key: MlKemDeviceKey) -> Result<SecretErasure> {
3107		{
3108			let state = self.state.borrow();
3109			if state.capture_active {
3110				return Err(Error::failed_precondition(
3111					"ML-KEM secret erasure cannot enter capture",
3112				));
3113			}
3114			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3115				|| !key.private.belongs_to(&state.device)
3116				|| !key.ready.comes_from(&state.device)
3117			{
3118				return Err(Error::invalid_argument(
3119					"ML-KEM key requires its originating Runtime",
3120				));
3121			}
3122		}
3123		self.flush_impl(FlushTiming::Untimed)?;
3124		let mut state = self.state.borrow_mut();
3125		let (command, witness) = key.private.record_retained_erasure()?;
3126		let event = submit_recorded(&mut state, command)?;
3127		Ok(SecretErasure::new(event, witness))
3128	}
3129
3130	pub(super) fn generate_mldsa_key(
3131		&self,
3132		parameter: u32,
3133		entropy: crate::crypto::entropy::Entropy<32>,
3134	) -> Result<(MlDsaDeviceKey, SecretErasure)> {
3135		let (seed_len, public_len, private_len) =
3136			super::dna::kernel::KernelId::mldsa_keygen_layout(parameter)
3137				.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3138		{
3139			let state = self.state.borrow();
3140			if state.capture_active {
3141				return Err(Error::failed_precondition(
3142					"ML-DSA secret execution cannot enter capture",
3143				));
3144			}
3145			state
3146				.device
3147				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaKeygenU8)?;
3148		}
3149		self.flush_impl(FlushTiming::Untimed)?;
3150		entropy.consume(|bytes| {
3151			let mut state = self.state.borrow_mut();
3152			let public = Buffer::host_visible_storage(
3153				&state.device,
3154				usize::try_from(public_len)
3155					.map_err(|_| Error::invalid_argument("ML-DSA public extent overflow"))?,
3156			)?;
3157			let private = Arc::new(SecretBuffer::new(
3158				&state.device,
3159				usize::try_from(private_len)
3160					.map_err(|_| Error::invalid_argument("ML-DSA private extent overflow"))?,
3161			)?);
3162			let seed = SecretBuffer::new(
3163				&state.device,
3164				usize::try_from(seed_len)
3165					.map_err(|_| Error::invalid_argument("ML-DSA seed extent overflow"))?,
3166			)?;
3167			let (command, witness) =
3168				seed.record_mldsa_retained_keygen(bytes, &private, &public, parameter)?;
3169			let ready = submit_recorded(&mut state, command)?;
3170			let erasure = SecretErasure::new(ready.clone(), witness);
3171			Ok((
3172				MlDsaDeviceKey {
3173					runtime: self.clone(),
3174					private,
3175					public,
3176					parameter,
3177					ready,
3178				},
3179				erasure,
3180			))
3181		})
3182	}
3183
3184	/// Import caller-supplied FIPS 204 signing-key bytes with their public key.
3185	/// The public value is copied into fresh exclusive storage in the same
3186	/// submission, so later caller-side mutation cannot alias the retained key.
3187	/// Import reports an upload boundary, not a key-pair consistency proof.
3188	pub(super) fn import_mldsa_key(
3189		&self,
3190		parameter: u32,
3191		secret_key: &[u8],
3192		public_key: &Buffer,
3193	) -> Result<(MlDsaDeviceKey, SecretErasure)> {
3194		let (_, public_len, private_len) = super::dna::kernel::KernelId::mldsa_keygen_layout(parameter)
3195			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3196		let private_len = usize::try_from(private_len)
3197			.map_err(|_| Error::invalid_argument("ML-DSA private extent overflow"))?;
3198		let public_len = usize::try_from(public_len)
3199			.map_err(|_| Error::invalid_argument("ML-DSA public extent overflow"))?;
3200		if secret_key.len() != private_len || public_key.byte_len() != public_len {
3201			return Err(Error::invalid_argument("ML-DSA key extent mismatch"));
3202		}
3203		{
3204			let state = self.state.borrow();
3205			if state.capture_active {
3206				return Err(Error::failed_precondition(
3207					"ML-DSA secret execution cannot enter capture",
3208				));
3209			}
3210			if !public_key.belongs_to(&state.device) {
3211				return Err(Error::invalid_argument(
3212					"ML-DSA public key requires the same Runtime device",
3213				));
3214			}
3215		}
3216		self.flush_impl(FlushTiming::Untimed)?;
3217		let mut state = self.state.borrow_mut();
3218		let public = Buffer::host_visible_storage(&state.device, public_len)?;
3219		let private = Arc::new(SecretBuffer::new(&state.device, private_len)?);
3220		let (command, witness) = private.record_secret_import(secret_key, |device, command| {
3221			// SAFETY: both public buffers are live, disjoint, equally sized and
3222			// carry transfer usage; the barrier above already orders the copy.
3223			unsafe {
3224				device.cmd_copy_buffer(
3225					command,
3226					public_key.raw(),
3227					public.raw(),
3228					&[vk::BufferCopy::new().set_size(public_len as u64)],
3229				)?;
3230			}
3231			Ok(())
3232		})?;
3233		let ready = submit_recorded(&mut state, command)?;
3234		let erasure = SecretErasure::new(ready.clone(), witness);
3235		Ok((
3236			MlDsaDeviceKey {
3237				runtime: self.clone(),
3238				private,
3239				public,
3240				parameter,
3241				ready,
3242			},
3243			erasure,
3244		))
3245	}
3246
3247	/// Explicit consuming boundary. Submission order includes key generation
3248	/// and all previous consumers; failure leaves storage quarantined.
3249	pub(super) fn erase_mldsa_key(&self, key: MlDsaDeviceKey) -> Result<SecretErasure> {
3250		{
3251			let state = self.state.borrow();
3252			if state.capture_active {
3253				return Err(Error::failed_precondition(
3254					"ML-DSA secret erasure cannot enter capture",
3255				));
3256			}
3257			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3258				|| !key.private.belongs_to(&state.device)
3259				|| !key.public.belongs_to(&state.device)
3260				|| !key.ready.comes_from(&state.device)
3261			{
3262				return Err(Error::invalid_argument(
3263					"ML-DSA key requires its originating Runtime",
3264				));
3265			}
3266		}
3267		self.flush_impl(FlushTiming::Untimed)?;
3268		let mut state = self.state.borrow_mut();
3269		let (command, witness) = key.private.record_retained_erasure()?;
3270		let event = submit_recorded(&mut state, command)?;
3271		Ok(SecretErasure::new(event, witness))
3272	}
3273
3274	/// Private FIPS 204 internal-mu interface. The 64-byte public representative
3275	/// is already H(tr || M', 64); raw messages require separate framing.
3276	/// Returns public signature storage (zero on failure), a public success word,
3277	/// and exact entropy-erasure completion. No rejection count is exposed.
3278	#[cfg_attr(
3279		not(test),
3280		expect(dead_code, reason = "private ML-DSA signing integration")
3281	)]
3282	pub(super) fn sign_mldsa_mu(
3283		&self,
3284		key: &MlDsaDeviceKey,
3285		mu: &Buffer,
3286		entropy: crate::crypto::entropy::Entropy<32>,
3287	) -> Result<(Buffer, Buffer, SecretErasure)> {
3288		let (seed_len, _, mu_len, sig_len) =
3289			super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3290				.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3291		{
3292			let state = self.state.borrow();
3293			if state.capture_active {
3294				return Err(Error::failed_precondition(
3295					"ML-DSA secret execution cannot enter capture",
3296				));
3297			}
3298			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3299				|| !key.private.belongs_to(&state.device)
3300				|| !key.public.belongs_to(&state.device)
3301				|| !key.ready.comes_from(&state.device)
3302				|| !mu.belongs_to(&state.device)
3303				|| mu.size() != mu_len
3304			{
3305				return Err(Error::invalid_argument(
3306					"ML-DSA signing ownership or mu extent mismatch",
3307				));
3308			}
3309			state
3310				.device
3311				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3312		}
3313		self.flush_impl(FlushTiming::Untimed)?;
3314		entropy.consume(|bytes| {
3315			let mut state = self.state.borrow_mut();
3316			let signature = Buffer::host_visible_storage(
3317				&state.device,
3318				usize::try_from((sig_len + 3) & !3)
3319					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3320			)?;
3321			let status = Buffer::host_visible_storage(&state.device, 4)?;
3322			let seed = SecretBuffer::new(
3323				&state.device,
3324				usize::try_from(seed_len)
3325					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3326			)?;
3327			let (command, witness) = seed.record_mldsa_sign(
3328				bytes,
3329				&key.private,
3330				[mu, &signature, &status],
3331				key.parameter,
3332			)?;
3333			let event = submit_recorded(&mut state, command)?;
3334			Ok((signature, status, SecretErasure::new(event, witness)))
3335		})
3336	}
3337
3338	/// Private pure ML-DSA signing. Message/context storage is public, packed
3339	/// and padded to at least one complete word; lengths exclude padding.
3340	/// The device forms H(tr || 0 || context length || context || message, 64).
3341	/// No host key readback, internal-message mode or prehash mode is implied.
3342	pub(super) fn sign_mldsa_message(
3343		&self,
3344		key: &MlDsaDeviceKey,
3345		message: &Buffer,
3346		context: &Buffer,
3347		lengths: [u32; 2],
3348		entropy: crate::crypto::entropy::Entropy<32>,
3349	) -> Result<(Buffer, Buffer, SecretErasure)> {
3350		let (seed_len, _, _, sig_len) = super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3351			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3352		if lengths[1] > 255 {
3353			return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
3354		}
3355		let extents = lengths.map(|length| length.checked_add(3).map(|n| u64::from((n & !3).max(4))));
3356		let [Some(message_extent), Some(context_extent)] = extents else {
3357			return Err(Error::invalid_argument("ML-DSA input extent overflow"));
3358		};
3359		{
3360			let state = self.state.borrow();
3361			if state.capture_active {
3362				return Err(Error::failed_precondition(
3363					"ML-DSA secret execution cannot enter capture",
3364				));
3365			}
3366			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3367				|| !key.private.belongs_to(&state.device)
3368				|| !key.public.belongs_to(&state.device)
3369				|| !key.ready.comes_from(&state.device)
3370				|| !message.belongs_to(&state.device)
3371				|| !context.belongs_to(&state.device)
3372				|| message.size() != message_extent
3373				|| context.size() != context_extent
3374				|| message.raw() == context.raw()
3375			{
3376				return Err(Error::invalid_argument(
3377					"ML-DSA signing ownership, alias or input extent mismatch",
3378				));
3379			}
3380			state
3381				.device
3382				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaMuU8)?;
3383			state
3384				.device
3385				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3386		}
3387		self.flush_impl(FlushTiming::Untimed)?;
3388		entropy.consume(|bytes| {
3389			let mut state = self.state.borrow_mut();
3390			let signature = Buffer::host_visible_storage(
3391				&state.device,
3392				usize::try_from((sig_len + 3) & !3)
3393					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3394			)?;
3395			let status = Buffer::host_visible_storage(&state.device, 4)?;
3396			let seed = SecretBuffer::new(
3397				&state.device,
3398				usize::try_from(seed_len)
3399					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3400			)?;
3401			let (command, witness) = seed.record_mldsa_sign_message(
3402				bytes,
3403				&key.private,
3404				&key.public,
3405				[message, context, &signature, &status],
3406				key.parameter,
3407				lengths,
3408			)?;
3409			let event = submit_recorded(&mut state, command)?;
3410			Ok((signature, status, SecretErasure::new(event, witness)))
3411		})
3412	}
3413
3414	/// Private HashML-DSA framing for a precomputed public digest. The generated
3415	/// NIST hash identity fixes its length and OID. This does not compute the
3416	/// prehash, admit a FIPS-validated module or imply full hash-family coverage.
3417	pub(super) fn sign_mldsa_prehashed(
3418		&self,
3419		key: &MlDsaDeviceKey,
3420		digest: &Buffer,
3421		context: &Buffer,
3422		algorithm: u32,
3423		context_length: u32,
3424		entropy: crate::crypto::entropy::Entropy<32>,
3425	) -> Result<(Buffer, Buffer, SecretErasure)> {
3426		let (seed_len, _, _, sig_len) = super::dna::kernel::KernelId::mldsa_sign_layout(key.parameter)
3427			.ok_or_else(|| Error::invalid_argument("ML-DSA parameter set must be 44, 65 or 87"))?;
3428		if context_length > 255 {
3429			return Err(Error::invalid_argument("ML-DSA context exceeds 255 bytes"));
3430		}
3431		let digest_extent = super::dna::kernel::KernelId::mldsa_prehash_bytes(algorithm)
3432			.ok_or_else(|| Error::invalid_argument("ML-DSA prehash identity is unknown"))?;
3433		let context_extent = u64::from(((context_length + 3) & !3).max(4));
3434		{
3435			let state = self.state.borrow();
3436			if state.capture_active {
3437				return Err(Error::failed_precondition(
3438					"ML-DSA secret execution cannot enter capture",
3439				));
3440			}
3441			if !Rc::ptr_eq(&key.runtime.state, &self.state)
3442				|| !key.private.belongs_to(&state.device)
3443				|| !key.public.belongs_to(&state.device)
3444				|| !key.ready.comes_from(&state.device)
3445				|| !digest.belongs_to(&state.device)
3446				|| !context.belongs_to(&state.device)
3447				|| digest.size() != digest_extent
3448				|| context.size() != context_extent
3449				|| digest.raw() == context.raw()
3450			{
3451				return Err(Error::invalid_argument(
3452					"ML-DSA signing ownership, alias or input extent mismatch",
3453				));
3454			}
3455			state
3456				.device
3457				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaMuU8)?;
3458			state
3459				.device
3460				.require_kernel(super::dna::kernel::KernelId::CryptographyMlDsaSignU8)?;
3461		}
3462		self.flush_impl(FlushTiming::Untimed)?;
3463		entropy.consume(|bytes| {
3464			let mut state = self.state.borrow_mut();
3465			let signature = Buffer::host_visible_storage(
3466				&state.device,
3467				usize::try_from((sig_len + 3) & !3)
3468					.map_err(|_| Error::invalid_argument("ML-DSA signature extent overflow"))?,
3469			)?;
3470			let status = Buffer::host_visible_storage(&state.device, 4)?;
3471			let seed = SecretBuffer::new(
3472				&state.device,
3473				usize::try_from(seed_len)
3474					.map_err(|_| Error::invalid_argument("ML-DSA randomness extent overflow"))?,
3475			)?;
3476			let (command, witness) = seed.record_mldsa_sign_prehashed(
3477				bytes,
3478				&key.private,
3479				&key.public,
3480				[digest, context, &signature, &status],
3481				key.parameter,
3482				algorithm,
3483				context_length,
3484			)?;
3485			let event = submit_recorded(&mut state, command)?;
3486			Ok((signature, status, SecretErasure::new(event, witness)))
3487		})
3488	}
3489
3490	fn validate_mlkem_key(&self, key: &MlKemDeviceKey) -> Result<()> {
3491		let state = self.state.borrow();
3492		if state.capture_active {
3493			return Err(Error::failed_precondition(
3494				"ML-KEM secret execution cannot enter capture",
3495			));
3496		}
3497		if !Rc::ptr_eq(&key.runtime.state, &self.state)
3498			|| !key.private.belongs_to(&state.device)
3499			|| !key.public.belongs_to(&state.device)
3500			|| !key.ready.comes_from(&state.device)
3501		{
3502			return Err(Error::invalid_argument(
3503				"ML-KEM key requires its originating Runtime",
3504			));
3505		}
3506		Ok(())
3507	}
3508
3509	/// Private retained-key route; external encapsulation keys are not admitted.
3510	/// Status is public key canonicality, never ciphertext rejection.
3511	#[cfg_attr(
3512		not(test),
3513		expect(dead_code, reason = "private ML-KEM shared-secret integration")
3514	)]
3515	pub(super) fn encapsulate_mlkem(
3516		&self,
3517		key: &MlKemDeviceKey,
3518		entropy: crate::crypto::entropy::Entropy<32>,
3519	) -> Result<(MlKemSharedSecret, Buffer, Buffer, SecretErasure)> {
3520		self.validate_mlkem_key(key)?;
3521		self.encapsulate_mlkem_public(key.k, &key.public, entropy)
3522	}
3523
3524	/// Private external-public-key qualification route. Canonicality is checked
3525	/// on device before the KEM formula; status never reports ciphertext rejection.
3526	pub(super) fn encapsulate_mlkem_public(
3527		&self,
3528		k: u32,
3529		public: &Buffer,
3530		entropy: crate::crypto::entropy::Entropy<32>,
3531	) -> Result<(MlKemSharedSecret, Buffer, Buffer, SecretErasure)> {
3532		if !(2..=4).contains(&k) {
3533			return Err(Error::invalid_argument("ML-KEM k must be 2, 3 or 4"));
3534		}
3535		{
3536			let state = self.state.borrow();
3537			if state.capture_active {
3538				return Err(Error::failed_precondition(
3539					"ML-KEM secret encapsulation cannot enter capture",
3540				));
3541			}
3542			if !public.belongs_to(&state.device) || public.size() != u64::from(384 * k + 32) {
3543				return Err(Error::invalid_argument(
3544					"ML-KEM public-key ownership or extent mismatch",
3545				));
3546			}
3547		}
3548		self
3549			.state
3550			.borrow()
3551			.device
3552			.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemEncapsU8)?;
3553		self.flush_impl(FlushTiming::Untimed)?;
3554		entropy.consume(|bytes| {
3555			let mut state = self.state.borrow_mut();
3556			let ciphertext_size = 32 * if k == 4 { 11 * k + 5 } else { 10 * k + 4 };
3557			let ciphertext = Buffer::host_visible_storage(
3558				&state.device,
3559				usize::try_from(ciphertext_size)
3560					.map_err(|_| Error::invalid_argument("ML-KEM ciphertext extent overflow"))?,
3561			)?;
3562			let status = Buffer::host_visible_storage(&state.device, 4)?;
3563			let private = Arc::new(SecretBuffer::new(&state.device, 32)?);
3564			let seed = SecretBuffer::new(&state.device, 32)?;
3565			let (command, witness) =
3566				seed.record_mlkem_encaps(bytes, public, &private, &ciphertext, &status, k)?;
3567			let ready = submit_recorded(&mut state, command)?;
3568			let erasure = SecretErasure::new(ready.clone(), witness);
3569			Ok((
3570				MlKemSharedSecret {
3571					runtime: self.clone(),
3572					private,
3573					ready,
3574				},
3575				ciphertext,
3576				status,
3577				erasure,
3578			))
3579		})
3580	}
3581
3582	/// Retained generated keys only. A malformed ciphertext of the correct size
3583	/// follows implicit rejection entirely on device; no rejection flag escapes.
3584	pub(super) fn decapsulate_mlkem(
3585		&self,
3586		key: &MlKemDeviceKey,
3587		ciphertext: &Buffer,
3588	) -> Result<(MlKemSharedSecret, SecretErasure)> {
3589		self.validate_mlkem_key(key)?;
3590		let expected = u64::from(
3591			32 * if key.k == 4 {
3592				11 * key.k + 5
3593			} else {
3594				10 * key.k + 4
3595			},
3596		);
3597		{
3598			let state = self.state.borrow();
3599			if !ciphertext.belongs_to(&state.device) || ciphertext.size() != expected {
3600				return Err(Error::invalid_argument(
3601					"ML-KEM ciphertext ownership or extent mismatch",
3602				));
3603			}
3604			state
3605				.device
3606				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemDecapsU8)?;
3607		}
3608		self.flush_impl(FlushTiming::Untimed)?;
3609		let mut state = self.state.borrow_mut();
3610		let private = Arc::new(SecretBuffer::new(&state.device, 32)?);
3611		let (command, witness) = key
3612			.private
3613			.record_mlkem_decaps(ciphertext, &private, key.k)?;
3614		let ready = submit_recorded(&mut state, command)?;
3615		let erasure = SecretErasure::new(ready.clone(), witness);
3616		Ok((
3617			MlKemSharedSecret {
3618				runtime: self.clone(),
3619				private,
3620				ready,
3621			},
3622			erasure,
3623		))
3624	}
3625
3626	pub(super) fn erase_mlkem_shared_secret(
3627		&self,
3628		secret: MlKemSharedSecret,
3629	) -> Result<SecretErasure> {
3630		{
3631			let state = self.state.borrow();
3632			if state.capture_active {
3633				return Err(Error::failed_precondition(
3634					"ML-KEM secret erasure cannot enter capture",
3635				));
3636			}
3637			if !Rc::ptr_eq(&secret.runtime.state, &self.state)
3638				|| !secret.private.belongs_to(&state.device)
3639				|| !secret.ready.comes_from(&state.device)
3640			{
3641				return Err(Error::invalid_argument(
3642					"ML-KEM shared secret requires its originating Runtime",
3643				));
3644			}
3645		}
3646		self.flush_impl(FlushTiming::Untimed)?;
3647		let mut state = self.state.borrow_mut();
3648		let (command, witness) = secret.private.record_retained_erasure()?;
3649		let event = submit_recorded(&mut state, command)?;
3650		Ok(SecretErasure::new(event, witness))
3651	}
3652
3653	/// Declassification boundary: the shared secret stays private while a
3654	/// keyed hash absorbs public info and emits only public derived bytes.
3655	pub(super) fn derive_mlkem_shared_secret(
3656		&self,
3657		secret: &MlKemSharedSecret,
3658		info: &Buffer,
3659		info_len: u32,
3660		output_len: u32,
3661	) -> Result<(Buffer, SecretErasure)> {
3662		{
3663			let state = self.state.borrow();
3664			if state.capture_active {
3665				return Err(Error::failed_precondition(
3666					"ML-KEM shared-secret derivation cannot enter capture",
3667				));
3668			}
3669			if !Rc::ptr_eq(&secret.runtime.state, &self.state)
3670				|| !secret.private.belongs_to(&state.device)
3671				|| !secret.ready.comes_from(&state.device)
3672			{
3673				return Err(Error::invalid_argument(
3674					"ML-KEM shared secret requires its originating Runtime",
3675				));
3676			}
3677			if !info.belongs_to(&state.device) {
3678				return Err(Error::invalid_argument(
3679					"ML-KEM derivation info requires the originating device",
3680				));
3681			}
3682			state
3683				.device
3684				.require_kernel(super::dna::kernel::KernelId::CryptographyMlKemSharedDeriveU8)?;
3685		}
3686		self.flush_impl(FlushTiming::Untimed)?;
3687		let mut state = self.state.borrow_mut();
3688		let output = Buffer::host_visible_storage(
3689			&state.device,
3690			usize::try_from(output_len)
3691				.map_err(|_| Error::invalid_argument("ML-KEM derivation extent overflow"))?,
3692		)?;
3693		let (command, witness) = secret
3694			.private
3695			.record_shared_derive(info, &output, info_len, output_len)?;
3696		let event = submit_recorded(&mut state, command)?;
3697		Ok((output, SecretErasure::new(event, witness)))
3698	}
3699
3700	pub(crate) fn checkpoint(&self, timed: bool) -> Result<Event> {
3701		self.checkpoint_impl(if timed {
3702			FlushTiming::Fresh
3703		} else {
3704			FlushTiming::Untimed
3705		})
3706	}
3707
3708	/// Checkpoint with a caller-owned timestamp pair. The pair is retained
3709	/// through command retirement but not exposed on the returned event.
3710	pub(crate) fn checkpoint_timed_with(&self, pair: &super::TimestampPair) -> Result<Event> {
3711		self.checkpoint_impl(FlushTiming::Borrowed(pair.clone()))
3712	}
3713
3714	fn checkpoint_impl(&self, timing: FlushTiming) -> Result<Event> {
3715		let timed = !matches!(timing, FlushTiming::Untimed);
3716		if let Some(event) = self.flush_impl(timing)? {
3717			return Ok(event);
3718		}
3719		if timed {
3720			return Err(Error::failed_precondition(
3721				"timed checkpoint requires pending eager work",
3722			));
3723		}
3724		let mut state = self.state.borrow_mut();
3725		let command = state.device.record_empty()?;
3726		submit_recorded(&mut state, command)
3727	}
3728
3729	pub(crate) fn record_semantic(
3730		&self,
3731		dispatch: ComputeDispatch<'_>,
3732		semantic: SemanticDispatch<'_>,
3733	) -> Result<()> {
3734		let mut state = self.state.borrow_mut();
3735		let device = state.device.clone();
3736		state.session.record_semantic(&device, dispatch, semantic)
3737	}
3738
3739	pub(crate) fn compute_shared_memory_bytes(&self) -> u32 {
3740		self.state.borrow().device.compute_shared_memory_bytes()
3741	}
3742
3743	pub(crate) fn uses_compatibility_profile(&self) -> bool {
3744		self.state.borrow().device.physical().profile
3745			== super::device::features::ExecutionProfile::Compatibility
3746	}
3747
3748	pub(crate) fn linear_dispatch_grid(&self, count: u32, group_size: u32) -> Result<[u32; 3]> {
3749		self
3750			.state
3751			.borrow()
3752			.device
3753			.linear_dispatch_grid(count, group_size)
3754	}
3755
3756	/// Queried per-dimension compute dispatch group limits of the selected device.
3757	pub(crate) fn max_compute_work_group_count(&self) -> [u32; 3] {
3758		self.state.borrow().device.max_compute_work_group_count()
3759	}
3760
3761	pub(crate) fn record_optional_semantic(
3762		&self,
3763		dispatch: ComputeDispatch<'_>,
3764		semantic: OptionalSemanticDispatch<'_>,
3765	) -> Result<()> {
3766		let mut state = self.state.borrow_mut();
3767		let device = state.device.clone();
3768		state
3769			.session
3770			.record_optional_semantic(&device, dispatch, semantic)
3771	}
3772
3773	pub(crate) fn record_fused_semantic(
3774		&self,
3775		dispatch: ComputeDispatch<'_>,
3776		semantics: &[SemanticDispatch<'_>],
3777	) -> Result<()> {
3778		let mut state = self.state.borrow_mut();
3779		let device = state.device.clone();
3780		state
3781			.session
3782			.record_fused_semantic(&device, dispatch, semantics)
3783	}
3784
3785	pub(crate) fn record_split_semantic(
3786		&self,
3787		dispatches: &[ComputeDispatch<'_>],
3788		semantic: SemanticDispatch<'_>,
3789	) -> Result<()> {
3790		let mut state = self.state.borrow_mut();
3791		let device = state.device.clone();
3792		state
3793			.session
3794			.record_split_semantic(&device, dispatches, semantic)
3795	}
3796
3797	pub(crate) fn record_split_optional_semantic(
3798		&self,
3799		dispatches: &[ComputeDispatch<'_>],
3800		semantic: OptionalSemanticDispatch<'_>,
3801	) -> Result<()> {
3802		let mut state = self.state.borrow_mut();
3803		let device = state.device.clone();
3804		state
3805			.session
3806			.record_split_optional_semantic(&device, dispatches, semantic)
3807	}
3808
3809	pub(crate) fn record_audio_semantic(
3810		&self,
3811		dispatch: ComputeDispatch<'_>,
3812		semantic: AudioSemanticDispatch<'_>,
3813	) -> Result<()> {
3814		let mut state = self.state.borrow_mut();
3815		let device = state.device.clone();
3816		state
3817			.session
3818			.record_audio_semantic(&device, dispatch, semantic)
3819	}
3820
3821	pub(crate) fn record_image_semantic(
3822		&self,
3823		dispatch: ComputeDispatch<'_>,
3824		semantic: ImageSemanticDispatch<'_>,
3825	) -> Result<()> {
3826		let mut state = self.state.borrow_mut();
3827		let device = state.device.clone();
3828		state
3829			.session
3830			.record_image_semantic(&device, dispatch, semantic)
3831	}
3832
3833	pub(crate) fn record_image_split_semantic(
3834		&self,
3835		dispatches: &[ComputeDispatch<'_>],
3836		semantic: ImageSemanticDispatch<'_>,
3837	) -> Result<()> {
3838		let mut state = self.state.borrow_mut();
3839		let device = state.device.clone();
3840		state
3841			.session
3842			.record_image_split_semantic(&device, dispatches, semantic)
3843	}
3844
3845	pub(crate) fn record_audio_split_semantic(
3846		&self,
3847		dispatches: &[ComputeDispatch<'_>],
3848		semantic: AudioSemanticDispatch<'_>,
3849	) -> Result<()> {
3850		let mut state = self.state.borrow_mut();
3851		let device = state.device.clone();
3852		state
3853			.session
3854			.record_audio_split_semantic(&device, dispatches, semantic)
3855	}
3856
3857	pub(crate) fn attach_semantic_autograd(
3858		&self,
3859		matrix_value: u64,
3860		sequence: u64,
3861	) -> Result<Option<(super::SemanticOpId, u64)>> {
3862		self
3863			.state
3864			.borrow_mut()
3865			.session
3866			.attach_autograd(matrix_value, sequence)
3867	}
3868
3869	pub(crate) fn semantic_operation_count(&self) -> usize {
3870		self.state.borrow().session.semantic_operation_count()
3871	}
3872
3873	pub(crate) fn complete_semantic_autograd(
3874		&self,
3875		forward: super::SemanticOpId,
3876		sequence: u64,
3877		generation: u64,
3878		backward_first: usize,
3879	) -> Result<()> {
3880		self
3881			.state
3882			.borrow_mut()
3883			.session
3884			.complete_autograd(forward, sequence, generation, backward_first)
3885	}
3886
3887	pub(crate) fn flush(&self) -> Result<Option<Event>> {
3888		self.flush_impl(FlushTiming::Untimed)
3889	}
3890
3891	fn flush_impl(&self, timing: FlushTiming) -> Result<Option<Event>> {
3892		let mut state = self.state.borrow_mut();
3893		if state.capture_active {
3894			return Err(Error::failed_precondition(
3895				"cannot submit eager work while execution capture is active",
3896			));
3897		}
3898		let device = state.device.clone();
3899		let Some(pending) = state.session.take(&device, &[])? else {
3900			return Ok(None);
3901		};
3902		let runs = pending.graph.queue_runs();
3903		if runs.len() > 1 {
3904			let start = state.next_epoch;
3905			let completion = (|| {
3906				if matches!(timing, FlushTiming::Borrowed(_)) {
3907					return Err(Error::missing_capability(
3908						"borrowed timing requires a single queue family",
3909					));
3910				}
3911				let timed = matches!(timing, FlushTiming::Fresh);
3912				let mut commands = RecordedBatch::new(&device);
3913				for run in runs {
3914					let command = device
3915						.record_reusable_graph_range(&pending.graph, run.nodes)?
3916						.submission();
3917					commands.push(if timed {
3918						device.time_reusable_command(command)?
3919					} else {
3920						command
3921					});
3922				}
3923				submit_recorded_batch(&mut state, commands, timed)
3924			})();
3925			return match completion {
3926				Ok(event) => {
3927					pending.mark_submitted(&event);
3928					Ok(Some(event))
3929				}
3930				Err(error) => {
3931					if state.next_epoch != start {
3932						pending.graph.invalidate_video_owners();
3933					}
3934					pending.mark_failed();
3935					Err(error)
3936				}
3937			};
3938		}
3939		let borrowed = matches!(timing, FlushTiming::Borrowed(_));
3940		let recorded = match timing {
3941			FlushTiming::Untimed => state.device.record_compute_graph(&pending.graph),
3942			FlushTiming::Fresh => state.device.record_timed_compute_graph(&pending.graph),
3943			FlushTiming::Borrowed(pair) => state
3944				.device
3945				.record_timed_compute_graph_with(&pending.graph, pair),
3946		};
3947		let recorded = recorded.map(|mut command| {
3948			if borrowed {
3949				command.suppress_event_timing();
3950			}
3951			command
3952		});
3953		match recorded {
3954			Ok(command) => match submit_recorded(&mut state, command) {
3955				Ok(event) => {
3956					pending.mark_submitted(&event);
3957					Ok(Some(event))
3958				}
3959				Err(error) => {
3960					pending.mark_failed();
3961					Err(error)
3962				}
3963			},
3964			Err(error) => {
3965				pending.mark_failed();
3966				Err(error)
3967			}
3968		}
3969	}
3970
3971	fn submit_plan(&self, plan: &ExecutionPlan, timed: bool) -> Result<Event> {
3972		if !plan.belongs_to(self) {
3973			return Err(Error::invalid_argument(
3974				"execution plan belongs to another runtime",
3975			));
3976		}
3977		self.flush()?;
3978		let mut state = self.state.borrow_mut();
3979		let ranges = match plan.submission_ranges(&state.device) {
3980			Ok(ranges) => ranges,
3981			Err(error) => {
3982				plan.mark_failed();
3983				return Err(error);
3984			}
3985		};
3986		// One submission range maps to one command buffer; ranges are
3987		// bounded by queue runs, so each command stays on one queue family.
3988		// Recording against the full graph keeps both sides of every
3989		// cross-family ownership transfer — the producer range emits the
3990		// release and the consumer range's first hazard emits the acquire.
3991		let start = state.next_epoch;
3992		let completion = (|| {
3993			plan.graph().validate_video_owners()?;
3994			let mut commands = RecordedBatch::new(&state.device);
3995			if plan.graph().has_video() {
3996				for range in ranges {
3997					commands.push(
3998						state
3999							.device
4000							.record_fresh_graph_range(plan.graph(), range, timed)?,
4001					);
4002				}
4003				plan.count_command_recording();
4004			} else if ranges.len() > plan.graph().queue_runs().len() {
4005				for range in ranges {
4006					let command = state
4007						.device
4008						.record_reusable_graph_range(plan.graph(), range)?
4009						.submission();
4010					commands.push(if timed {
4011						state.device.time_reusable_command(command)?
4012					} else {
4013						command
4014					});
4015				}
4016			} else {
4017				for command in plan.reusable_commands(&state.device)? {
4018					commands.push(if timed {
4019						state.device.time_reusable_command(command)?
4020					} else {
4021						command
4022					});
4023				}
4024			}
4025			submit_recorded_batch(&mut state, commands, timed)
4026		})();
4027		match completion {
4028			Ok(event) => {
4029				plan.mark_submitted(&event);
4030				Ok(event)
4031			}
4032			Err(error) => {
4033				if state.next_epoch != start {
4034					plan.graph().invalidate_video_owners();
4035				}
4036				plan.mark_failed();
4037				Err(error)
4038			}
4039		}
4040	}
4041}
4042
4043impl SemanticLoweringScope {
4044	/// Record one private physical dispatch owned by this composite lowering.
4045	pub(crate) fn record_physical(&self, dispatch: ComputeDispatch<'_>) -> Result<()> {
4046		let mut state = self.runtime.state.borrow_mut();
4047		let device = state.device.clone();
4048		state.session.record_physical_lowering(&device, dispatch)
4049	}
4050
4051	pub(crate) fn commit(mut self, semantic: SemanticDispatch<'_>) -> Result<()> {
4052		let result = self
4053			.runtime
4054			.state
4055			.borrow_mut()
4056			.session
4057			.finish_semantic_lowering(semantic);
4058		self.active = false;
4059		result.map(|_| ())
4060	}
4061
4062	pub(crate) fn commit_optional(mut self, semantic: OptionalSemanticDispatch<'_>) -> Result<()> {
4063		let result = self
4064			.runtime
4065			.state
4066			.borrow_mut()
4067			.session
4068			.finish_optional_semantic_lowering(semantic);
4069		self.active = false;
4070		result.map(|_| ())
4071	}
4072
4073	pub(crate) fn commit_quant(mut self, semantic: QuantSemanticDispatch<'_>) -> Result<()> {
4074		let result = self
4075			.runtime
4076			.state
4077			.borrow_mut()
4078			.session
4079			.finish_quant_semantic_lowering(semantic);
4080		self.active = false;
4081		result.map(|_| ())
4082	}
4083}
4084
4085impl Drop for SemanticLoweringScope {
4086	fn drop(&mut self) {
4087		if !self.active {
4088			return;
4089		}
4090		self
4091			.runtime
4092			.state
4093			.borrow_mut()
4094			.session
4095			.cancel_semantic_lowering();
4096	}
4097}
4098
4099struct CaptureGuard {
4100	runtime: RuntimeHandle,
4101	active: bool,
4102	/// Heap descriptor writes issued before capture began; the delta at
4103	/// finish is this plan's binding cost (OA-CC-21 census).
4104	descriptor_writes_before: u64,
4105}
4106
4107/// Movable private recording transaction used by stateful domain sessions.
4108pub(crate) struct RecordingTransaction {
4109	guard: Option<CaptureGuard>,
4110}
4111
4112impl RecordingTransaction {
4113	pub(crate) fn begin(runtime: RuntimeHandle) -> Result<Self> {
4114		Ok(Self {
4115			guard: Some(CaptureGuard::begin(runtime)?),
4116		})
4117	}
4118
4119	pub(crate) fn submit(mut self, timed: bool) -> Result<Event> {
4120		let guard = self.guard.take().expect("recording transaction guard");
4121		let runtime = guard.runtime.clone();
4122		let plan = guard.finish(&[])?;
4123		runtime.submit_plan(&plan, timed)
4124	}
4125}
4126
4127impl CaptureGuard {
4128	fn begin(runtime: RuntimeHandle) -> Result<Self> {
4129		{
4130			let mut state = runtime.state.borrow_mut();
4131			if state.capture_active {
4132				return Err(Error::failed_precondition(
4133					"nested execution capture is not supported",
4134				));
4135			}
4136			if !state.session.is_empty() {
4137				return Err(Error::failed_precondition(
4138					"pending eager work must be submitted before execution capture",
4139				));
4140			}
4141			state.session.begin_capture()?;
4142			state.capture_active = true;
4143		}
4144		let descriptor_writes_before = runtime.descriptor_write_count();
4145		Ok(Self {
4146			runtime,
4147			active: true,
4148			descriptor_writes_before,
4149		})
4150	}
4151
4152	fn finish(mut self, observed_outputs: &[&Matrix]) -> Result<ExecutionPlan> {
4153		let pending = {
4154			let mut state = self.runtime.state.borrow_mut();
4155			let device = state.device.clone();
4156			let pending = match state.session.take(&device, observed_outputs) {
4157				Ok(pending) => pending,
4158				Err(error) => {
4159					state.session.abort_capture();
4160					state.capture_active = false;
4161					self.active = false;
4162					return Err(error);
4163				}
4164			};
4165			state.session.end_capture();
4166			state.capture_active = false;
4167			self.active = false;
4168			pending
4169		};
4170		let Some(pending) = pending else {
4171			return Err(Error::failed_precondition(
4172				"execution capture recorded no executable work",
4173			));
4174		};
4175		pending.mark_captured();
4176		let mut plan = ExecutionPlan::new(self.runtime.clone(), pending, false)?;
4177		plan.set_descriptor_write_count(
4178			self
4179				.runtime
4180				.descriptor_write_count()
4181				.saturating_sub(self.descriptor_writes_before),
4182		);
4183		Ok(plan)
4184	}
4185
4186	fn finish_preserving(mut self, observed_outputs: &[&Matrix]) -> Result<ExecutionPlan> {
4187		let pending = {
4188			let mut state = self.runtime.state.borrow_mut();
4189			let pending = state.session.snapshot(&state.device, observed_outputs);
4190			state.capture_active = false;
4191			self.active = false;
4192			state.session.end_capture();
4193			pending?
4194		};
4195		let Some(pending) = pending else {
4196			return Err(Error::failed_precondition(
4197				"execution capture recorded no executable work",
4198			));
4199		};
4200		let mut plan = ExecutionPlan::new(self.runtime.clone(), pending, true)?;
4201		plan.set_descriptor_write_count(
4202			self
4203				.runtime
4204				.descriptor_write_count()
4205				.saturating_sub(self.descriptor_writes_before),
4206		);
4207		plan.validate_training_replay_safety()?;
4208		let mut state = self.runtime.state.borrow_mut();
4209		plan.precompile(&state.device)?;
4210		state.session.commit_captured_snapshot()?;
4211		Ok(plan)
4212	}
4213}
4214
4215impl Drop for CaptureGuard {
4216	fn drop(&mut self) {
4217		if !self.active {
4218			return;
4219		}
4220		let mut state = self.runtime.state.borrow_mut();
4221		state.session.abort_capture();
4222		state.capture_active = false;
4223	}
4224}
4225
4226fn require_immediate_batch(state: &RuntimeState) -> Result<()> {
4227	if state.capture_active || state.secret_scope.is_some() {
4228		return Err(Error::failed_precondition(
4229			"an immediate command batch requires an runtime outside capture and secret lowering",
4230		));
4231	}
4232	Ok(())
4233}
4234
4235/// Submit a fully recorded batch through the runtime timeline and publish
4236/// its last exact epoch. A failed submit leaves the remaining commands in
4237/// the batch guard, which frees them without submitting.
4238fn submit_recorded_batch(
4239	state: &mut RuntimeState,
4240	batch: RecordedBatch,
4241	timed: bool,
4242) -> Result<Event> {
4243	submit_recorded_batch_with(state, batch, timed, submit_recorded)
4244}
4245
4246fn submit_recorded_batch_with(
4247	state: &mut RuntimeState,
4248	mut batch: RecordedBatch,
4249	timed: bool,
4250	mut submit: impl FnMut(&mut RuntimeState, RecordedCommandBuffer) -> Result<Event>,
4251) -> Result<Event> {
4252	require_immediate_batch(state)?;
4253	if !batch.belongs_to(&state.device) {
4254		return Err(Error::invalid_argument(
4255			"command batch belongs to another runtime",
4256		));
4257	}
4258	let count = u64::try_from(batch.len())
4259		.ok()
4260		.filter(|count| *count != 0)
4261		.ok_or_else(|| Error::invalid_argument("command batch must be nonempty"))?;
4262	state
4263		.next_epoch
4264		.checked_add(count)
4265		.ok_or_else(|| Error::resource_exhausted("Vulkan submission epoch exhausted"))?;
4266	let mut statuses = Vec::new();
4267	let mut receipts = Vec::new();
4268	let first_command = batch.next().expect("nonempty command batch");
4269	statuses.extend(first_command.decode_statuses.iter().cloned());
4270	receipts.extend(first_command.encode_receipts.iter().cloned());
4271	let mut completion = submit(state, first_command)?;
4272	let first = timed.then(|| completion.clone());
4273	while let Some(command) = batch.next() {
4274		statuses.extend(command.decode_statuses.iter().cloned());
4275		receipts.extend(command.encode_receipts.iter().cloned());
4276		completion = submit(state, command)?;
4277	}
4278	if let Some(first) = first {
4279		completion.set_timing_start(&first);
4280	}
4281	completion.set_decode_statuses(statuses);
4282	completion.set_encode_receipts(receipts);
4283	Ok(completion)
4284}
4285
4286fn submit_recorded(state: &mut RuntimeState, command: RecordedCommandBuffer) -> Result<Event> {
4287	if let Some(scope) = &mut state.secret_scope {
4288		let index = u64::try_from(scope.pending.len())
4289			.ok()
4290			.and_then(|index| index.checked_add(1));
4291		let Some(epoch) = index.and_then(|index| state.next_epoch.checked_add(index)) else {
4292			state.device.free(command);
4293			return Err(Error::resource_exhausted(
4294				"Vulkan submission epoch exhausted",
4295			));
4296		};
4297		if let Err(error) = state.retirement.prepare() {
4298			state.device.free(command);
4299			return Err(error);
4300		}
4301		let (deferred, ticket) = state.retirement.reserve();
4302		let node = SecretScopeNode {
4303			uses_secret: command.has_secret_use(),
4304			records_erasure: command.has_secret_erasure(),
4305			retains_public: command.has_public_resources(),
4306		};
4307		scope.nodes.push(node);
4308		let timing = command.timing();
4309		scope.pending.push(DeferredSubmission {
4310			epoch,
4311			command,
4312			deferred,
4313			ticket: ticket.clone(),
4314		});
4315		return Ok(Event::new(state.device.clone(), epoch, ticket, timing));
4316	}
4317	let Some(epoch) = state.next_epoch.checked_add(1) else {
4318		state.device.free(command);
4319		return Err(Error::resource_exhausted(
4320			"Vulkan submission epoch exhausted",
4321		));
4322	};
4323	if let Err(error) = state.retirement.prepare() {
4324		state.device.free(command);
4325		return Err(error);
4326	}
4327	if let Err(error) = state.device.submit(&command, epoch) {
4328		state.device.free(command);
4329		return Err(error);
4330	}
4331	let timing = command.timing();
4332	state.next_epoch = epoch;
4333	let retirement = state.retirement.retire(command, epoch)?;
4334	Ok(Event::new(state.device.clone(), epoch, retirement, timing))
4335}
4336
4337#[cfg(test)]
4338#[path = "../../../../test/rs/runtime/secret_runtime_unit.rs"]
4339mod secret_tests;
4340
4341#[cfg(test)]
4342#[path = "../../../../test/rs/runtime/device_owner_unit.rs"]
4343mod device_owner_tests;
4344
4345#[cfg(test)]
4346#[path = "../../../../test/rs/runtime/jit_chain_unit.rs"]
4347mod jit_chain_tests;
4348
4349#[cfg(test)]
4350#[path = "../../../../test/rs/runtime/recorded_batch_unit.rs"]
4351mod recorded_batch_tests;