1#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5
6use std::fmt::Debug;
7
8use logit_loom_core::{CoreError, Digest};
9use serde::{Deserialize, Serialize};
10
11mod whole;
12
13pub use whole::{
14 ClassifiedWholeGenerationError, DurabilityReceipt, MAX_WHOLE_GENERATION_EVIDENCE,
15 MAX_WHOLE_GENERATION_EVIDENCE_BYTES, MAX_WHOLE_GENERATION_INPUT_BYTES,
16 MAX_WHOLE_GENERATION_OUTPUT_BYTES, PendingGeneration, ProviderOwnedGenerationPlan,
17 ProviderOwnedSampler, WholeGenerationBackend, WholeGenerationCommitReceipt,
18 WholeGenerationEvidence, WholeGenerationFailure, WholeGenerationOutput, WholeGenerationPlan,
19 WholeGenerationReceipt, WholeGenerationRequest,
20};
21
22pub const MAX_MEDIA_TYPE_BYTES: usize = 128;
24pub const MAX_EXECUTION_BUFFERS: usize = 64;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "kebab-case")]
30pub enum ExecutorState {
31 Unloaded,
33 Resident,
35 Busy,
37 Poisoned,
39 Closed,
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "kebab-case")]
46pub enum FailureDisposition {
47 Rejected,
49 Cancelled,
51 Poisoned,
53}
54
55pub trait ClassifiedExecutionError: std::error::Error {
57 fn disposition(&self) -> FailureDisposition;
59}
60
61#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct BufferSpec {
65 pub identity: Digest,
67 pub byte_length: u64,
69 pub media_type: String,
71}
72
73impl BufferSpec {
74 pub fn new(
80 identity: Digest,
81 byte_length: u64,
82 media_type: impl Into<String>,
83 ) -> Result<Self, CoreError> {
84 let value = Self {
85 identity,
86 byte_length,
87 media_type: media_type.into(),
88 };
89 value.validate()?;
90 Ok(value)
91 }
92
93 pub fn validate(&self) -> Result<(), CoreError> {
99 if self.byte_length == 0 {
100 return Err(CoreError::invalid(
101 "executor buffer length",
102 "must be positive",
103 ));
104 }
105 if self.media_type.is_empty()
106 || self.media_type.len() > MAX_MEDIA_TYPE_BYTES
107 || self.media_type.contains('\0')
108 {
109 return Err(CoreError::invalid(
110 "executor buffer media type",
111 format!("must be non-empty, NUL-free, and at most {MAX_MEDIA_TYPE_BYTES} bytes"),
112 ));
113 }
114 Ok(())
115 }
116
117 pub fn digest(&self) -> Result<Digest, CoreError> {
123 self.validate()?;
124 Digest::of_serializable("executor-buffer-spec-v1", self)
125 }
126}
127
128#[derive(Debug)]
130pub struct InputBuffer<'a> {
131 specification: &'a BufferSpec,
132 bytes: &'a [u8],
133}
134
135impl<'a> InputBuffer<'a> {
136 pub fn new(specification: &'a BufferSpec, bytes: &'a [u8]) -> Result<Self, CoreError> {
145 specification.validate()?;
146 let actual = u64::try_from(bytes.len())
147 .map_err(|_| CoreError::invalid("executor input length", "exceeds u64"))?;
148 if actual != specification.byte_length {
149 return Err(CoreError::invalid(
150 "executor input length",
151 "does not match the exact buffer specification",
152 ));
153 }
154 Ok(Self {
155 specification,
156 bytes,
157 })
158 }
159
160 pub const fn specification(&self) -> &BufferSpec {
162 self.specification
163 }
164
165 pub const fn bytes(&self) -> &[u8] {
167 self.bytes
168 }
169}
170
171#[derive(Debug)]
173pub struct OutputBuffer<'a> {
174 specification: &'a BufferSpec,
175 bytes: &'a mut [u8],
176 written: usize,
177}
178
179impl<'a> OutputBuffer<'a> {
180 pub fn new(specification: &'a BufferSpec, bytes: &'a mut [u8]) -> Result<Self, CoreError> {
186 specification.validate()?;
187 let actual = u64::try_from(bytes.len())
188 .map_err(|_| CoreError::invalid("executor output length", "exceeds u64"))?;
189 if actual != specification.byte_length {
190 return Err(CoreError::invalid(
191 "executor output length",
192 "does not match the exact buffer specification",
193 ));
194 }
195 Ok(Self {
196 specification,
197 bytes,
198 written: 0,
199 })
200 }
201
202 pub const fn specification(&self) -> &BufferSpec {
204 self.specification
205 }
206
207 pub fn bytes_mut(&mut self) -> &mut [u8] {
209 self.bytes
210 }
211
212 pub fn set_written(&mut self, written: usize) -> Result<(), CoreError> {
218 if written > self.bytes.len() {
219 return Err(CoreError::invalid(
220 "executor output written length",
221 "exceeds the output allocation",
222 ));
223 }
224 self.written = written;
225 Ok(())
226 }
227
228 pub const fn written(&self) -> usize {
230 self.written
231 }
232
233 pub fn initialized(&self) -> &[u8] {
235 &self.bytes[..self.written]
236 }
237}
238
239pub trait CancellationProbe {
241 fn is_cancelled(&self) -> bool;
243}
244
245#[derive(Clone, Copy, Debug, Default)]
247pub struct NeverCancel;
248
249impl CancellationProbe for NeverCancel {
250 fn is_cancelled(&self) -> bool {
251 false
252 }
253}
254
255#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(deny_unknown_fields)]
258pub struct CleanupReceipt {
259 pub backend: Digest,
261 pub cleared_epoch: u64,
263 pub confirmed: bool,
265}
266
267impl CleanupReceipt {
268 pub fn validate(&self) -> Result<(), CoreError> {
274 if !self.confirmed {
275 return Err(CoreError::invalid(
276 "executor cleanup receipt",
277 "cleanup was not confirmed",
278 ));
279 }
280 Ok(())
281 }
282}
283
284pub trait LocalExecutor {
290 type Plan;
292 type Receipt;
294 type Error: ClassifiedExecutionError;
296
297 fn state(&self) -> ExecutorState;
299
300 fn warm(
306 &mut self,
307 plan: &Self::Plan,
308 cancellation: &dyn CancellationProbe,
309 ) -> Result<Self::Receipt, Self::Error>;
310
311 fn execute(
317 &mut self,
318 plan: &Self::Plan,
319 inputs: &[InputBuffer<'_>],
320 outputs: &mut [OutputBuffer<'_>],
321 cancellation: &dyn CancellationProbe,
322 ) -> Result<Self::Receipt, Self::Error>;
323
324 fn clear_session(&mut self) -> Result<CleanupReceipt, Self::Error>;
330
331 fn close(self) -> Result<CleanupReceipt, Self::Error>
337 where
338 Self: Sized;
339}
340
341pub trait LocalExecutorFactory {
343 type LoadPlan;
345 type Executor: LocalExecutor;
347 type Error: ClassifiedExecutionError;
349
350 fn load(
357 &self,
358 plan: &Self::LoadPlan,
359 artifacts: &[InputBuffer<'_>],
360 ) -> Result<Self::Executor, Self::Error>;
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 fn specification(length: u64) -> BufferSpec {
368 BufferSpec::new(
369 Digest::of_bytes("test-buffer", b"bytes"),
370 length,
371 "application/octet-stream",
372 )
373 .unwrap()
374 }
375
376 #[test]
377 fn borrowed_buffers_require_exact_lengths() {
378 let specification = specification(3);
379 assert!(InputBuffer::new(&specification, b"abc").is_ok());
380 assert!(InputBuffer::new(&specification, b"ab").is_err());
381
382 let mut exact = [0_u8; 3];
383 assert!(OutputBuffer::new(&specification, &mut exact).is_ok());
384 let mut short = [0_u8; 2];
385 assert!(OutputBuffer::new(&specification, &mut short).is_err());
386 }
387
388 #[test]
389 fn output_tracks_only_the_initialized_prefix() {
390 let specification = specification(4);
391 let mut storage = [0_u8; 4];
392 let mut output = OutputBuffer::new(&specification, &mut storage).unwrap();
393 output.bytes_mut()[..2].copy_from_slice(b"ok");
394 output.set_written(2).unwrap();
395 assert_eq!(output.initialized(), b"ok");
396 assert!(output.set_written(5).is_err());
397 }
398
399 #[test]
400 fn metadata_round_trips_and_rejects_nul() {
401 let specification = specification(7);
402 let json = serde_json::to_string(&specification).unwrap();
403 assert_eq!(
404 serde_json::from_str::<BufferSpec>(&json).unwrap(),
405 specification
406 );
407 assert!(BufferSpec::new(Digest::of_bytes("test-buffer", b"x"), 1, "bad\0type").is_err());
408 }
409}