lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! Per-call cancellation and native resource admission.

use std::{
    cell::{Cell, RefCell},
    rc::Rc,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use crate::{
    errors::{BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
    Error, Result,
};

/// A shared, single-use cancellation flag.
///
/// Clones observe the same flag across threads. Cancelling an operation does
/// not alter its input declaration or a previously completed output.
#[derive(Debug, Clone, Default)]
pub struct CancelToken(Arc<AtomicBool>);

impl CancelToken {
    /// Create an uncancelled token.
    pub fn new() -> Self {
        Self::default()
    }

    /// Permanently request cancellation.
    pub fn cancel(&self) {
        self.0.store(true, Ordering::Release);
    }

    /// Whether cancellation has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }
}

type InterruptCheck = dyn Fn(OperationPhase) -> Result<()> + Send + Sync;

/// Options for one synchronous native operation.
///
/// Memory admission counts requested native storage capacity growth in the
/// operation's fallible reservations, plus explicitly scoped scratch buffers.
/// It excludes pre-existing immutable inputs, allocator overhead and memory
/// internal to third-party libraries. Retained reservation charges accumulate
/// conservatively for the call; scoped scratch is released when no longer
/// needed. This is a storage budget, not a process RSS limit.
///
/// Work admission counts the actual defined operations described by the
/// producer (such as sampled observations, layout rounds, replay commands and
/// raster/encoding work). Neither budget changes the scientific or visual
/// algorithm. Existing device limits still apply without either added budget.
#[derive(Clone, Default)]
pub struct OperationOptions {
    cancellation: Option<CancelToken>,
    memory_limit_bytes: Option<u64>,
    work_limit: Option<u64>,
    interrupt_check: Option<Arc<InterruptCheck>>,
}

impl std::fmt::Debug for OperationOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OperationOptions")
            .field("cancellation", &self.cancellation)
            .field("memory_limit_bytes", &self.memory_limit_bytes)
            .field("work_limit", &self.work_limit)
            .finish_non_exhaustive()
    }
}

impl OperationOptions {
    /// Request cancellation using the supplied shared token.
    #[must_use]
    pub fn cancellation(mut self, token: impl Into<Option<CancelToken>>) -> Self {
        self.cancellation = token.into();
        self
    }

    /// Limit the operation's admitted native storage, in bytes.
    #[must_use]
    pub fn memory_limit_bytes(mut self, bytes: impl Into<Option<u64>>) -> Self {
        self.memory_limit_bytes = bytes.into();
        self
    }

    /// Limit the operation's defined work units.
    #[must_use]
    pub fn work_limit(mut self, units: impl Into<Option<u64>>) -> Self {
        self.work_limit = units.into();
        self
    }

    /// Borrow the configured cancellation token.
    pub fn get_cancellation(&self) -> Option<&CancelToken> {
        self.cancellation.as_ref()
    }

    /// Configured storage budget.
    pub const fn get_memory_limit_bytes(&self) -> Option<u64> {
        self.memory_limit_bytes
    }

    /// Configured work budget.
    pub const fn get_work_limit(&self) -> Option<u64> {
        self.work_limit
    }

    /// Host-language interrupt integration. Called only at checkpoints on the
    /// initiating thread, outside renderer locks and before publication.
    #[doc(hidden)]
    #[must_use]
    pub fn with_interrupt_check(
        mut self,
        check: impl Fn(OperationPhase) -> Result<()> + Send + Sync + 'static,
    ) -> Self {
        self.interrupt_check = Some(Arc::new(check));
        self
    }
}

struct Operation {
    options: OperationOptions,
    scientific: Cell<bool>,
    phase: Cell<OperationPhase>,
    retained: Cell<u128>,
    scratch: Cell<u128>,
    work: Cell<u128>,
}

impl Operation {
    fn cancelled(&self) -> Result<()> {
        if self
            .options
            .cancellation
            .as_ref()
            .is_some_and(CancelToken::is_cancelled)
        {
            return Err(Error::Cancelled);
        }
        Ok(())
    }

    fn budget_error(
        &self,
        resource: BudgetResource,
        required: u128,
        limit: u64,
        scientific: bool,
    ) -> Error {
        let diagnostic = Diagnostic::new(
            DiagnosticKind::BudgetExceeded {
                resource,
                required,
                limit: u128::from(limit),
            },
            format!("operation {resource:?} requires {required}, exceeding the limit {limit}"),
        )
        .with_context(ErrorContext::new().with_operation(self.phase.get()));
        if scientific || self.scientific.get() {
            Error::Data(diagnostic)
        } else {
            Error::Render(diagnostic)
        }
    }

    fn admit_memory(&self, bytes: u128, temporary: bool) -> Result<()> {
        self.cancelled()?;
        let Some(limit) = self.options.memory_limit_bytes else {
            return Ok(());
        };
        let required = self
            .retained
            .get()
            .saturating_add(self.scratch.get())
            .saturating_add(bytes);
        if required > u128::from(limit) {
            return Err(self.budget_error(BudgetResource::MemoryBytes, required, limit, false));
        }
        let counter = if temporary {
            &self.scratch
        } else {
            &self.retained
        };
        counter.set(counter.get() + bytes);
        Ok(())
    }
}

thread_local! {
    // All current native prepare/replay/encode stages are synchronous and run
    // on the initiating thread. Even a default nested public operation installs
    // a fresh scope, rather than borrowing its caller's cancellation or budget.
    static ACTIVE: RefCell<Option<Rc<Operation>>> = const { RefCell::new(None) };
}

struct Scope(Option<Rc<Operation>>);

impl Drop for Scope {
    fn drop(&mut self) {
        // Dropping an application-owned interrupt closure must happen outside
        // the TLS borrow.
        let previous = ACTIVE.with(|active| active.replace(self.0.take()));
        drop(previous);
    }
}

pub(crate) fn run<T>(options: &OperationOptions, execute: impl FnOnce() -> Result<T>) -> Result<T> {
    run_scoped(options, false, execute)
}

/// Independent scientific preparation has no layout or device resources.
pub(crate) fn run_scientific<T>(
    options: &OperationOptions,
    execute: impl FnOnce() -> Result<T>,
) -> Result<T> {
    run_scoped(options, true, execute)
}

fn run_scoped<T>(
    options: &OperationOptions,
    scientific: bool,
    execute: impl FnOnce() -> Result<T>,
) -> Result<T> {
    let current = Rc::new(Operation {
        options: options.clone(),
        scientific: Cell::new(scientific),
        phase: Cell::new(OperationPhase::Check),
        retained: Cell::new(0),
        scratch: Cell::new(0),
        work: Cell::new(0),
    });
    let _scope = Scope(ACTIVE.with(|active| active.replace(Some(current))));
    checkpoint()?;
    execute()
}

pub(crate) fn current_phase() -> Option<OperationPhase> {
    ACTIVE.with_borrow(|active| active.as_ref().map(|active| active.phase.get()))
}

/// Preserve scientific admission errors when a drawing also prepares science.
/// The drawing's existing counters continue across this scope.
pub(crate) struct ScientificPreparation(Option<(Rc<Operation>, bool)>);

impl Drop for ScientificPreparation {
    fn drop(&mut self) {
        if let Some((operation, previous)) = &self.0 {
            operation.scientific.set(*previous);
        }
    }
}

pub(crate) fn scientific_preparation() -> ScientificPreparation {
    ScientificPreparation(ACTIVE.with_borrow(|active| {
        active.as_ref().map(|operation| {
            let previous = operation.scientific.replace(true);
            (Rc::clone(operation), previous)
        })
    }))
}

/// Application callbacks may start independent operations or edit a declaration.
pub(crate) fn external<T>(call: impl FnOnce() -> T) -> T {
    let _scope = Scope(ACTIVE.with(|active| active.replace(None)));
    call()
}

pub(crate) fn phase(phase: OperationPhase) -> Result<()> {
    ACTIVE.with_borrow(|active| {
        if let Some(active) = active {
            active.phase.set(phase);
        }
    });
    checkpoint()
}

/// Check only the native flag. Safe while a preparation resource is locked.
pub(crate) fn check() -> Result<()> {
    ACTIVE.with_borrow(|active| active.as_ref().map_or(Ok(()), |active| active.cancelled()))
}

/// A lock-free application interrupt boundary. Never borrow TLS across the hook.
pub(crate) fn checkpoint() -> Result<()> {
    let active = ACTIVE.with_borrow(Clone::clone);
    if let Some(active) = active {
        active.cancelled()?;
        if let Some(check) = &active.options.interrupt_check {
            external(|| check(active.phase.get()))?;
        }
        active.cancelled()?;
    }
    Ok(())
}

fn admit_work(units: usize, scientific: bool) -> Result<()> {
    ACTIVE.with_borrow(|active| {
        let Some(active) = active else {
            return Ok(());
        };
        active.cancelled()?;
        if let Some(limit) = active.options.work_limit {
            let required = active.work.get() + units as u128;
            if required > u128::from(limit) {
                return Err(active.budget_error(BudgetResource::Work, required, limit, scientific));
            }
            active.work.set(required);
        }
        Ok(())
    })
}

pub(crate) fn work(units: usize) -> Result<()> {
    admit_work(units, false)
}

pub(crate) fn scientific_work(units: usize) -> Result<()> {
    admit_work(units, true)
}

/// Admit the extra logical capacity before a fallible allocation.
pub(crate) fn capacity<T>(capacity: usize, len: usize, additional: usize) -> Result<()> {
    check()?;
    let required = len
        .checked_add(additional)
        .ok_or_else(|| Error::Render("operation storage capacity overflow".into()))?;
    let growth = required.saturating_sub(capacity) as u128 * std::mem::size_of::<T>() as u128;
    memory(growth)
}

pub(crate) fn vector<T>(values: &Vec<T>, additional: usize) -> Result<()> {
    capacity::<T>(values.capacity(), values.len(), additional)
}

pub(crate) fn string(value: &String, additional: usize) -> Result<()> {
    capacity::<u8>(value.capacity(), value.len(), additional)
}

pub(crate) fn memory(bytes: u128) -> Result<()> {
    ACTIVE.with_borrow(|active| {
        active
            .as_ref()
            .map_or(Ok(()), |active| active.admit_memory(bytes, false))
    })
}

/// Account for an allocation whose lifetime is known (e.g. one raster tile).
pub(crate) struct Scratch {
    operation: Option<Rc<Operation>>,
    bytes: u128,
}

impl Drop for Scratch {
    fn drop(&mut self) {
        if let Some(active) = &self.operation {
            active.scratch.set(active.scratch.get() - self.bytes);
        }
    }
}

pub(crate) fn scratch(bytes: u128) -> Result<Scratch> {
    let operation = ACTIVE.with_borrow(|active| {
        active
            .as_ref()
            .filter(|active| active.options.memory_limit_bytes.is_some())
            .cloned()
    });
    check()?;
    if let Some(active) = &operation {
        active.admit_memory(bytes, true)?;
    }
    Ok(Scratch { operation, bytes })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn owning_scientific_columns_admit_their_real_storage() {
        let options = OperationOptions::default().memory_limit_bytes(0);
        let categorical = run_scientific(&options, || {
            crate::CategoryValues::new("category", ["A", "B"])
        });
        let rows = run_scientific(&options, || crate::data::SourceRows::new([10, 20]));
        for error in [categorical.unwrap_err(), rows.unwrap_err()] {
            let Error::Data(diagnostic) = error else {
                panic!("scientific storage must report a data error");
            };
            assert!(matches!(diagnostic.kind(),
                DiagnosticKind::BudgetExceeded { resource: BudgetResource::MemoryBytes, required, limit: 0 }
                if *required > 0));
        }
        let original = crate::NumericValues::nullable("v", [Some(-0.), None, Some(f64::NAN)]);
        let selected = original.select(&[2, 0, 1]).unwrap();
        assert!(selected.get(0).flatten().unwrap().is_nan());
        assert_eq!(
            selected.get(1).flatten().unwrap().to_bits(),
            (-0.0_f64).to_bits()
        );
        assert_eq!(selected.get(2), Some(None));
    }

    #[test]
    fn direct_terminal_consumes_one_shared_render_and_write_budget() {
        let plot = crate::Plot::scatter(
            crate::NumericValues::new("x", [0., 1., 2.]),
            crate::NumericValues::new("y", [1., 0., 2.]),
        )
        .size(800, 600);
        let work = run(&OperationOptions::default().work_limit(u64::MAX), || {
            crate::orchestrator::render_scene(crate::orchestrator::root::RootSource::Plot(
                plot.description(),
            ))?;
            Ok(ACTIVE.with_borrow(|active| active.as_ref().unwrap().work.get()))
        })
        .unwrap();
        let exact = OperationOptions::default().work_limit(u64::try_from(work).unwrap());
        plot.render_with_operation(&exact).unwrap();
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("existing.svg");
        std::fs::write(&path, b"old").unwrap();
        let Err(Error::Render(diagnostic)) = plot.svg_preserve_text_with_operation(&path, &exact)
        else {
            panic!("direct terminal must not reset the render budget for publication");
        };
        assert!(matches!(diagnostic.kind(),
            DiagnosticKind::BudgetExceeded { resource: BudgetResource::Work, required, limit }
            if *required == work + 1 && *limit == work));
        assert_eq!(
            diagnostic.context().operation(),
            Some(OperationPhase::Write)
        );
        assert_eq!(std::fs::read(&path).unwrap(), b"old");
        assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
    }
}