Skip to main content

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