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