Skip to main content

logit_loom_executor/
whole.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Backend-neutral whole-request execution contracts.
4
5use logit_loom_core::{CoreError, Digest, GenerationPlan};
6use serde::{Deserialize, Serialize};
7
8use crate::{BufferSpec, CancellationProbe, MAX_MEDIA_TYPE_BYTES};
9
10/// Maximum exact input bytes owned by one whole-generation request.
11pub const MAX_WHOLE_GENERATION_INPUT_BYTES: usize = 16 * 1024 * 1024;
12/// Maximum output bytes accepted from one whole-generation backend.
13pub const MAX_WHOLE_GENERATION_OUTPUT_BYTES: usize = 16 * 1024 * 1024;
14/// Maximum opaque evidence objects attached to one terminal result.
15pub const MAX_WHOLE_GENERATION_EVIDENCE: usize = 16;
16/// Maximum bytes in one opaque backend evidence object.
17pub const MAX_WHOLE_GENERATION_EVIDENCE_BYTES: usize = 1024 * 1024;
18
19/// Failure category for a whole-request backend.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "kebab-case")]
22pub enum WholeGenerationFailure {
23    /// The public request was structurally invalid.
24    Rejected,
25    /// The request selected mechanics the backend cannot represent exactly.
26    Unsupported,
27    /// Cooperative cancellation reached a declared backend boundary.
28    Cancelled,
29    /// A caller or backend deadline expired.
30    Deadline,
31    /// Backend execution failed while cleanup remained known.
32    Backend,
33    /// Returned data or receipts violated the selected contract.
34    Protocol,
35    /// Terminal acknowledgement or cleanup could not be confirmed.
36    CommitUncertain,
37}
38
39/// A whole-request error with an explicit failure category.
40pub trait ClassifiedWholeGenerationError: std::error::Error {
41    /// Returns the mechanical failure category.
42    fn failure(&self) -> WholeGenerationFailure;
43}
44
45#[derive(Serialize)]
46struct WholeGenerationRequestIdentity<'a> {
47    input_specification: &'a BufferSpec,
48    input_content: &'a Digest,
49    generation_plan: &'a Digest,
50    maximum_output_bytes: u64,
51}
52
53/// Portable caller-selected sampler semantics for a provider-owned backend.
54///
55/// Physical sampler stages, candidate bounds, and implementation defaults are
56/// deliberately absent. When this value is omitted, the selected backend owns
57/// both temperature and nucleus defaults.
58#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct ProviderOwnedSampler {
61    /// Caller-selected sampling temperature.
62    pub temperature: f32,
63    /// Caller-selected nucleus probability.
64    pub top_p: f32,
65}
66
67impl ProviderOwnedSampler {
68    fn validate(self) -> Result<(), CoreError> {
69        if !self.temperature.is_finite()
70            || !(0.0..=10.0).contains(&self.temperature)
71            || !self.top_p.is_finite()
72            || !(0.0..=1.0).contains(&self.top_p)
73        {
74            return Err(CoreError::invalid(
75                "provider-owned sampler",
76                "temperature or top-p is outside its finite public bound",
77            ));
78        }
79        Ok(())
80    }
81}
82
83/// Portable generation semantics whose physical mechanics remain backend-owned.
84///
85/// A backend accepting this plan must bind its actual selected implementation
86/// and mechanics into terminal evidence. It must not reinterpret this value as
87/// an exact native [`GenerationPlan`].
88#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct ProviderOwnedGenerationPlan {
91    /// Maximum generated tokens.
92    pub max_tokens: u32,
93    /// Exact caller-selected seed.
94    pub seed: u32,
95    /// Optional caller-selected portable sampling semantics.
96    pub sampler: Option<ProviderOwnedSampler>,
97}
98
99impl ProviderOwnedGenerationPlan {
100    /// Validates bounded portable controls.
101    ///
102    /// # Errors
103    ///
104    /// Returns an error for a zero output budget or invalid sampler values.
105    pub fn validate(self) -> Result<(), CoreError> {
106        if self.max_tokens == 0 {
107            return Err(CoreError::invalid(
108                "provider-owned maximum tokens",
109                "must be greater than zero",
110            ));
111        }
112        if let Some(sampler) = self.sampler {
113            sampler.validate()?;
114        }
115        Ok(())
116    }
117
118    fn digest(self) -> Result<Digest, CoreError> {
119        Digest::of_serializable("whole-generation-provider-owned-plan-v1", &self)
120    }
121}
122
123/// Authority boundary selected by a whole-generation request.
124#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
125#[serde(tag = "authority", content = "plan", rename_all = "kebab-case")]
126pub enum WholeGenerationPlan {
127    /// Every native generation mechanic is caller-selected.
128    Exact(GenerationPlan),
129    /// Only portable semantics are caller-selected; physical mechanics remain
130    /// with the selected backend.
131    ProviderOwned(ProviderOwnedGenerationPlan),
132}
133
134/// One validated, owned, backend-neutral generation request.
135#[derive(Clone, Debug)]
136pub struct WholeGenerationRequest {
137    input_specification: BufferSpec,
138    input_bytes: Vec<u8>,
139    input_content: Digest,
140    generation_plan: WholeGenerationPlan,
141    generation_plan_identity: Digest,
142    maximum_output_bytes: usize,
143    identity: Digest,
144}
145
146impl WholeGenerationRequest {
147    /// Constructs a bounded request and binds its exact bytes and mechanics.
148    ///
149    /// # Errors
150    ///
151    /// Returns an error when the buffer metadata, exact length, generation
152    /// plan, or input/output bounds are invalid.
153    pub fn new(
154        input_specification: BufferSpec,
155        input_bytes: Vec<u8>,
156        generation_plan: GenerationPlan,
157        maximum_output_bytes: usize,
158    ) -> Result<Self, CoreError> {
159        generation_plan.validate()?;
160        let generation_plan_identity = generation_plan.digest()?;
161        Self::build(
162            input_specification,
163            input_bytes,
164            WholeGenerationPlan::Exact(generation_plan),
165            generation_plan_identity,
166            maximum_output_bytes,
167            "whole-generation-request-v1",
168        )
169    }
170
171    /// Constructs a bounded request whose physical mechanics remain
172    /// provider-owned.
173    ///
174    /// # Errors
175    ///
176    /// Returns an error when the buffer metadata, exact length, portable
177    /// generation controls, or input/output bounds are invalid.
178    pub fn new_provider_owned(
179        input_specification: BufferSpec,
180        input_bytes: Vec<u8>,
181        generation_plan: ProviderOwnedGenerationPlan,
182        maximum_output_bytes: usize,
183    ) -> Result<Self, CoreError> {
184        generation_plan.validate()?;
185        let generation_plan_identity = generation_plan.digest()?;
186        Self::build(
187            input_specification,
188            input_bytes,
189            WholeGenerationPlan::ProviderOwned(generation_plan),
190            generation_plan_identity,
191            maximum_output_bytes,
192            "whole-generation-request-v2",
193        )
194    }
195
196    fn build(
197        input_specification: BufferSpec,
198        input_bytes: Vec<u8>,
199        generation_plan: WholeGenerationPlan,
200        generation_plan_identity: Digest,
201        maximum_output_bytes: usize,
202        identity_domain: &'static str,
203    ) -> Result<Self, CoreError> {
204        input_specification.validate()?;
205        if input_bytes.is_empty() || input_bytes.len() > MAX_WHOLE_GENERATION_INPUT_BYTES {
206            return Err(CoreError::invalid(
207                "whole generation input",
208                format!("must contain 1..={MAX_WHOLE_GENERATION_INPUT_BYTES} exact bytes"),
209            ));
210        }
211        let input_length = u64::try_from(input_bytes.len())
212            .map_err(|_| CoreError::invalid("whole generation input", "length exceeds u64"))?;
213        if input_specification.byte_length != input_length {
214            return Err(CoreError::invalid(
215                "whole generation input",
216                "length does not match the buffer specification",
217            ));
218        }
219        if maximum_output_bytes == 0 || maximum_output_bytes > MAX_WHOLE_GENERATION_OUTPUT_BYTES {
220            return Err(CoreError::invalid(
221                "whole generation output bound",
222                format!("must be in 1..={MAX_WHOLE_GENERATION_OUTPUT_BYTES}"),
223            ));
224        }
225        let input_content = Digest::of_bytes("whole-generation-input-content-v1", &input_bytes);
226        let maximum_output_bytes_u64 = u64::try_from(maximum_output_bytes)
227            .map_err(|_| CoreError::invalid("whole generation output bound", "exceeds u64"))?;
228        let identity = Digest::of_serializable(
229            identity_domain,
230            &WholeGenerationRequestIdentity {
231                input_specification: &input_specification,
232                input_content: &input_content,
233                generation_plan: &generation_plan_identity,
234                maximum_output_bytes: maximum_output_bytes_u64,
235            },
236        )?;
237        Ok(Self {
238            input_specification,
239            input_bytes,
240            input_content,
241            generation_plan,
242            generation_plan_identity,
243            maximum_output_bytes,
244            identity,
245        })
246    }
247
248    /// Returns the exact request identity.
249    pub const fn identity(&self) -> &Digest {
250        &self.identity
251    }
252
253    /// Returns the exact input buffer contract.
254    pub const fn input_specification(&self) -> &BufferSpec {
255        &self.input_specification
256    }
257
258    /// Returns the exact owned input bytes.
259    pub fn input_bytes(&self) -> &[u8] {
260        &self.input_bytes
261    }
262
263    /// Returns the input content identity.
264    pub const fn input_content_identity(&self) -> &Digest {
265        &self.input_content
266    }
267
268    /// Returns the selected generation authority and validated plan.
269    pub const fn generation_plan(&self) -> &WholeGenerationPlan {
270        &self.generation_plan
271    }
272
273    /// Returns the exact generation-plan identity.
274    pub const fn generation_plan_identity(&self) -> &Digest {
275        &self.generation_plan_identity
276    }
277
278    /// Returns the caller-selected maximum output bytes.
279    pub const fn maximum_output_bytes(&self) -> usize {
280        self.maximum_output_bytes
281    }
282}
283
284/// Bounded opaque backend evidence retained with a terminal result.
285#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
286#[serde(deny_unknown_fields)]
287pub struct WholeGenerationEvidence {
288    /// Mechanical evidence media type.
289    pub media_type: String,
290    /// Exact content identity.
291    pub identity: Digest,
292    /// Exact evidence bytes.
293    pub bytes: Vec<u8>,
294}
295
296impl WholeGenerationEvidence {
297    /// Constructs bounded evidence and computes its content identity.
298    ///
299    /// # Errors
300    ///
301    /// Returns an error for an invalid media type or byte bound.
302    pub fn new(media_type: impl Into<String>, bytes: Vec<u8>) -> Result<Self, CoreError> {
303        let media_type = media_type.into();
304        validate_media_type("whole generation evidence media type", &media_type)?;
305        if bytes.is_empty() || bytes.len() > MAX_WHOLE_GENERATION_EVIDENCE_BYTES {
306            return Err(CoreError::invalid(
307                "whole generation evidence",
308                format!("must contain 1..={MAX_WHOLE_GENERATION_EVIDENCE_BYTES} bytes"),
309            ));
310        }
311        let identity = Digest::of_bytes("whole-generation-evidence-v1", &bytes);
312        Ok(Self {
313            media_type,
314            identity,
315            bytes,
316        })
317    }
318}
319
320/// Backend-neutral terminal receipt before caller durability is committed.
321#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct WholeGenerationReceipt {
324    /// Exact originating request.
325    pub request: Digest,
326    /// Exact input content.
327    pub input: Digest,
328    /// Exact generation mechanics.
329    pub plan: Digest,
330    /// Exact output bytes.
331    pub output: Digest,
332    /// Selected backend contract or implementation identity.
333    pub backend: Digest,
334    /// Exact opaque evidence identities in declared order.
335    pub evidence: Vec<Digest>,
336    /// The backend reported a verified terminal result.
337    pub terminal_verified: bool,
338}
339
340/// Verified output held before terminal acknowledgement.
341#[derive(Clone, Debug, PartialEq, Eq)]
342pub struct WholeGenerationOutput {
343    specification: BufferSpec,
344    bytes: Vec<u8>,
345    evidence: Vec<WholeGenerationEvidence>,
346    receipt: WholeGenerationReceipt,
347}
348
349impl WholeGenerationOutput {
350    /// Constructs a bounded verified terminal result for one request.
351    ///
352    /// # Errors
353    ///
354    /// Returns an error when output or evidence violates public bounds.
355    pub fn new(
356        request: &WholeGenerationRequest,
357        backend: Digest,
358        media_type: impl Into<String>,
359        bytes: Vec<u8>,
360        evidence: Vec<WholeGenerationEvidence>,
361    ) -> Result<Self, CoreError> {
362        let media_type = media_type.into();
363        validate_media_type("whole generation output media type", &media_type)?;
364        if bytes.is_empty() || bytes.len() > request.maximum_output_bytes {
365            return Err(CoreError::invalid(
366                "whole generation output",
367                "is empty or exceeds the request output bound",
368            ));
369        }
370        if evidence.len() > MAX_WHOLE_GENERATION_EVIDENCE {
371            return Err(CoreError::invalid(
372                "whole generation evidence",
373                format!("exceeds {MAX_WHOLE_GENERATION_EVIDENCE} objects"),
374            ));
375        }
376        let output_identity = Digest::of_bytes("whole-generation-output-v1", &bytes);
377        let byte_length = u64::try_from(bytes.len())
378            .map_err(|_| CoreError::invalid("whole generation output", "length exceeds u64"))?;
379        let specification = BufferSpec::new(output_identity.clone(), byte_length, media_type)?;
380        let receipt = WholeGenerationReceipt {
381            request: request.identity.clone(),
382            input: request.input_content.clone(),
383            plan: request.generation_plan_identity.clone(),
384            output: output_identity,
385            backend,
386            evidence: evidence.iter().map(|item| item.identity.clone()).collect(),
387            terminal_verified: true,
388        };
389        Ok(Self {
390            specification,
391            bytes,
392            evidence,
393            receipt,
394        })
395    }
396
397    /// Returns exact output metadata.
398    pub const fn specification(&self) -> &BufferSpec {
399        &self.specification
400    }
401
402    /// Returns exact output bytes.
403    pub fn bytes(&self) -> &[u8] {
404        &self.bytes
405    }
406
407    /// Returns bounded opaque backend evidence.
408    pub fn evidence(&self) -> &[WholeGenerationEvidence] {
409        &self.evidence
410    }
411
412    /// Returns the verified pre-commit receipt.
413    pub const fn receipt(&self) -> &WholeGenerationReceipt {
414        &self.receipt
415    }
416}
417
418/// Caller evidence that a verified terminal result was durably persisted.
419#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
420#[serde(deny_unknown_fields)]
421pub struct DurabilityReceipt {
422    /// Caller-owned durable record identity.
423    pub identity: Digest,
424}
425
426impl DurabilityReceipt {
427    /// Wraps an exact caller-owned durable record identity.
428    #[must_use]
429    pub const fn new(identity: Digest) -> Self {
430        Self { identity }
431    }
432}
433
434/// Evidence that terminal acknowledgement completed after caller durability.
435#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
436#[serde(deny_unknown_fields)]
437pub struct WholeGenerationCommitReceipt {
438    /// Exact originating request.
439    pub request: Digest,
440    /// Exact output bytes.
441    pub output: Digest,
442    /// Caller-owned durable record.
443    pub durability: Digest,
444    /// Selected backend contract or implementation identity.
445    pub backend: Digest,
446    /// Whether terminal acknowledgement and required cleanup were confirmed.
447    pub acknowledged: bool,
448}
449
450impl WholeGenerationCommitReceipt {
451    /// Constructs confirmed commit evidence from verified output.
452    #[must_use]
453    pub fn confirmed(output: &WholeGenerationOutput, durability: &DurabilityReceipt) -> Self {
454        Self {
455            request: output.receipt.request.clone(),
456            output: output.receipt.output.clone(),
457            durability: durability.identity.clone(),
458            backend: output.receipt.backend.clone(),
459            acknowledged: true,
460        }
461    }
462
463    /// Validates confirmed acknowledgement evidence.
464    ///
465    /// # Errors
466    ///
467    /// Returns an error when acknowledgement was not confirmed.
468    pub fn validate(&self) -> Result<(), CoreError> {
469        if !self.acknowledged {
470            return Err(CoreError::invalid(
471                "whole generation commit receipt",
472                "terminal acknowledgement was not confirmed",
473            ));
474        }
475        Ok(())
476    }
477}
478
479/// A verified terminal result awaiting caller durability and acknowledgement.
480///
481/// Implementations must not acknowledge backend success before `commit`.
482/// `abort` and `Drop` must make a best effort to release request-local state
483/// without representing the operation as committed.
484pub trait PendingGeneration: Send {
485    /// Classified backend failure.
486    type Error: ClassifiedWholeGenerationError;
487
488    /// Returns verified output before acknowledgement.
489    fn output(&self) -> &WholeGenerationOutput;
490
491    /// Acknowledges the backend terminal result after caller durability.
492    ///
493    /// # Errors
494    ///
495    /// Returns a classified error when acknowledgement or required cleanup
496    /// cannot be confirmed.
497    fn commit(
498        self,
499        durability: DurabilityReceipt,
500    ) -> Result<WholeGenerationCommitReceipt, Self::Error>
501    where
502        Self: Sized;
503
504    /// Aborts without acknowledging successful completion.
505    ///
506    /// # Errors
507    ///
508    /// Returns a classified error when cancellation or cleanup is uncertain.
509    fn abort(self) -> Result<(), Self::Error>
510    where
511        Self: Sized;
512}
513
514/// Synchronous whole-request generation backend.
515///
516/// Transport, admission, scheduling, and resource policy may exist behind
517/// this boundary. The contract exposes no per-token callback, transform,
518/// observer, or checkpoint semantics.
519pub trait WholeGenerationBackend {
520    /// Verified result awaiting caller durability.
521    type Pending: PendingGeneration<Error = Self::Error>;
522    /// Classified backend failure.
523    type Error: ClassifiedWholeGenerationError;
524
525    /// Runs one validated request through a verified terminal result.
526    ///
527    /// # Errors
528    ///
529    /// Returns a classified validation, support, cancellation, deadline,
530    /// backend, or protocol error.
531    fn generate(
532        &mut self,
533        request: WholeGenerationRequest,
534        cancellation: &dyn CancellationProbe,
535    ) -> Result<Self::Pending, Self::Error>;
536}
537
538fn validate_media_type(field: &'static str, media_type: &str) -> Result<(), CoreError> {
539    if media_type.is_empty() || media_type.len() > MAX_MEDIA_TYPE_BYTES || media_type.contains('\0')
540    {
541        return Err(CoreError::invalid(
542            field,
543            format!("must be non-empty, NUL-free, and at most {MAX_MEDIA_TYPE_BYTES} bytes"),
544        ));
545    }
546    Ok(())
547}
548
549#[cfg(test)]
550mod tests {
551    use std::{
552        error::Error,
553        fmt,
554        sync::{
555            Arc, Mutex,
556            atomic::{AtomicBool, Ordering},
557        },
558    };
559
560    use logit_loom_core::SamplingPlan;
561
562    use super::*;
563
564    fn request(input: &[u8]) -> WholeGenerationRequest {
565        WholeGenerationRequest::new(
566            BufferSpec::new(
567                Digest::of_bytes("caller-input", input),
568                u64::try_from(input.len()).unwrap(),
569                "application/json",
570            )
571            .unwrap(),
572            input.to_vec(),
573            GenerationPlan {
574                sampling: SamplingPlan {
575                    top_k: 0,
576                    ..SamplingPlan::default()
577                },
578                max_tokens: 8,
579                biases: Vec::new(),
580                grammar: None,
581                stops: Vec::new(),
582            },
583            128,
584        )
585        .unwrap()
586    }
587
588    fn exact_plan(request: &WholeGenerationRequest) -> GenerationPlan {
589        match request.generation_plan() {
590            WholeGenerationPlan::Exact(plan) => plan.clone(),
591            WholeGenerationPlan::ProviderOwned(_) => {
592                panic!("fixture must retain exact generation mechanics")
593            }
594        }
595    }
596
597    #[test]
598    fn request_identity_binds_exact_bytes_plan_and_output_bound() {
599        let original = request(b"{\"value\":1}");
600        let changed = request(b"{\"value\":2}");
601        assert_ne!(original.identity(), changed.identity());
602
603        let mut plan = exact_plan(&original);
604        plan.max_tokens += 1;
605        let changed_plan = WholeGenerationRequest::new(
606            original.input_specification().clone(),
607            original.input_bytes().to_vec(),
608            plan,
609            original.maximum_output_bytes(),
610        )
611        .unwrap();
612        assert_ne!(original.identity(), changed_plan.identity());
613
614        let changed_bound = WholeGenerationRequest::new(
615            original.input_specification().clone(),
616            original.input_bytes().to_vec(),
617            exact_plan(&original),
618            original.maximum_output_bytes() + 1,
619        )
620        .unwrap();
621        assert_ne!(original.identity(), changed_bound.identity());
622    }
623
624    #[test]
625    fn provider_owned_plan_is_distinct_and_binds_portable_controls() {
626        let input = b"input";
627        let specification = BufferSpec::new(
628            Digest::of_bytes("caller-input", input),
629            u64::try_from(input.len()).unwrap(),
630            "application/json",
631        )
632        .unwrap();
633        let plan = ProviderOwnedGenerationPlan {
634            max_tokens: 8,
635            seed: 7,
636            sampler: None,
637        };
638        let request = WholeGenerationRequest::new_provider_owned(
639            specification.clone(),
640            input.to_vec(),
641            plan,
642            128,
643        )
644        .unwrap();
645        assert_eq!(
646            request.generation_plan(),
647            &WholeGenerationPlan::ProviderOwned(plan)
648        );
649
650        let changed = WholeGenerationRequest::new_provider_owned(
651            specification,
652            input.to_vec(),
653            ProviderOwnedGenerationPlan {
654                max_tokens: 9,
655                ..plan
656            },
657            128,
658        )
659        .unwrap();
660        assert_ne!(request.identity(), changed.identity());
661        assert_ne!(
662            request.generation_plan_identity(),
663            changed.generation_plan_identity()
664        );
665
666        assert!(
667            WholeGenerationRequest::new_provider_owned(
668                request.input_specification().clone(),
669                input.to_vec(),
670                ProviderOwnedGenerationPlan {
671                    max_tokens: 0,
672                    ..plan
673                },
674                128,
675            )
676            .is_err()
677        );
678    }
679
680    #[test]
681    fn request_rejects_mismatched_and_unbounded_storage() {
682        let spec = BufferSpec::new(
683            Digest::of_bytes("caller-input", b"x"),
684            2,
685            "application/json",
686        )
687        .unwrap();
688        assert!(
689            WholeGenerationRequest::new(spec, b"x".to_vec(), exact_plan(&request(b"x")), 1,)
690                .is_err()
691        );
692        let oversized = vec![0_u8; MAX_WHOLE_GENERATION_INPUT_BYTES + 1];
693        let oversized_spec = BufferSpec::new(
694            Digest::of_bytes("caller-input", &oversized),
695            u64::try_from(oversized.len()).unwrap(),
696            "application/octet-stream",
697        )
698        .unwrap();
699        assert!(
700            WholeGenerationRequest::new(oversized_spec, oversized, exact_plan(&request(b"x")), 1,)
701                .is_err()
702        );
703    }
704
705    #[test]
706    fn output_binds_bounded_bytes_and_evidence() {
707        let request = request(b"input");
708        let evidence =
709            WholeGenerationEvidence::new("application/vnd.example.receipt+json", b"{}".to_vec())
710                .unwrap();
711        let output = WholeGenerationOutput::new(
712            &request,
713            Digest::of_bytes("backend", b"fake"),
714            "application/json",
715            b"{\"text\":\"ok\"}".to_vec(),
716            vec![evidence.clone()],
717        )
718        .unwrap();
719        assert_eq!(output.evidence(), &[evidence]);
720        assert_eq!(output.specification().identity, output.receipt().output);
721        assert!(output.receipt().terminal_verified);
722    }
723
724    #[derive(Debug)]
725    struct FakeError(WholeGenerationFailure);
726
727    impl fmt::Display for FakeError {
728        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
729            write!(formatter, "fake {:?}", self.0)
730        }
731    }
732
733    impl Error for FakeError {}
734
735    impl ClassifiedWholeGenerationError for FakeError {
736        fn failure(&self) -> WholeGenerationFailure {
737            self.0
738        }
739    }
740
741    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
742    enum FakeState {
743        Pending,
744        Committed,
745        Aborted,
746        Dropped,
747    }
748
749    struct FakePending {
750        output: WholeGenerationOutput,
751        state: Arc<Mutex<FakeState>>,
752    }
753
754    impl PendingGeneration for FakePending {
755        type Error = FakeError;
756
757        fn output(&self) -> &WholeGenerationOutput {
758            &self.output
759        }
760
761        fn commit(
762            mut self,
763            durability: DurabilityReceipt,
764        ) -> Result<WholeGenerationCommitReceipt, Self::Error> {
765            *self.state.lock().unwrap() = FakeState::Committed;
766            let receipt = WholeGenerationCommitReceipt::confirmed(&self.output, &durability);
767            self.state = Arc::new(Mutex::new(FakeState::Committed));
768            Ok(receipt)
769        }
770
771        fn abort(mut self) -> Result<(), Self::Error> {
772            *self.state.lock().unwrap() = FakeState::Aborted;
773            self.state = Arc::new(Mutex::new(FakeState::Aborted));
774            Ok(())
775        }
776    }
777
778    impl Drop for FakePending {
779        fn drop(&mut self) {
780            let mut state = self.state.lock().unwrap();
781            if *state == FakeState::Pending {
782                *state = FakeState::Dropped;
783            }
784        }
785    }
786
787    struct AtomicCancellation(AtomicBool);
788
789    impl CancellationProbe for AtomicCancellation {
790        fn is_cancelled(&self) -> bool {
791            self.0.load(Ordering::Acquire)
792        }
793    }
794
795    struct FakeBackend {
796        state: Arc<Mutex<FakeState>>,
797    }
798
799    impl WholeGenerationBackend for FakeBackend {
800        type Pending = FakePending;
801        type Error = FakeError;
802
803        fn generate(
804            &mut self,
805            request: WholeGenerationRequest,
806            cancellation: &dyn CancellationProbe,
807        ) -> Result<Self::Pending, Self::Error> {
808            if cancellation.is_cancelled() {
809                return Err(FakeError(WholeGenerationFailure::Cancelled));
810            }
811            let output = WholeGenerationOutput::new(
812                &request,
813                Digest::of_bytes("backend", b"fake"),
814                "text/plain",
815                b"ok".to_vec(),
816                Vec::new(),
817            )
818            .unwrap();
819            Ok(FakePending {
820                output,
821                state: Arc::clone(&self.state),
822            })
823        }
824    }
825
826    #[test]
827    fn pending_result_commits_only_after_durability() {
828        let state = Arc::new(Mutex::new(FakeState::Pending));
829        let mut backend = FakeBackend {
830            state: Arc::clone(&state),
831        };
832        let pending = backend
833            .generate(request(b"input"), &crate::NeverCancel)
834            .unwrap();
835        assert_eq!(*state.lock().unwrap(), FakeState::Pending);
836        let durability = DurabilityReceipt::new(Digest::of_bytes("durability", b"event-record"));
837        let commit = pending.commit(durability.clone()).unwrap();
838        assert_eq!(*state.lock().unwrap(), FakeState::Committed);
839        assert_eq!(commit.durability, durability.identity);
840        commit.validate().unwrap();
841    }
842
843    #[test]
844    fn dropped_result_is_not_committed_and_cancellation_is_classified() {
845        let state = Arc::new(Mutex::new(FakeState::Pending));
846        let mut backend = FakeBackend {
847            state: Arc::clone(&state),
848        };
849        drop(
850            backend
851                .generate(request(b"input"), &crate::NeverCancel)
852                .unwrap(),
853        );
854        assert_eq!(*state.lock().unwrap(), FakeState::Dropped);
855
856        let cancellation = AtomicCancellation(AtomicBool::new(true));
857        let Err(error) = backend.generate(request(b"input"), &cancellation) else {
858            panic!("cancelled request unexpectedly succeeded");
859        };
860        assert_eq!(error.failure(), WholeGenerationFailure::Cancelled);
861    }
862}