Skip to main content

ursa_engine/
options.rs

1//! Ursa's session settings, set with `SET ursa.<name> = …` and shown with
2//! `SHOW ursa.<name>`: a DataFusion config extension with the prefix `ursa`.
3//!
4//! Settings last for the session, as in DuckDB and Postgres (#353): `SET` and
5//! `RESET` change only the current session, in any database, and nothing is
6//! written to the catalog. To keep a setting, put the `SET` in `~/.ursarc` or
7//! an `-init` file. (Ursa 0.8 and 0.9 stored `ursa.index_storage_limit` in a
8//! writable database's catalog; such an entry is no longer applied, see
9//! `ursa-sql`'s `database` module.)
10//!
11//! `ursa.index_storage_limit` is `auto` unless `SET`: a database then keeps
12//! at most [`default_index_storage_limit`], a share of the free space on its
13//! disk.
14
15use std::fmt;
16
17use datafusion::common::extensions_options;
18use datafusion::config::{ConfigExtension, ConfigField, Visit};
19use datafusion::error::{DataFusionError, Result};
20use datafusion::prelude::SessionConfig;
21
22/// The least the default `ursa.index_storage_limit` is: 4 GiB, whatever the
23/// free space (the default of Ursa 0.8 and 0.9).
24pub const MIN_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 4 << 30;
25/// The most the default `ursa.index_storage_limit` is: 64 GiB.
26pub const MAX_DEFAULT_INDEX_STORAGE_LIMIT: u64 = 64 << 30;
27/// The default `ursa.index_storage_limit` is a multiple of this, 4 GiB, so it
28/// does not move between opens as the free space changes a little (#381).
29pub const DEFAULT_INDEX_STORAGE_STEP: u64 = 4 << 30;
30/// The share of the space available to indexes that the default
31/// `ursa.index_storage_limit` takes, in percent.
32pub const DEFAULT_INDEX_STORAGE_SHARE: u64 = 25;
33
34/// The default `ursa.index_storage_limit` of a database whose indexes could
35/// use `available` bytes (the free space on its disk plus what its stored
36/// indexes already take; `None` if the free space cannot be read): 25% of
37/// it, rounded down to a multiple of 4 GiB, at least 4 GiB and at most 64 GiB
38/// (#353, #381).
39///
40/// Relative, so a large disk keeps the indexes of several large graphs (an
41/// index of 95.7M edges takes about 1.3 GiB, and 2.3 GiB once an algorithm
42/// adds its reverse adjacency) instead of evicting one to store another; and
43/// a share, so indexes, which are a cache, never take most of a disk: three
44/// quarters of it stays free for everything else. Capped, so a vast disk does
45/// not keep an unbounded cache; and at least the 4 GiB earlier versions kept,
46/// so no database keeps less than it did. The stored indexes count as
47/// available, so storing them does not shrink the limit at the next open.
48pub fn default_index_storage_limit(available: Option<u64>) -> u64 {
49    let Some(available) = available else {
50        return MIN_DEFAULT_INDEX_STORAGE_LIMIT;
51    };
52    let share = (available as u128 * DEFAULT_INDEX_STORAGE_SHARE as u128 / 100) as u64;
53    (share / DEFAULT_INDEX_STORAGE_STEP * DEFAULT_INDEX_STORAGE_STEP).clamp(
54        MIN_DEFAULT_INDEX_STORAGE_LIMIT,
55        MAX_DEFAULT_INDEX_STORAGE_LIMIT,
56    )
57}
58
59/// `ursa.index_storage_limit`: `auto` (the default, see
60/// [`default_index_storage_limit`]) or a size `SET` for the session.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum IndexStorageLimit {
63    /// The database's default, relative to the free space on its disk.
64    #[default]
65    Auto,
66    /// A size `SET` for the session.
67    Bytes(ByteSize),
68}
69
70impl IndexStorageLimit {
71    /// `auto` (or `default`), in any case, or a size ([`ByteSize::parse`]).
72    pub fn parse(text: &str) -> Result<Self> {
73        match text.trim().to_ascii_lowercase().as_str() {
74            "auto" | "default" => Ok(Self::Auto),
75            _ => ByteSize::parse(text).map(Self::Bytes),
76        }
77    }
78
79    /// The size `SET`, if one was.
80    pub fn bytes(&self) -> Option<u64> {
81        match self {
82            Self::Auto => None,
83            Self::Bytes(b) => Some(b.0),
84        }
85    }
86}
87
88impl fmt::Display for IndexStorageLimit {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::Auto => f.write_str("auto"),
92            Self::Bytes(b) => b.fmt(f),
93        }
94    }
95}
96
97impl ConfigField for IndexStorageLimit {
98    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
99        v.some(key, self, description)
100    }
101
102    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
103        *self = IndexStorageLimit::parse(value)?;
104        Ok(())
105    }
106}
107
108/// `ursa.build_read_ahead`: `auto` (the default: 256 MiB per partition of
109/// the plan read, at most 1 GiB and at most an eighth of the memory
110/// available) or a size `SET` for the session; 0 reads a build's partitions
111/// one after another (#385).
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
113pub enum ReadAhead {
114    /// Scaled with the partitions read, and capped by the memory available.
115    #[default]
116    Auto,
117    /// A size `SET` for the session.
118    Bytes(ByteSize),
119}
120
121impl ReadAhead {
122    /// `auto` (or `default`), in any case, or a size ([`ByteSize::parse`]).
123    pub fn parse(text: &str) -> Result<Self> {
124        match text.trim().to_ascii_lowercase().as_str() {
125            "auto" | "default" => Ok(Self::Auto),
126            _ => ByteSize::parse(text).map(Self::Bytes),
127        }
128    }
129
130    /// The size `SET`, if one was.
131    pub fn bytes(&self) -> Option<u64> {
132        match self {
133            Self::Auto => None,
134            Self::Bytes(b) => Some(b.0),
135        }
136    }
137}
138
139impl fmt::Display for ReadAhead {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        match self {
142            Self::Auto => f.write_str("auto"),
143            Self::Bytes(b) => b.fmt(f),
144        }
145    }
146}
147
148impl ConfigField for ReadAhead {
149    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
150        v.some(key, self, description)
151    }
152
153    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
154        *self = ReadAhead::parse(value)?;
155        Ok(())
156    }
157}
158
159/// A number of bytes, written as plain bytes (`1048576`) or with a binary
160/// unit (`512KiB`, `64MiB`, `8GiB`, `1TiB`; `B` for bytes).
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub struct ByteSize(pub u64);
163
164const UNITS: [(&str, u64); 5] = [
165    ("TiB", 1 << 40),
166    ("GiB", 1 << 30),
167    ("MiB", 1 << 20),
168    ("KiB", 1 << 10),
169    ("B", 1),
170];
171
172impl ByteSize {
173    /// Parse `512KiB`, `8 GiB`, `1.5GiB` or `1048576`. Units are binary and
174    /// matched without regard to case.
175    pub fn parse(text: &str) -> Result<Self> {
176        let invalid = || {
177            DataFusionError::Configuration(format!(
178                "'{text}' is not a size; write bytes (1048576) or a number with KiB, MiB, GiB \
179                 or TiB (8GiB)"
180            ))
181        };
182        let text = text.trim();
183        let split = text
184            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
185            .unwrap_or(text.len());
186        let (number, unit) = (text[..split].trim(), text[split..].trim());
187        let scale = match unit {
188            "" => 1,
189            unit => {
190                UNITS
191                    .iter()
192                    .find(|(name, _)| name.eq_ignore_ascii_case(unit))
193                    .ok_or_else(invalid)?
194                    .1
195            }
196        };
197        if let Ok(n) = number.parse::<u64>() {
198            return n.checked_mul(scale).map(ByteSize).ok_or_else(invalid);
199        }
200        let n: f64 = number.parse().map_err(|_| invalid())?;
201        let bytes = n * scale as f64;
202        if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
203            return Err(invalid());
204        }
205        Ok(ByteSize(bytes as u64))
206    }
207}
208
209impl fmt::Display for ByteSize {
210    /// In the largest binary unit that divides it, as `SHOW` prints it.
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        let (name, scale) = UNITS
213            .iter()
214            .find(|(_, scale)| self.0 != 0 && self.0.is_multiple_of(*scale))
215            .copied()
216            .unwrap_or(("B", 1));
217        if name == "B" {
218            write!(f, "{}", self.0)
219        } else {
220            write!(f, "{}{name}", self.0 / scale)
221        }
222    }
223}
224
225impl ConfigField for ByteSize {
226    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
227        v.some(key, self, description)
228    }
229
230    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
231        *self = ByteSize::parse(value)?;
232        Ok(())
233    }
234}
235
236/// A limit `SET` as a whole number, 0 for no limit (`ursa.max_paths`,
237/// `ursa.graph_max_edges`): `name` is the setting, for the message when
238/// `text` is not one, in the style of the other settings' messages (rather
239/// than DataFusion's "Error parsing '-5' as usize").
240pub fn parse_limit(name: &str, text: &str) -> Result<usize> {
241    text.trim().parse::<usize>().map_err(|_| {
242        DataFusionError::Configuration(format!(
243            "{name} must be a non-negative integer (0 for no limit); got {text}"
244        ))
245    })
246}
247
248/// A setting that is a limit: a whole number, 0 for no limit, parsed with
249/// [`parse_limit`] so a bad value names the setting.
250macro_rules! limit_setting {
251    ($(#[$doc:meta])* $ty:ident, $name:literal) => {
252        $(#[$doc])*
253        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
254        pub struct $ty(pub usize);
255
256        impl fmt::Display for $ty {
257            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258                self.0.fmt(f)
259            }
260        }
261
262        impl ConfigField for $ty {
263            fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
264                v.some(key, self, description)
265            }
266
267            fn set(&mut self, _key: &str, value: &str) -> Result<()> {
268                self.0 = parse_limit($name, value)?;
269                Ok(())
270            }
271        }
272    };
273}
274
275limit_setting!(
276    /// `ursa.max_paths`: the most paths one path search holds.
277    MaxPaths,
278    "ursa.max_paths"
279);
280limit_setting!(
281    /// `ursa.graph_max_edges`: the most edges the graph view draws.
282    GraphMaxEdges,
283    "ursa.graph_max_edges"
284);
285
286/// Which notices a session prints (`ursa.notices`): one line each, to the
287/// sink the host installed (`crate::notices`; the CLI's is stderr).
288#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
289pub enum NoticeLevel {
290    /// None.
291    Off,
292    /// Index builds that take more than a second, and every stored-index
293    /// decision that loses work: an index not stored, an index evicted, a
294    /// failed write.
295    #[default]
296    On,
297    /// Every index build, load and store, however quick.
298    All,
299}
300
301impl NoticeLevel {
302    /// `on`, `off` or `all` (`true` and `false` too), in any case.
303    pub fn parse(text: &str) -> Result<Self> {
304        match text.trim().to_ascii_lowercase().as_str() {
305            "off" | "false" => Ok(Self::Off),
306            "on" | "true" => Ok(Self::On),
307            "all" => Ok(Self::All),
308            _ => Err(DataFusionError::Configuration(format!(
309                "'{text}' is not a notice level; use 'on', 'off' or 'all'"
310            ))),
311        }
312    }
313}
314
315impl fmt::Display for NoticeLevel {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.write_str(match self {
318            Self::Off => "off",
319            Self::On => "on",
320            Self::All => "all",
321        })
322    }
323}
324
325impl ConfigField for NoticeLevel {
326    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
327        v.some(key, self, description)
328    }
329
330    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
331        *self = NoticeLevel::parse(value)?;
332        Ok(())
333    }
334}
335
336extensions_options! {
337    /// Ursa's settings (`SET ursa.<name> = …`).
338    pub struct UrsaOptions {
339        /// The most bytes of graph indexes a `.ursa` database keeps on disk:
340        /// a new index is stored only within it, removing the least recently
341        /// used to make room. Lowering it removes nothing. Default auto: 25%
342        /// of the free space on the database's disk (counting its stored
343        /// indexes), at least 4GiB and at most 64GiB. Lasts for the session.
344        pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
345        /// Which notices to print on stderr: 'on' (slow index builds, and
346        /// indexes not stored or evicted), 'all' (every index build, load
347        /// and store) or 'off'. Default on.
348        pub notices: NoticeLevel, default = NoticeLevel::On
349        /// The most paths one GRAPH_TABLE path search holds before it stops
350        /// with an error; 0 for no limit. Under ANY SHORTEST (and SHORTEST
351        /// k) it counts the paths kept, never fewer than one (k) per node of
352        /// the graph; otherwise the paths and prefixes held. Default
353        /// 10000000.
354        pub max_paths: MaxPaths, default = MaxPaths(crate::graph::path_search::MAX_PATHS)
355        /// The most bytes of decoded rows an index build reads ahead of the
356        /// rows it is interning, so the partitions of its edge and vertex
357        /// tables decode in parallel.
358        /// Default auto: 256MiB per partition read, at most 1GiB and at most
359        /// an eighth of the memory available. 0 reads the partitions one
360        /// after another.
361        pub build_read_ahead: ReadAhead, default = ReadAhead::Auto
362        /// The most edges the graph view draws (`.graph`): a result or a
363        /// graph with more is refused, with a message that names this
364        /// setting. 0 for no limit. Default 5000000, which a desktop
365        /// browser draws; the web shell sets 500000 on a phone.
366        pub graph_max_edges: GraphMaxEdges, default = GraphMaxEdges(crate::graph::view::MAX_EDGES)
367    }
368}
369
370impl ConfigExtension for UrsaOptions {
371    const PREFIX: &'static str = "ursa";
372}
373
374/// `config` with Ursa's settings, unless it has them.
375pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
376    if config.options().extensions.get::<UrsaOptions>().is_none() {
377        config
378            .options_mut()
379            .extensions
380            .insert(UrsaOptions::default());
381    }
382    config
383}
384
385/// The session's `ursa.notices`.
386pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
387    config
388        .options()
389        .extensions
390        .get::<UrsaOptions>()
391        .map_or(NoticeLevel::default(), |o| o.notices)
392}
393
394/// The session's `ursa.max_paths`: `None` when it is 0, no limit.
395pub fn max_paths(config: &SessionConfig) -> Option<usize> {
396    let n = config
397        .options()
398        .extensions
399        .get::<UrsaOptions>()
400        .map_or(crate::graph::path_search::MAX_PATHS, |o| o.max_paths.0);
401    (n > 0).then_some(n)
402}
403
404/// The session's `ursa.graph_max_edges`: the most edges the graph view
405/// draws; `usize::MAX` when it is 0, no limit.
406pub fn graph_max_edges(config: &SessionConfig) -> usize {
407    let n = config
408        .options()
409        .extensions
410        .get::<UrsaOptions>()
411        .map_or(crate::graph::view::MAX_EDGES, |o| o.graph_max_edges.0);
412    if n == 0 {
413        usize::MAX
414    } else {
415        n
416    }
417}
418
419/// The session's `ursa.build_read_ahead`, if it was `SET`; `None` when it
420/// is `auto` (see `graph::in_order`).
421pub fn build_read_ahead_set(config: &SessionConfig) -> Option<u64> {
422    config
423        .options()
424        .extensions
425        .get::<UrsaOptions>()
426        .and_then(|o| o.build_read_ahead.bytes())
427}
428
429/// The session's `ursa.index_storage_limit`, if it was `SET`; `None` when it
430/// is `auto`, the database's default (`Database::index_storage_limit` gives
431/// the limit in effect).
432pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
433    config
434        .options()
435        .extensions
436        .get::<UrsaOptions>()
437        .and_then(|o| o.index_storage_limit.bytes())
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443
444    #[test]
445    fn limits_parse_or_name_their_setting() {
446        assert_eq!(parse_limit("ursa.max_paths", "1000").unwrap(), 1000);
447        assert_eq!(parse_limit("ursa.max_paths", " 0 ").unwrap(), 0);
448        for bad in ["-5", "lots", "1.5", ""] {
449            let e = parse_limit("ursa.max_paths", bad).unwrap_err().to_string();
450            assert!(
451                e.ends_with(&format!(
452                    "ursa.max_paths must be a non-negative integer (0 for no limit); got {bad}"
453                )),
454                "{e}"
455            );
456        }
457    }
458
459    #[test]
460    fn sizes_parse_and_print() {
461        for (text, bytes) in [
462            ("0", 0),
463            ("1048576", 1 << 20),
464            ("512KiB", 512 << 10),
465            ("64 MiB", 64 << 20),
466            ("8GiB", 8 << 30),
467            ("8gib", 8 << 30),
468            ("1.5GiB", 3 << 29),
469            ("2TiB", 2 << 40),
470            ("100B", 100),
471        ] {
472            assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
473        }
474        for bad in [
475            "",
476            "GiB",
477            "8GB",
478            "-1",
479            "8 gigabytes",
480            "1e3",
481            "99999999999TiB",
482        ] {
483            assert!(ByteSize::parse(bad).is_err(), "{bad}");
484        }
485        assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
486        assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
487        assert_eq!(ByteSize(1000).to_string(), "1000");
488        assert_eq!(ByteSize(0).to_string(), "0");
489    }
490
491    #[test]
492    fn the_limit_is_auto_or_a_size() {
493        assert_eq!(IndexStorageLimit::default().to_string(), "auto");
494        for auto in ["auto", "AUTO", "default"] {
495            assert_eq!(
496                IndexStorageLimit::parse(auto).unwrap(),
497                IndexStorageLimit::Auto
498            );
499        }
500        let set = IndexStorageLimit::parse("50MiB").unwrap();
501        assert_eq!(set.to_string(), "50MiB");
502        assert_eq!(set.bytes(), Some(50 << 20));
503        assert!(IndexStorageLimit::parse("lots").is_err());
504    }
505
506    #[test]
507    fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
508        let gib = 1u64 << 30;
509        assert_eq!(default_index_storage_limit(None), 4 * gib);
510        assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
511        assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
512        // 25%, rounded down to a multiple of 4 GiB.
513        assert_eq!(default_index_storage_limit(Some(100 * gib)), 24 * gib);
514        assert_eq!(default_index_storage_limit(Some(103 * gib)), 24 * gib);
515        assert_eq!(default_index_storage_limit(Some(87 * gib)), 20 * gib);
516        assert_eq!(default_index_storage_limit(Some(95 * gib)), 20 * gib);
517        assert_eq!(default_index_storage_limit(Some(96 * gib)), 24 * gib);
518        assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
519        assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
520    }
521}