ifc_lite_geometry/resource/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Explicit admission for audited allocations. This is not an allocator or RSS bound.
3mod account;
4#[cfg(feature = "retained-runtime")]
5mod budget;
6#[cfg(all(feature = "retained-runtime", test))]
7pub use budget::test_clock as budget_test_clock;
8#[cfg(feature = "retained-runtime")]
9pub use budget::{budget_checkpoint, budget_deadline_fired, BudgetStart, ProductBudget};
10// Refs #7955: private dormant resource owner.
11#[cfg(any(
12    all(
13        test,
14        any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
15    ),
16    feature = "retained-runtime"
17))]
18#[cfg_attr(not(test), allow(dead_code))]
19mod owned;
20#[cfg(feature = "retained-runtime")]
21pub(crate) use owned::OwnedResourceContext;
22mod pool;
23mod storage;
24pub(crate) use storage::reserve_headers;
25pub mod mesh;
26pub use account::{ExecutionAccount, Reservation, Usage};
27pub use pool::{ModelResourcePool, RequestAdmission};
28use std::cell::{Cell, RefCell};
29
30/// No new resource limits are imposed unless the caller explicitly opts in.
31#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub enum ExecutionPolicy {
33    #[default]
34    Compatibility,
35    Bounded(ResourceLimits),
36    /// Refuses before invocation until all opaque allocation families are covered.
37    Strict(ResourceLimits),
38}
39/// None means explicitly unlimited; Some(0) admits zero, in every dimension.
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41pub struct ResourceLimits {
42    pub work: Option<u64>,
43    pub copy_bytes: Option<u64>,
44    pub output_bytes: Option<u64>,
45    pub occurrences: Option<u64>,
46    pub live_bytes: Option<u64>,
47}
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
49pub struct Cost {
50    pub work: u64,
51    pub copy_bytes: u64,
52    pub output_bytes: u64,
53    pub occurrences: u64,
54    pub live_bytes: u64,
55}
56pub use ifc_lite_core::resource_stop::{Dimension, ProgramStop, RefusalReason, ResourceFailure};
57thread_local! {
58    static CURRENT: RefCell<Option<ExecutionAccount>> = const { RefCell::new(None) };
59    static SOURCE_STOP: RefCell<Option<ifc_lite_core::execution_owner::SourceStopHandle>> = const { RefCell::new(None) };
60    static TERMINAL: Cell<Option<Option<ProgramStop>>> = const { Cell::new(None) };
61}
62struct TerminalScope;
63impl Drop for TerminalScope {
64    fn drop(&mut self) {
65        TERMINAL.with(|slot| slot.set(None));
66    }
67}
68fn terminal_scope() -> Option<TerminalScope> {
69    TERMINAL.with(|slot| {
70        if slot.get().is_some() {
71            None
72        } else {
73            slot.set(Some(None));
74            Some(TerminalScope)
75        }
76    })
77}
78
79/// Keep terminal stops visible for a complete consumer operation, including
80/// compatibility callers without an execution account. Nested calls share the
81/// existing terminal domain; a fresh domain is restored on return or unwind.
82pub fn with_terminal_scope<T>(
83    operation: impl FnOnce() -> Result<T, ProgramStop>,
84) -> Result<T, ProgramStop> {
85    let _terminal = terminal_scope();
86    check_current()?;
87    let result = operation();
88    check_current()?;
89    result
90}
91
92/// Every [`stop`] in this process, from any thread. A caller that sees the
93/// same count before and after a pass knows no product in it was refused,
94/// cancelled or degraded by resource state, its own or an unrelated scope's
95/// (a rayon wait can run another caller's job under that caller's thread
96/// state). Only the count is shared; no stop state is.
97static STOP_EVENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
98
99/// The number of [`stop`] calls so far in this process.
100pub fn stop_events() -> u64 {
101    STOP_EVENTS.load(std::sync::atomic::Ordering::SeqCst)
102}
103
104/// Whether this thread runs inside any lexical resource scope: an execution
105/// account, a source stop, a terminal domain or (retained builds) an owned
106/// stop observer. Work inside one can be refused or degraded by that scope's
107/// allowance, cancellation or earlier stop, so its output is not a function
108/// of its inputs alone.
109pub fn ambient_scope_active() -> bool {
110    let owned = {
111        #[cfg(any(
112            all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")),
113            feature = "retained-runtime"
114        ))]
115        {
116            owned::OWNED.with(|slot| slot.borrow().is_some())
117        }
118        #[cfg(not(any(
119            all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")),
120            feature = "retained-runtime"
121        )))]
122        {
123            false
124        }
125    };
126    owned
127        || CURRENT.with(|slot| slot.borrow().is_some())
128        || SOURCE_STOP.with(|slot| slot.borrow().is_some())
129        || TERMINAL.with(|slot| slot.get().is_some())
130}
131
132pub fn current_account() -> Option<ExecutionAccount> {
133    CURRENT.with(|slot| slot.borrow().clone())
134}
135pub fn is_active() -> bool {
136    CURRENT.with(|slot| slot.borrow().is_some())
137}
138pub fn check_current() -> Result<(), ProgramStop> {
139    let source = SOURCE_STOP.with(|slot| {
140        slot.borrow()
141            .as_ref()
142            .map_or(Ok(()), |source| source.check())
143    });
144    if let Err(error) = source {
145        return Err(stop(error));
146    }
147    let account = CURRENT.with(|slot| match slot.borrow().as_ref() {
148        Some(a) => a.check(),
149        None => Ok(()),
150    });
151    if let Err(error) = account {
152        return Err(stop(error));
153    }
154    if let Some(error) = current_terminal() {
155        return Err(error);
156    }
157    #[cfg(feature = "retained-runtime")]
158    if let Some(account) = current_account() {
159        account.check_allowance().map_err(stop)?;
160    }
161    Ok(())
162}
163fn current_terminal() -> Option<ProgramStop> {
164    TERMINAL.with(|slot| slot.get().flatten())
165}
166
167/// Poll live stop state without constructing an aggregate result for a live
168/// source-only authority. Presence and the source's atomic stop are read afresh.
169#[inline]
170pub fn is_stopped() -> bool {
171    let source_stopped = SOURCE_STOP.with_borrow(|source| {
172        source
173            .as_ref()
174            .is_some_and(|source| source.check().is_err())
175    });
176    if source_stopped || CURRENT.with_borrow(Option::is_some) {
177        // Keep typed propagation, account polling and first-stop precedence on
178        // the slow path. A boolean observation must latch an actual refusal.
179        check_active_stop()
180    } else {
181        current_terminal().is_some()
182    }
183}
184
185#[cold]
186#[inline(never)]
187fn check_active_stop() -> bool {
188    check_current().is_err()
189}
190
191/// Check controlled source iterations under the opt-in retained budget.
192/// Default builds keep their existing loops unchanged: this is a no-op there,
193/// with no stop, thread-local or account check added.
194#[cfg(feature = "retained-runtime")]
195pub(crate) fn source_step() -> crate::Result<()> {
196    budget::source_step()
197}
198
199pub fn charge(cost: Cost) -> Result<Reservation, ProgramStop> {
200    check_current()?;
201    match current_account() {
202        Some(account) => account.prepare(cost).map_err(stop),
203        None => Ok(Reservation::empty()),
204    }
205}
206pub fn stop(error: ProgramStop) -> ProgramStop {
207    STOP_EVENTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
208    // A deadline is local to the product. Do not poison source, account, owned
209    // or lexical terminal channels when a callback echoes its Cancelled value.
210    #[cfg(feature = "retained-runtime")]
211    if error == ProgramStop::Cancelled && budget_deadline_fired() {
212        return error;
213    }
214    let prior_source = SOURCE_STOP.with(|slot| {
215        slot.borrow()
216            .as_ref()
217            .and_then(|source| source.check().err())
218    });
219    let error = prior_source.unwrap_or(error);
220    let error = current_account().map_or(error, |account| account.stop(error));
221    let source = SOURCE_STOP.with(|slot| slot.borrow().as_ref().map(|source| source.stop(error)));
222    let error = source.unwrap_or(error);
223    #[cfg(any(
224        all(
225            test,
226            any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
227        ),
228        feature = "retained-runtime"
229    ))]
230    let error = owned::record_stop(error);
231    TERMINAL.with(|slot| match (source, slot.get()) {
232        // A validated source chain is authoritative for this lexical domain;
233        // unrelated ambient terminal state is restored by with_source_stop.
234        (Some(_), Some(_)) => {
235            slot.set(Some(Some(error)));
236            error
237        }
238        (_, Some(Some(first))) => first,
239        (_, Some(None)) => {
240            slot.set(Some(Some(error)));
241            error
242        }
243        (_, None) => error,
244    })
245}
246pub fn refused(
247    dimension: Dimension,
248    requested: u64,
249    remaining: u64,
250    reason: RefusalReason,
251) -> ProgramStop {
252    stop(ProgramStop::ResourceRefused(ResourceFailure {
253        dimension,
254        requested,
255        remaining,
256        reason,
257    }))
258}
259pub fn overflow() -> ProgramStop {
260    refused(
261        Dimension::Representation,
262        u64::MAX,
263        0,
264        RefusalReason::Overflow,
265    )
266}
267pub fn allocation_failure() -> ProgramStop {
268    refused(Dimension::LiveBytes, 0, 0, RefusalReason::Allocation)
269}
270
271#[cfg(test)]
272mod boolean_tests;
273#[cfg(test)]
274mod tests;
275
276/// Translate the typed legacy callback error at the first audited boundary.
277/// Source faults (including identical diagnostic text) retain ordinary recovery.
278pub(crate) fn observe<T>(result: crate::Result<T>) -> crate::Result<T> {
279    if let Err(crate::Error::ProgramStopped(error)) = &result {
280        stop(*error);
281    }
282    check_current()?;
283    result
284}
285
286/// Resource-only capability transport for joined source-borrow workers. Cloning
287/// the existing account Arc allocates nothing and transfers no unrelated TLS.
288pub fn current_source_context() -> Option<ifc_lite_core::execution_owner::SourceResourceContext> {
289    current_account().and_then(|account| account.source_context())
290}
291pub fn account_from_source_context(
292    context: &ifc_lite_core::execution_owner::SourceResourceContext,
293) -> Result<ExecutionAccount, ProgramStop> {
294    ExecutionAccount::from_source_context(context).ok_or_else(|| {
295        refused(
296            Dimension::Coverage,
297            0,
298            0,
299            RefusalReason::UnsupportedCoverage,
300        )
301    })
302}
303
304/// Run `operation` with none of this thread's lexical resource state: no
305/// account, source stop, terminal or owned stop observer.
306///
307/// A rayon wait (`join`, `par_iter`) may run an unrelated queued job on the
308/// waiting thread before it returns, such as another element's whole product.
309/// That job is not part of the caller's work: it must not bill the caller's
310/// account, observe the caller's source stop or terminal, or record its own
311/// stop into them. Wrap every rayon wait inside product work in this; the
312/// caller's state is restored on return and on unwind. `operation` itself
313/// must not need the caller's resource state.
314///
315/// This hides RESOURCE state only (including the owned stop observer). Other
316/// per-thread diagnostic capture, such as geometry telemetry transactions and
317/// the CSG census sink, is not scoped by it.
318pub fn detached<T>(operation: impl FnOnce() -> T) -> T {
319    struct Restore {
320        account: Option<ExecutionAccount>,
321        source: Option<ifc_lite_core::execution_owner::SourceStopHandle>,
322        terminal: Option<Option<ProgramStop>>,
323        #[cfg(any(
324            all(
325                test,
326                any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
327            ),
328            feature = "retained-runtime"
329        ))]
330        owned: Option<owned::OwnedResourceContext>,
331    }
332    impl Drop for Restore {
333        fn drop(&mut self) {
334            CURRENT.with(|slot| *slot.borrow_mut() = self.account.take());
335            SOURCE_STOP.with(|slot| *slot.borrow_mut() = self.source.take());
336            TERMINAL.with(|slot| slot.set(self.terminal));
337            #[cfg(any(
338                all(
339                    test,
340                    any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
341                ),
342                feature = "retained-runtime"
343            ))]
344            owned::OWNED.with(|slot| *slot.borrow_mut() = self.owned.take());
345        }
346    }
347    let _restore = Restore {
348        account: CURRENT.with(|slot| slot.borrow_mut().take()),
349        source: SOURCE_STOP.with(|slot| slot.borrow_mut().take()),
350        terminal: TERMINAL.with(Cell::take),
351        #[cfg(any(
352            all(
353                test,
354                any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
355            ),
356            feature = "retained-runtime"
357        ))]
358        owned: owned::OWNED.with(|slot| slot.borrow_mut().take()),
359    };
360    operation()
361}
362
363/// Install only a validated source capability's shared terminal handle. The
364/// lexical guard restores the previous handle on return and unwind.
365pub fn with_source_stop<T>(
366    source: ifc_lite_core::execution_owner::SourceStopHandle,
367    operation: impl FnOnce() -> T,
368) -> T {
369    struct Restore {
370        source: Option<ifc_lite_core::execution_owner::SourceStopHandle>,
371        terminal: Option<Option<ProgramStop>>,
372    }
373    impl Drop for Restore {
374        fn drop(&mut self) {
375            SOURCE_STOP.with(|slot| *slot.borrow_mut() = self.source.take());
376            TERMINAL.with(|slot| slot.set(self.terminal));
377        }
378    }
379    let _restore = Restore {
380        source: SOURCE_STOP.with(|slot| slot.borrow_mut().replace(source)),
381        terminal: TERMINAL.with(|slot| slot.replace(Some(None))),
382    };
383    // Do not inspect CURRENT after operation: a source-account scope may already
384    // have restored an unrelated worker's account. The actual source chain owns
385    // its stops; consumers capture them before leaving their work epoch.
386    operation()
387}
388
389#[cfg(all(feature = "retained-runtime", any(target_arch = "wasm32", test)))]
390mod budget_monotonic;