Skip to main content

logit_loom_executor/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3#![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
22/// Maximum bytes in a buffer media-type label.
23pub const MAX_MEDIA_TYPE_BYTES: usize = 128;
24/// Maximum buffers presented to one local execution.
25pub const MAX_EXECUTION_BUFFERS: usize = 64;
26
27/// Mechanical state of one worker-local executor.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "kebab-case")]
30pub enum ExecutorState {
31    /// No backend state is resident.
32    Unloaded,
33    /// Exact artifacts are resident and no operation is running.
34    Resident,
35    /// One synchronous operation is running.
36    Busy,
37    /// Native or cleanup state is uncertain and must not be reused.
38    Poisoned,
39    /// Cleanup completed and the executor cannot be reused.
40    Closed,
41}
42
43/// Downstream handling required after an execution error.
44#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "kebab-case")]
46pub enum FailureDisposition {
47    /// The request was rejected while resident state remained known.
48    Rejected,
49    /// Cooperative cancellation reached a declared safe boundary.
50    Cancelled,
51    /// Native state or cleanup is uncertain and the executor must be replaced.
52    Poisoned,
53}
54
55/// An error whose effect on resident executor state is explicit.
56pub trait ClassifiedExecutionError: std::error::Error {
57    /// Returns the required downstream handling.
58    fn disposition(&self) -> FailureDisposition;
59}
60
61/// Exact metadata for one borrowed or writable byte buffer.
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct BufferSpec {
65    /// Caller-defined content or allocation identity.
66    pub identity: Digest,
67    /// Exact accessible byte length.
68    pub byte_length: u64,
69    /// Bounded mechanical media type.
70    pub media_type: String,
71}
72
73impl BufferSpec {
74    /// Constructs and validates an exact buffer contract.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error for a zero length or invalid media type.
79    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    /// Validates public bounds without touching storage.
94    ///
95    /// # Errors
96    ///
97    /// Returns the first invalid field.
98    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    /// Returns the identity of this exact metadata.
118    ///
119    /// # Errors
120    ///
121    /// Returns a validation or serialization error.
122    pub fn digest(&self) -> Result<Digest, CoreError> {
123        self.validate()?;
124        Digest::of_serializable("executor-buffer-spec-v1", self)
125    }
126}
127
128/// One validated read-only buffer borrowed for a synchronous operation.
129#[derive(Debug)]
130pub struct InputBuffer<'a> {
131    specification: &'a BufferSpec,
132    bytes: &'a [u8],
133}
134
135impl<'a> InputBuffer<'a> {
136    /// Binds exact metadata to readable bytes.
137    ///
138    /// Content hashing and seal verification remain the caller's
139    /// responsibility; this constructor verifies the exact accessible length.
140    ///
141    /// # Errors
142    ///
143    /// Returns an error when metadata is invalid or the length differs.
144    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    /// Returns exact validated metadata.
161    pub const fn specification(&self) -> &BufferSpec {
162        self.specification
163    }
164
165    /// Returns the readable bytes.
166    pub const fn bytes(&self) -> &[u8] {
167        self.bytes
168    }
169}
170
171/// One exact caller-owned output allocation for a synchronous operation.
172#[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    /// Binds exact metadata to writable storage.
181    ///
182    /// # Errors
183    ///
184    /// Returns an error when metadata is invalid or storage has another size.
185    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    /// Returns exact validated metadata.
203    pub const fn specification(&self) -> &BufferSpec {
204        self.specification
205    }
206
207    /// Returns the complete writable allocation.
208    pub fn bytes_mut(&mut self) -> &mut [u8] {
209        self.bytes
210    }
211
212    /// Records the exact initialized prefix.
213    ///
214    /// # Errors
215    ///
216    /// Returns an error when `written` exceeds the allocation.
217    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    /// Returns the exact initialized prefix length.
229    pub const fn written(&self) -> usize {
230        self.written
231    }
232
233    /// Returns the initialized prefix.
234    pub fn initialized(&self) -> &[u8] {
235        &self.bytes[..self.written]
236    }
237}
238
239/// Cooperative cancellation state owned by the caller.
240pub trait CancellationProbe {
241    /// Reports whether cancellation is currently requested.
242    fn is_cancelled(&self) -> bool;
243}
244
245/// Cancellation probe that never requests a stop.
246#[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/// Evidence returned by explicit session cleanup or close.
256#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(deny_unknown_fields)]
258pub struct CleanupReceipt {
259    /// Backend identity whose state was cleared.
260    pub backend: Digest,
261    /// Session epoch that was invalidated.
262    pub cleared_epoch: u64,
263    /// Whether backend cleanup was confirmed.
264    pub confirmed: bool,
265}
266
267impl CleanupReceipt {
268    /// Validates cleanup evidence.
269    ///
270    /// # Errors
271    ///
272    /// Returns an error when an unconfirmed receipt is presented as success.
273    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
284/// Synchronous, single-owner executor over borrowed storage.
285///
286/// Implementations must not retain input or output slices after a call.
287/// Transport, admission, queueing, and resource allocation remain outside this
288/// trait.
289pub trait LocalExecutor {
290    /// Exact backend-specific plan.
291    type Plan;
292    /// Successful mechanical receipt.
293    type Receipt;
294    /// Classified executor failure.
295    type Error: ClassifiedExecutionError;
296
297    /// Returns current lifecycle state.
298    fn state(&self) -> ExecutorState;
299
300    /// Performs an explicit caller-selected warm operation.
301    ///
302    /// # Errors
303    ///
304    /// Returns a classified request, cancellation, native, or cleanup error.
305    fn warm(
306        &mut self,
307        plan: &Self::Plan,
308        cancellation: &dyn CancellationProbe,
309    ) -> Result<Self::Receipt, Self::Error>;
310
311    /// Executes over already verified borrowed inputs and caller-owned outputs.
312    ///
313    /// # Errors
314    ///
315    /// Returns a classified request, cancellation, native, or cleanup error.
316    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    /// Clears request-local mutable state and advances the backend epoch.
325    ///
326    /// # Errors
327    ///
328    /// Returns a poisoning error when cleanup cannot be confirmed.
329    fn clear_session(&mut self) -> Result<CleanupReceipt, Self::Error>;
330
331    /// Consumes the executor and explicitly releases resident state.
332    ///
333    /// # Errors
334    ///
335    /// Returns a poisoning error when cleanup cannot be confirmed.
336    fn close(self) -> Result<CleanupReceipt, Self::Error>
337    where
338        Self: Sized;
339}
340
341/// Factory that loads one exact worker-local executor from verified artifacts.
342pub trait LocalExecutorFactory {
343    /// Exact backend-specific load plan.
344    type LoadPlan;
345    /// Loaded executor type.
346    type Executor: LocalExecutor;
347    /// Classified load failure.
348    type Error: ClassifiedExecutionError;
349
350    /// Loads exact artifacts without selecting transport or resource policy.
351    ///
352    /// # Errors
353    ///
354    /// Returns a classified validation, compatibility, native, or cleanup
355    /// failure.
356    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}