Skip to main content

oa/runtime/plan/
serialization.rs

1//! Persisted execution-plan descriptor serialization and validation.
2//!
3//! Donor: `oacpp/source/cpp/lib/oa/runtime/executionPlanSerialization.cpp`.
4//! The envelope contract is donor-identical: an `"OAEXPLAN"` magic, a format
5//! version, a payload byte count, and an FNV-1a 64-bit payload checksum. The
6//! payload is a Rust-native deterministic record of the compiled plan — DNN
7//! planner output, captured resource and binding contracts, the queried device
8//! contract, and the executable graph — with no Vulkan handles, device
9//! addresses, or pointer identities. Validation reserializes the live plan and
10//! requires byte-for-byte equality, matching the donor's cache-revalidation
11//! semantic.
12
13use crate::{Error, Result};
14
15use super::super::{
16	Buffer, BufferAccess, PushConstant,
17	graph::executable::{BufferUse, GraphNode, ResourceLifetime},
18};
19use super::ExecutionPlan;
20
21/// `"OAEXPLAN"` — identical to the donor descriptor magic.
22const DESCRIPTOR_MAGIC: u64 = 0x4E41_4C50_5854_414F;
23/// Rust descriptor payload format version. The donor's version `4` describes
24/// the C++ payload; the Rust payload is its own format lineage and is not
25/// byte-compatible with the donor.
26const DESCRIPTOR_VERSION: u32 = 1;
27const DESCRIPTOR_HEADER_BYTES: usize = 28;
28
29/// Little-endian descriptor writer mirroring the donor's `DescriptorWriter`.
30/// `count` and `string` reject values above the u32 format limit by marking the
31/// writer invalid; callers surface that as `ResourceExhausted`.
32pub(in crate::runtime) struct DescriptorWriter {
33	bytes: Vec<u8>,
34	valid: bool,
35}
36
37impl DescriptorWriter {
38	pub(in crate::runtime) fn new() -> Self {
39		Self {
40			bytes: Vec::new(),
41			valid: true,
42		}
43	}
44
45	pub(in crate::runtime) fn u8(&mut self, value: u8) {
46		self.bytes.push(value);
47	}
48
49	pub(in crate::runtime) fn bool(&mut self, value: bool) {
50		self.u8(u8::from(value));
51	}
52
53	pub(in crate::runtime) fn u32(&mut self, value: u32) {
54		self.bytes.extend_from_slice(&value.to_le_bytes());
55	}
56
57	pub(in crate::runtime) fn u64(&mut self, value: u64) {
58		self.bytes.extend_from_slice(&value.to_le_bytes());
59	}
60
61	pub(in crate::runtime) fn i64(&mut self, value: i64) {
62		self.u64(value.cast_unsigned());
63	}
64
65	pub(in crate::runtime) fn usize(&mut self, value: usize) {
66		self.i64(value as i64);
67	}
68
69	pub(in crate::runtime) fn isize(&mut self, value: isize) {
70		self.i64(value as i64);
71	}
72
73	pub(in crate::runtime) fn count(&mut self, value: usize) {
74		if let Ok(value) = u32::try_from(value) {
75			self.u32(value);
76		} else {
77			self.valid = false;
78			self.u32(0);
79		}
80	}
81
82	pub(in crate::runtime) fn string(&mut self, value: &str) {
83		self.count(value.len());
84		if self.valid && !value.is_empty() {
85			self.bytes.extend_from_slice(value.as_bytes());
86		}
87	}
88
89	pub(in crate::runtime) fn bytes(&mut self, value: &[u8]) {
90		self.bytes.extend_from_slice(value);
91	}
92
93	pub(in crate::runtime) const fn valid(&self) -> bool {
94		self.valid
95	}
96
97	pub(in crate::runtime) fn take(self) -> Vec<u8> {
98		self.bytes
99	}
100}
101
102/// FNV-1a 64-bit checksum, identical to the donor's `descriptorChecksum`.
103fn descriptor_checksum(bytes: &[u8]) -> u64 {
104	let mut hash = 0xcbf2_9ce4_8422_2325_u64;
105	for byte in bytes {
106		hash ^= u64::from(*byte);
107		hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
108	}
109	hash
110}
111
112fn resource_id(lifetimes: &[ResourceLifetime], buffer: &Buffer) -> Result<u32> {
113	let resource = lifetimes
114		.iter()
115		.position(|lifetime| lifetime.buffer.same_as(buffer))
116		.ok_or_else(|| {
117			Error::internal(
118				"compiled execution plan references a buffer outside the captured resource inventory",
119			)
120		})?;
121	u32::try_from(resource)
122		.map_err(|_| Error::resource_exhausted("captured resource identity exceeds u32"))
123}
124
125fn write_resource_contract(plan: &ExecutionPlan, out: &mut DescriptorWriter) -> Result<()> {
126	let lifetimes = plan.graph.resource_lifetimes();
127	out.count(plan.captured_resources.len());
128	for resource in &plan.captured_resources {
129		out.u32(resource.resource());
130		out.u64(resource.byte_len() as u64);
131		out.count(resource.first_access());
132		out.count(resource.last_access());
133		out.u8(
134			u8::from(resource.stable_replay_input())
135				| u8::from(resource.stable_transient()) << 1
136				| u8::from(resource.semantic_external()) << 2
137				| u8::from(resource.observed_output()) << 3,
138		);
139	}
140	out.count(plan.input_bindings.len());
141	for binding in &plan.input_bindings {
142		out.u32(resource_id(&lifetimes, &binding.original)?);
143	}
144	out.count(plan.semantic_bindings.len());
145	for binding in plan.semantic_bindings() {
146		out.u32(binding.value().index());
147		out.u32(binding.resource());
148		out.u8(
149			u8::from(binding.semantic_external())
150				| u8::from(binding.stable_replay_input()) << 1
151				| u8::from(binding.observed_output()) << 2,
152		);
153	}
154	Ok(())
155}
156
157fn write_device_contract(plan: &ExecutionPlan, out: &mut DescriptorWriter) {
158	let info = plan.runtime.device_info();
159	out.u32(info.hardware.vendor_id);
160	out.u32(info.hardware.device_id);
161	out.u8(info.hardware.kind as u8);
162	out.string(&info.hardware.name);
163	out.u64(info.hardware.local_memory_bytes);
164	out.u32(info.hardware.max_compute_shared_memory_bytes);
165	out.u32(info.hardware.max_compute_workgroup_invocations);
166	out.u32(info.hardware.subgroup_size);
167	out.u32(info.hardware.storage_buffer_descriptors);
168	out.u32(info.hardware.storage_image_descriptors);
169	out.bool(info.hardware.graphics);
170	out.bool(info.hardware.swapchain);
171	out.string(&info.software.api_version);
172	out.string(&info.software.driver_name);
173	out.string(&info.software.driver_info);
174	out.u32(info.software.driver_version);
175	out.u64(info.software.capability_identity);
176	out.bool(info.software.shader_float16);
177	out.bool(info.software.shader_float64);
178	out.bool(info.software.shader_integer_dot_product);
179	out.count(info.software.cooperative_matrix_tuple_count);
180}
181
182fn write_executable_graph(plan: &ExecutionPlan, out: &mut DescriptorWriter) -> Result<()> {
183	let lifetimes = plan.graph.resource_lifetimes();
184	let nodes = plan.graph.nodes();
185	out.count(nodes.len());
186	for (index, graph_node) in nodes.iter().enumerate() {
187		let (operation, semantic_ops, contract) = graph_node.semantic();
188		out.string(operation);
189		out.count(plan.graph.barriers_before(index).len());
190		out.count(semantic_ops.len());
191		for operation in semantic_ops {
192			out.u32(operation.index());
193		}
194		out.u64(contract);
195		let node = match graph_node {
196			GraphNode::Compute(node) => node,
197			GraphNode::BufferCopy(copy) => {
198				// Compute kernel IDs occupy the u16 range in the v1 descriptor.
199				out.u32(u32::MAX);
200				out.u64(copy.bytes);
201				write_buffer_uses(out, &lifetimes, &copy.buffers)?;
202				continue;
203			}
204			GraphNode::VideoDecode(video) => {
205				out.u32(u32::MAX - 2);
206				let descriptor = video.descriptor_words();
207				out.count(descriptor.len());
208				for word in descriptor {
209					out.u32(word);
210				}
211				continue;
212			}
213			GraphNode::VideoEncode(video) => {
214				out.u32(u32::MAX - 4);
215				let descriptor = video.descriptor_words();
216				out.count(descriptor.len());
217				for word in descriptor {
218					out.u32(word);
219				}
220				continue;
221			}
222			GraphNode::VideoEncodeInput(video) => {
223				out.u32(u32::MAX - 3);
224				let words = video.copy.descriptor_words();
225				out.count(video.copy.descriptor_words().count());
226				for word in words {
227					out.u32(word);
228				}
229				write_buffer_uses(out, &lifetimes, graph_node.buffers())?;
230				continue;
231			}
232
233			GraphNode::VideoPlanes(video) => {
234				out.u32(u32::MAX - 1);
235				let words = video.copy.descriptor_words();
236				out.count(video.copy.descriptor_words().count());
237				for word in words {
238					out.u32(word);
239				}
240				write_buffer_uses(out, &lifetimes, graph_node.buffers())?;
241				continue;
242			}
243		};
244		out.u32(u32::from(node.kernel as u16));
245		let artifact = node.kernel.artifact();
246		out.u64(artifact.content_id());
247		match artifact.physical_write {
248			None => out.bool(false),
249			Some(contract) => {
250				out.bool(true);
251				out.count(contract.writes.len());
252				for write in contract.writes {
253					out.u8(write.binding);
254					out.u8(write.domain as u8);
255					out.u8(write.partition as u8);
256					out.u8(write.extent as u8);
257					out.u8(write.collision as u8);
258					out.u8(write.tail as u8);
259				}
260				out.u8(contract.workspace as u8);
261			}
262		}
263		write_buffer_uses(out, &lifetimes, &node.buffers)?;
264		out.count(node.push_constants.len());
265		for constant in &node.push_constants {
266			match *constant {
267				PushConstant::U32(value) => {
268					out.u8(0);
269					out.u32(value);
270				}
271				PushConstant::F32(value) => {
272					out.u8(1);
273					out.u32(value.to_bits());
274				}
275			}
276		}
277		for dimension in node.workgroups {
278			out.u32(dimension);
279		}
280		match &node.indirect {
281			None => out.bool(false),
282			Some(indirect) => {
283				out.bool(true);
284				out.u32(resource_id(&lifetimes, &indirect.buffer)?);
285				out.u64(indirect.offset);
286			}
287		}
288	}
289	Ok(())
290}
291
292fn write_buffer_uses(
293	out: &mut DescriptorWriter,
294	lifetimes: &[ResourceLifetime],
295	buffers: &[BufferUse],
296) -> Result<()> {
297	out.count(buffers.len());
298	for buffer_use in buffers {
299		out.u32(resource_id(lifetimes, &buffer_use.buffer)?);
300		out.u64(buffer_use.buffer.byte_len() as u64);
301		out.u8(match buffer_use.access {
302			BufferAccess::Read => 0,
303			BufferAccess::Write => 1,
304			BufferAccess::ReadWrite => 2,
305		});
306	}
307	Ok(())
308}
309
310impl ExecutionPlan {
311	/// Serialize this compiled plan into a deterministic, handle-free
312	/// descriptor suitable for persisting alongside cache metadata.
313	///
314	/// The `"OAEXPLAN"` envelope and FNV-1a checksum match the donor's
315	/// `ExecutionPlan::serializeDescriptor`; the payload is a Rust-native format
316	/// at its own version and is not byte-compatible with the C++ descriptor.
317	///
318	/// # Errors
319	///
320	/// Returns an error when a captured resource identity or serialized count
321	/// exceeds the format limits, or when the compiled plan is internally
322	/// inconsistent.
323	pub fn serialize_descriptor(&self) -> Result<Vec<u8>> {
324		let mut payload = DescriptorWriter::new();
325		payload.u64(self.graph_id);
326		payload.u64(self.device_capability_identity);
327		self.dnn.write_descriptor(&mut payload)?;
328		write_resource_contract(self, &mut payload)?;
329		write_device_contract(self, &mut payload);
330		write_executable_graph(self, &mut payload)?;
331		if !payload.valid() {
332			return Err(Error::resource_exhausted(
333				"execution plan descriptor exceeds the format limits",
334			));
335		}
336		let payload = payload.take();
337		let mut descriptor = DescriptorWriter::new();
338		descriptor.u64(DESCRIPTOR_MAGIC);
339		descriptor.u32(DESCRIPTOR_VERSION);
340		descriptor.u64(payload.len() as u64);
341		descriptor.u64(descriptor_checksum(&payload));
342		descriptor.bytes(&payload);
343		Ok(descriptor.take())
344	}
345
346	/// Validate a persisted descriptor against this compiled plan.
347	///
348	/// The envelope must be well formed and the payload must equal a fresh
349	/// serialization of this plan byte for byte — the donor's cache
350	/// revalidation semantic.
351	///
352	/// # Errors
353	///
354	/// - `InvalidArgument`: truncated header or invalid magic.
355	/// - `FailedPrecondition`: unsupported version or descriptor mismatch.
356	/// - `DataLoss`: invalid payload length or checksum mismatch.
357	pub fn validate_serialized_descriptor(&self, descriptor: &[u8]) -> Result<()> {
358		if descriptor.len() < DESCRIPTOR_HEADER_BYTES {
359			return Err(Error::invalid_argument(
360				"serialized execution plan descriptor is truncated",
361			));
362		}
363		let magic = u64::from_le_bytes(descriptor[0..8].try_into().expect("slice length checked"));
364		let version = u32::from_le_bytes(descriptor[8..12].try_into().expect("slice length checked"));
365		let payload_bytes =
366			u64::from_le_bytes(descriptor[12..20].try_into().expect("slice length checked"));
367		let checksum = u64::from_le_bytes(descriptor[20..28].try_into().expect("slice length checked"));
368		if magic != DESCRIPTOR_MAGIC {
369			return Err(Error::invalid_argument(
370				"serialized execution plan descriptor has an invalid magic value",
371			));
372		}
373		if version != DESCRIPTOR_VERSION {
374			return Err(Error::failed_precondition(
375				"serialized execution plan descriptor version is unsupported",
376			));
377		}
378		if payload_bytes != (descriptor.len() - DESCRIPTOR_HEADER_BYTES) as u64 {
379			return Err(Error::data_loss(
380				"serialized execution plan descriptor has an invalid payload length",
381			));
382		}
383		if descriptor_checksum(&descriptor[DESCRIPTOR_HEADER_BYTES..]) != checksum {
384			return Err(Error::data_loss(
385				"serialized execution plan descriptor checksum does not match",
386			));
387		}
388		let current = self.serialize_descriptor()?;
389		if current != descriptor {
390			return Err(Error::failed_precondition(
391				"serialized execution plan descriptor does not match this compiled plan",
392			));
393		}
394		Ok(())
395	}
396}
397
398#[cfg(test)]
399#[path = "../../../../../test/rs/runtime/plan_serialization_unit.rs"]
400mod tests;