ifc_lite_geometry_runtime/
worker_sweep.rs

1// SPDX-License-Identifier: MPL-2.0
2//! One immutable retained construction; no fallback or implicit replay.
3use super::{BrepHandle, MeshLimits, SmlibWorker, WorkerError};
4use ifc_lite_geometry::document::{
5    RegionQualification, RetainedCompletion, RetainedRequest, RetainedTessellation,
6};
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::Arc;
9
10/// Executor-issued binding of one completion to the live solid it describes.
11/// Public host-trusted completions cannot construct this receipt.
12///
13/// The receipt owns its solid: dropping it releases that one object before the
14/// worker's next command, and never retires the process or another object.
15#[derive(Debug)]
16pub struct RetainedRealization {
17    solid: BrepHandle,
18    completion: RetainedCompletion,
19    owner: crate::RuntimeOwner,
20    lease: Arc<super::objects::ManagedObjectLease>,
21    object_live: Arc<AtomicBool>,
22}
23
24impl RetainedRealization {
25    pub fn solid(&self) -> BrepHandle {
26        self.solid
27    }
28    pub fn completion(&self) -> &RetainedCompletion {
29        &self.completion
30    }
31    pub fn owner(&self) -> &crate::RuntimeOwner {
32        &self.owner
33    }
34    /// Explicit standalone host-trusted escape. Consumes the receipt and hands
35    /// the solid to the caller, who must [`SmlibWorker::release`] it; the
36    /// returned numerical data cannot recreate runtime authority.
37    pub fn into_host_trusted_parts(self) -> (BrepHandle, RetainedCompletion) {
38        self.lease.disarm();
39        (self.solid, self.completion)
40    }
41    /// The producing process is live and the solid has not been released.
42    pub fn validate_live(&self) -> Result<(), WorkerError> {
43        if self.owner.incarnation() == Some(self.solid.worker)
44            && self.object_live.load(Ordering::Acquire)
45        {
46            Ok(())
47        } else {
48            Err(WorkerError::WrongWorker)
49        }
50    }
51}
52
53/// An uncut source-exact face set (#8291): authored triangles with no SDK object.
54#[cfg(feature = "retained-runtime")]
55#[derive(Debug)]
56pub struct RetainedSourceFaceSet {
57    no_solid: BrepHandle,
58    completion: RetainedCompletion,
59    owner: crate::RuntimeOwner,
60    /// The closed solid, built only when a Boolean or copy first consumes it.
61    realized: std::sync::OnceLock<RetainedRealization>,
62}
63#[cfg(feature = "retained-runtime")]
64impl RetainedSourceFaceSet {
65    /// The realized solid, else a handle no operation can resolve.
66    pub fn solid(&self) -> BrepHandle { self.realized.get().map_or(self.no_solid, RetainedRealization::solid) }
67    pub fn completion(&self) -> &RetainedCompletion { &self.completion }
68    pub fn realized(&self) -> Option<&RetainedRealization> { self.realized.get() }
69    pub fn validate_live(&self) -> Result<(), WorkerError> {
70        if let Some(realized) = self.realized.get() { return realized.validate_live(); }
71        if self.owner.incarnation() == Some(self.no_solid.worker) { Ok(()) } else { Err(WorkerError::WrongWorker) }
72    }
73}
74
75#[cfg(feature = "retained-runtime")]
76impl SmlibWorker {
77    /// Seal one source-exact request under this incarnation without a kernel
78    /// call, at the same byte budget a kernel mesh of that size must meet.
79    pub fn seal_source_face_set(&self, request: &RetainedRequest, limits: MeshLimits) -> Result<RetainedSourceFaceSet, WorkerError> {
80        if !self.is_live() || request.worker_incarnation() != self.incarnation() {
81            return Err(WorkerError::WrongWorker);
82        }
83        if request.source_exact_mesh_bytes().is_none_or(|bytes| bytes > limits.max_bytes) {
84            return Err(WorkerError::ResourceLimit("mesh exceeds max_bytes"));
85        }
86        let completion = request.source_exact_completion()
87            .ok_or(WorkerError::InvalidArgument("request is not a decodable source-exact face set"))?;
88        Ok(RetainedSourceFaceSet {
89            no_solid: BrepHandle { worker: self.identity, wire: crate::protocol::WireHandle { session: 0, slot: 0, generation: 0 } },
90            completion,
91            owner: self.retained_owner(),
92            realized: std::sync::OnceLock::new(),
93        })
94    }
95
96    /// Build the closed solid behind a source-exact face set, once. Its kernel mesh
97    /// is dropped: the receipt's budget covers the authored mesh, and only the solid
98    /// is needed from here on.
99    pub fn realize_source_face_set<'a>(&mut self, source: &'a RetainedSourceFaceSet, chord_metres: f64,
100        angle_degrees: f64, limits: MeshLimits) -> Result<&'a RetainedRealization, WorkerError> {
101        if source.realized.get().is_none() {
102            let mut realized = self.evaluate_retained(source.completion.request().clone(), chord_metres, angle_degrees, limits)?;
103            realized.completion.tessellation = Default::default();
104            // Single-threaded executor: the cell was checked empty just above.
105            source.realized.set(realized).map_err(|_| WorkerError::Protocol("face set realized twice"))?;
106        }
107        source.realized.get().ok_or(WorkerError::Protocol("face set realization missing"))
108    }
109}
110
111impl SmlibWorker {
112    /// Independently captured liveness/retirement for this exact process.
113    pub fn retained_owner(&self) -> crate::RuntimeOwner {
114        crate::RuntimeOwner::new(self.process_control(), self.identity)
115    }
116
117    /// Execute one retained source request on the incarnation it was prepared
118    /// for. A stale request, or a curved/disk request this incarnation has not
119    /// qualified, is refused before anything is uploaded. Only the raw authored
120    /// solid is evaluated: no opening, enclosing Boolean or style applies.
121    pub fn evaluate_retained(
122        &mut self,
123        request: RetainedRequest,
124        chord_metres: f64,
125        angle_degrees: f64,
126        limits: MeshLimits,
127    ) -> Result<RetainedRealization, WorkerError> {
128        if !self.is_live() || request.worker_incarnation() != self.incarnation() {
129            return Err(WorkerError::WrongWorker);
130        }
131        let payload = request.payload();
132        let qualified = match payload.qualification {
133            RegionQualification::Rectangle => true,
134            RegionQualification::OrderedRegion => self.regions_qualified,
135            RegionQualification::RationalDisk => self.disks_qualified,
136            RegionQualification::SourceFaceSet => self.face_sets_qualified,
137            _ => false,
138        };
139        if !qualified {
140            return Err(WorkerError::Unqualified(
141                "execute this incarnation's numerical witnesses first",
142            ));
143        }
144        let solid = self.create_sweep(
145            &payload.bytes,
146            payload.format,
147            payload.loops,
148            payload.segments,
149        )?;
150        let mesh = match self.tessellate(solid, chord_metres, angle_degrees, limits) {
151            Ok(mesh) => mesh,
152            Err(error) => {
153                // Never retain an unpublished object: if its cleanup fails the
154                // process is retired. The execution error is reported.
155                if self.release(solid).is_err() {
156                    self.retire();
157                }
158                return Err(error);
159            }
160        };
161        // The adapter publishes sweeps only after manifold/positive-volume
162        // checks: a certified-empty construction is a contract breach.
163        if mesh.is_empty() {
164            self.retire();
165            return Err(WorkerError::Protocol("retained construction sealed empty"));
166        }
167        let (source_from_evaluation, evaluation_from_source) = (
168            payload.source_from_evaluation,
169            payload.evaluation_from_source,
170        );
171        let tessellation = RetainedTessellation {
172            positions: mesh.positions,
173            indices: mesh.indices,
174            flat_corner_normals: mesh.corner_normals,
175            revision_local_faces: mesh.source_faces,
176            source_face_count: mesh.source_face_count,
177            boundary_edges: mesh.boundary_edges,
178            spine_edges: mesh.spine_edges,
179        };
180        Ok(RetainedRealization {
181            lease: self.manage_object(solid)?,
182            object_live: self.object_liveness(solid)?,
183            owner: self.retained_owner(),
184            solid,
185            completion: RetainedCompletion::new(
186                request,
187                tessellation,
188                source_from_evaluation,
189                evaluation_from_source,
190            ),
191        })
192    }
193}