Skip to main content

lichtung_plot/
operation.rs

1//! Per-call cancellation and native resource admission.
2
3use std::{
4    cell::{Cell, RefCell},
5    rc::Rc,
6    sync::{
7        atomic::{AtomicBool, Ordering},
8        Arc,
9    },
10};
11
12use crate::{
13    errors::{BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
14    Error, Result,
15};
16
17/// A shared, single-use cancellation flag.
18///
19/// Clones observe the same flag across threads. Cancelling an operation does
20/// not alter its input declaration or a previously completed output.
21#[derive(Debug, Clone, Default)]
22pub struct CancelToken(Arc<AtomicBool>);
23
24impl CancelToken {
25    /// Create an uncancelled token.
26    pub fn new() -> Self {
27        Self::default()
28    }
29
30    /// Permanently request cancellation.
31    pub fn cancel(&self) {
32        self.0.store(true, Ordering::Release);
33    }
34
35    /// Whether cancellation has been requested.
36    pub fn is_cancelled(&self) -> bool {
37        self.0.load(Ordering::Acquire)
38    }
39}
40
41type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;
42
43/// Options for one synchronous native operation.
44///
45/// Memory admission counts requested native storage capacity growth in the
46/// operation's fallible reservations, plus explicitly scoped scratch buffers.
47/// It excludes pre-existing immutable inputs, allocator overhead and memory
48/// internal to third-party libraries. Retained reservation charges accumulate
49/// conservatively for the call; scoped scratch is released when no longer
50/// needed. This is a storage budget, not a process RSS limit.
51///
52/// Work admission counts the actual defined operations described by the
53/// producer (such as sampled observations, layout rounds, replay commands and
54/// raster/encoding work). Neither budget changes the scientific or visual
55/// algorithm. Existing device limits still apply without either added budget.
56#[derive(Clone, Default)]
57pub struct OperationOptions {
58    cancellation: Option<CancelToken>,
59    memory_limit_bytes: Option<u64>,
60    work_limit: Option<u64>,
61    interrupt_check: Option<Arc<InterruptCheck>>,
62}
63
64impl std::fmt::Debug for OperationOptions {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("OperationOptions")
67            .field("cancellation", &self.cancellation)
68            .field("memory_limit_bytes", &self.memory_limit_bytes)
69            .field("work_limit", &self.work_limit)
70            .finish_non_exhaustive()
71    }
72}
73
74impl OperationOptions {
75    /// Request cancellation using the supplied shared token.
76    #[must_use]
77    pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
78        self.cancellation = token.into();
79        self
80    }
81
82    /// Limit the operation's admitted native storage, in bytes.
83    #[must_use]
84    pub fn memory_limit_bytes(mut self, bytes: impl Into<Option<u64>>) -> Self {
85        self.memory_limit_bytes = bytes.into();
86        self
87    }
88
89    /// Limit the operation's defined work units.
90    #[must_use]
91    pub fn work_limit(mut self, units: impl Into<Option<u64>>) -> Self {
92        self.work_limit = units.into();
93        self
94    }
95
96    /// Borrow the configured cancellation token.
97    pub fn get_cancellation(&self) -> Option<&CancelToken> {
98        self.cancellation.as_ref()
99    }
100
101    /// Configured storage budget.
102    pub const fn get_memory_limit_bytes(&self) -> Option<u64> {
103        self.memory_limit_bytes
104    }
105
106    /// Configured work budget.
107    pub const fn get_work_limit(&self) -> Option<u64> {
108        self.work_limit
109    }
110
111    /// Host-language interrupt integration. Called only at checkpoints on the
112    /// initiating thread, outside renderer locks and before publication.
113    #[doc(hidden)]
114    #[must_use]
115    pub fn with_interrupt_check(
116        mut self,
117        check: impl Fn(OperationPhase) -> Result<()> + Send + Sync + 'static,
118    ) -> Self {
119        self.interrupt_check = Some(Arc::new(check));
120        self
121    }
122}
123
124struct Operation {
125    options: OperationOptions,
126    scientific: Cell<bool>,
127    phase: Cell<OperationPhase>,
128    retained: Cell<u128>,
129    scratch: Cell<u128>,
130    work: Cell<u128>,
131}
132
133impl Operation {
134    fn cancelled(&self) -> Result<()> {
135        if self
136            .options
137            .cancellation
138            .as_ref()
139            .is_some_and(CancelToken::is_cancelled)
140        {
141            return Err(Error::Cancelled);
142        }
143        Ok(())
144    }
145
146    fn budget_error(
147        &self,
148        resource: BudgetResource,
149        required: u128,
150        limit: u64,
151        scientific: bool,
152    ) -> Error {
153        let diagnostic = Diagnostic::new(
154            DiagnosticKind::BudgetExceeded {
155                resource,
156                required,
157                limit: u128::from(limit),
158            },
159            format!("operation {resource:?} requires {required}, exceeding the limit {limit}"),
160        )
161        .with_context(ErrorContext::new().with_operation(self.phase.get()));
162        if scientific || self.scientific.get() {
163            Error::Data(diagnostic)
164        } else {
165            Error::Render(diagnostic)
166        }
167    }
168
169    fn admit_memory(&self, bytes: u128, temporary: bool) -> Result<()> {
170        self.cancelled()?;
171        let Some(limit) = self.options.memory_limit_bytes else {
172            return Ok(());
173        };
174        let required = self
175            .retained
176            .get()
177            .saturating_add(self.scratch.get())
178            .saturating_add(bytes);
179        if required > u128::from(limit) {
180            return Err(self.budget_error(BudgetResource::MemoryBytes, required, limit, false));
181        }
182        let counter = if temporary {
183            &self.scratch
184        } else {
185            &self.retained
186        };
187        counter.set(counter.get() + bytes);
188        Ok(())
189    }
190}
191
192thread_local! {
193    // All current native prepare/replay/encode stages are synchronous and run
194    // on the initiating thread. Even a default nested public operation installs
195    // a fresh scope, rather than borrowing its caller's cancellation or budget.
196    static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
197}
198
199struct Scope(Option<Rc<Operation>>);
200
201impl Drop for Scope {
202    fn drop(&mut self) {
203        // Dropping an application-owned interrupt closure must happen outside
204        // the TLS borrow.
205        let previous = ACTIVE.with(|active| active.replace(self.0.take()));
206        drop(previous);
207    }
208}
209
210pub(crate) fn run<T>(options: &OperationOptions, execute: impl FnOnce() -> Result<T>) -> Result<T> {
211    run_scoped(options, false, execute)
212}
213
214/// Independent scientific preparation has no layout or device resources.
215pub(crate) fn run_scientific<T>(
216    options: &OperationOptions,
217    execute: impl FnOnce() -> Result<T>,
218) -> Result<T> {
219    run_scoped(options, true, execute)
220}
221
222fn run_scoped<T>(
223    options: &OperationOptions,
224    scientific: bool,
225    execute: impl FnOnce() -> Result<T>,
226) -> Result<T> {
227    let current = Rc::new(Operation {
228        options: options.clone(),
229        scientific: Cell::new(scientific),
230        phase: Cell::new(OperationPhase::Check),
231        retained: Cell::new(0),
232        scratch: Cell::new(0),
233        work: Cell::new(0),
234    });
235    let _scope = Scope(ACTIVE.with(|active| active.replace(Some(current))));
236    checkpoint()?;
237    execute()
238}
239
240pub(crate) fn current_phase() -> Option<OperationPhase> {
241    ACTIVE.with_borrow(|active| active.as_ref().map(|active| active.phase.get()))
242}
243
244/// Preserve scientific admission errors when a drawing also prepares science.
245/// The drawing's existing counters continue across this scope.
246pub(crate) struct ScientificPreparation(Option<(Rc<Operation>, bool)>);
247
248impl Drop for ScientificPreparation {
249    fn drop(&mut self) {
250        if let Some((operation, previous)) = &self.0 {
251            operation.scientific.set(*previous);
252        }
253    }
254}
255
256pub(crate) fn scientific_preparation() -> ScientificPreparation {
257    ScientificPreparation(ACTIVE.with_borrow(|active| {
258        active.as_ref().map(|operation| {
259            let previous = operation.scientific.replace(true);
260            (Rc::clone(operation), previous)
261        })
262    }))
263}
264
265/// Application callbacks may start independent operations or edit a declaration.
266pub(crate) fn external<T>(call: impl FnOnce() -> T) -> T {
267    let _scope = Scope(ACTIVE.with(|active| active.replace(None)));
268    call()
269}
270
271pub(crate) fn phase(phase: OperationPhase) -> Result<()> {
272    ACTIVE.with_borrow(|active| {
273        if let Some(active) = active {
274            active.phase.set(phase);
275        }
276    });
277    checkpoint()
278}
279
280/// Check only the native flag. Safe while a preparation resource is locked.
281pub(crate) fn check() -> Result<()> {
282    ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
283}
284
285/// A lock-free application interrupt boundary. Never borrow TLS across the hook.
286pub(crate) fn checkpoint() -> Result<()> {
287    let active = ACTIVE.with_borrow(Clone::clone);
288    if let Some(active) = active {
289        active.cancelled()?;
290        if let Some(check) = &active.options.interrupt_check {
291            external(|| check(active.phase.get()))?;
292        }
293        active.cancelled()?;
294    }
295    Ok(())
296}
297
298fn admit_work(units: usize, scientific: bool) -> Result<()> {
299    ACTIVE.with_borrow(|active| {
300        let Some(active) = active else {
301            return Ok(());
302        };
303        active.cancelled()?;
304        if let Some(limit) = active.options.work_limit {
305            let required = active.work.get() + units as u128;
306            if required > u128::from(limit) {
307                return Err(active.budget_error(BudgetResource::Work, required, limit, scientific));
308            }
309            active.work.set(required);
310        }
311        Ok(())
312    })
313}
314
315pub(crate) fn work(units: usize) -> Result<()> {
316    admit_work(units, false)
317}
318
319pub(crate) fn scientific_work(units: usize) -> Result<()> {
320    admit_work(units, true)
321}
322
323/// Admit the extra logical capacity before a fallible allocation.
324pub(crate) fn capacity<T>(capacity: usize, len: usize, additional: usize) -> Result<()> {
325    check()?;
326    let required = len
327        .checked_add(additional)
328        .ok_or_else(|| Error::Render("operation storage capacity overflow".into()))?;
329    let growth = required.saturating_sub(capacity) as u128 * std::mem::size_of::<T>() as u128;
330    memory(growth)
331}
332
333pub(crate) fn vector<T>(values: &Vec<T>, additional: usize) -> Result<()> {
334    capacity::<T>(values.capacity(), values.len(), additional)
335}
336
337pub(crate) fn string(value: &String, additional: usize) -> Result<()> {
338    capacity::<u8>(value.capacity(), value.len(), additional)
339}
340
341pub(crate) fn memory(bytes: u128) -> Result<()> {
342    ACTIVE.with_borrow(|active| {
343        active
344            .as_ref()
345            .map_or(Ok(()), |active| active.admit_memory(bytes, false))
346    })
347}
348
349/// Account for an allocation whose lifetime is known (e.g. one raster tile).
350pub(crate) struct Scratch {
351    operation: Option<Rc<Operation>>,
352    bytes: u128,
353}
354
355impl Drop for Scratch {
356    fn drop(&mut self) {
357        if let Some(active) = &self.operation {
358            active.scratch.set(active.scratch.get() - self.bytes);
359        }
360    }
361}
362
363pub(crate) fn scratch(bytes: u128) -> Result<Scratch> {
364    let operation = ACTIVE.with_borrow(|active| {
365        active
366            .as_ref()
367            .filter(|active| active.options.memory_limit_bytes.is_some())
368            .cloned()
369    });
370    check()?;
371    if let Some(active) = &operation {
372        active.admit_memory(bytes, true)?;
373    }
374    Ok(Scratch { operation, bytes })
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn owning_scientific_columns_admit_their_real_storage() {
383        let options = OperationOptions::default().memory_limit_bytes(0);
384        let categorical = run_scientific(&options, || {
385            crate::CategoryValues::new("category", ["A", "B"])
386        });
387        let rows = run_scientific(&options, || crate::data::SourceRows::new([10, 20]));
388        for error in [categorical.unwrap_err(), rows.unwrap_err()] {
389            let Error::Data(diagnostic) = error else {
390                panic!("scientific storage must report a data error");
391            };
392            assert!(matches!(diagnostic.kind(),
393                DiagnosticKind::BudgetExceeded { resource: BudgetResource::MemoryBytes, required, limit: 0 }
394                if *required > 0));
395        }
396        let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
397        let selected = original.select(&[2, 0, 1]).unwrap();
398        assert!(selected.get(0).flatten().unwrap().is_nan());
399        assert_eq!(
400            selected.get(1).flatten().unwrap().to_bits(),
401            (-0.0_f64).to_bits()
402        );
403        assert_eq!(selected.get(2), Some(None));
404    }
405
406    #[test]
407    fn direct_terminal_consumes_one_shared_render_and_write_budget() {
408        let plot = crate::Plot::scatter(
409            crate::NumericValues::new("x", [0., 1., 2.]),
410            crate::NumericValues::new("y", [1., 0., 2.]),
411        )
412        .size(800, 600);
413        let work = run(&OperationOptions::default().work_limit(u64::MAX), || {
414            crate::orchestrator::render_scene(crate::orchestrator::root::RootSource::Plot(
415                plot.description(),
416            ))?;
417            Ok(ACTIVE.with_borrow(|active| active.as_ref().unwrap().work.get()))
418        })
419        .unwrap();
420        let exact = OperationOptions::default().work_limit(u64::try_from(work).unwrap());
421        plot.render_with_operation(&exact).unwrap();
422        let directory = tempfile::tempdir().unwrap();
423        let path = directory.path().join("existing.svg");
424        std::fs::write(&path, b"old").unwrap();
425        let Err(Error::Render(diagnostic)) = plot.svg_preserve_text_with_operation(&path, &exact)
426        else {
427            panic!("direct terminal must not reset the render budget for publication");
428        };
429        assert!(matches!(diagnostic.kind(),
430            DiagnosticKind::BudgetExceeded { resource: BudgetResource::Work, required, limit }
431            if *required == work + 1 && *limit == work));
432        assert_eq!(
433            diagnostic.context().operation(),
434            Some(OperationPhase::Write)
435        );
436        assert_eq!(std::fs::read(&path).unwrap(), b"old");
437        assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
438    }
439}