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/// Which notices a session prints (`ursa.notices`): one line each, to the
237/// sink the host installed (`crate::notices`; the CLI's is stderr).
238#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
239pub enum NoticeLevel {
240    /// None.
241    Off,
242    /// Index builds that take more than a second, and every stored-index
243    /// decision that loses work: an index not stored, an index evicted, a
244    /// failed write.
245    #[default]
246    On,
247    /// Every index build, load and store, however quick.
248    All,
249}
250
251impl NoticeLevel {
252    /// `on`, `off` or `all` (`true` and `false` too), in any case.
253    pub fn parse(text: &str) -> Result<Self> {
254        match text.trim().to_ascii_lowercase().as_str() {
255            "off" | "false" => Ok(Self::Off),
256            "on" | "true" => Ok(Self::On),
257            "all" => Ok(Self::All),
258            _ => Err(DataFusionError::Configuration(format!(
259                "'{text}' is not a notice level; use 'on', 'off' or 'all'"
260            ))),
261        }
262    }
263}
264
265impl fmt::Display for NoticeLevel {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        f.write_str(match self {
268            Self::Off => "off",
269            Self::On => "on",
270            Self::All => "all",
271        })
272    }
273}
274
275impl ConfigField for NoticeLevel {
276    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
277        v.some(key, self, description)
278    }
279
280    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
281        *self = NoticeLevel::parse(value)?;
282        Ok(())
283    }
284}
285
286extensions_options! {
287    /// Ursa's settings (`SET ursa.<name> = …`).
288    pub struct UrsaOptions {
289        /// The most bytes of graph indexes a `.ursa` database keeps on disk:
290        /// a new index is stored only within it, removing the least recently
291        /// used to make room. Lowering it removes nothing. Default auto: 25%
292        /// of the free space on the database's disk (counting its stored
293        /// indexes), at least 4GiB and at most 64GiB. Lasts for the session.
294        pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
295        /// Which notices to print on stderr: 'on' (slow index builds, and
296        /// indexes not stored or evicted), 'all' (every index build, load
297        /// and store) or 'off'. Default on.
298        pub notices: NoticeLevel, default = NoticeLevel::On
299        /// The most paths one GRAPH_TABLE path search holds before it stops
300        /// with an error; 0 for no limit. Under ANY SHORTEST (and SHORTEST
301        /// k) it counts the paths kept, never fewer than one (k) per node of
302        /// the graph; otherwise the paths and prefixes held. Default
303        /// 10000000.
304        pub max_paths: usize, default = crate::graph::path_search::MAX_PATHS
305        /// The most bytes of decoded rows an index build reads ahead of the
306        /// rows it is interning, so the partitions of its edge and vertex
307        /// tables decode in parallel.
308        /// Default auto: 256MiB per partition read, at most 1GiB and at most
309        /// an eighth of the memory available. 0 reads the partitions one
310        /// after another.
311        pub build_read_ahead: ReadAhead, default = ReadAhead::Auto
312    }
313}
314
315impl ConfigExtension for UrsaOptions {
316    const PREFIX: &'static str = "ursa";
317}
318
319/// `config` with Ursa's settings, unless it has them.
320pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
321    if config.options().extensions.get::<UrsaOptions>().is_none() {
322        config
323            .options_mut()
324            .extensions
325            .insert(UrsaOptions::default());
326    }
327    config
328}
329
330/// The session's `ursa.notices`.
331pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
332    config
333        .options()
334        .extensions
335        .get::<UrsaOptions>()
336        .map_or(NoticeLevel::default(), |o| o.notices)
337}
338
339/// The session's `ursa.max_paths`: `None` when it is 0, no limit.
340pub fn max_paths(config: &SessionConfig) -> Option<usize> {
341    let n = config
342        .options()
343        .extensions
344        .get::<UrsaOptions>()
345        .map_or(crate::graph::path_search::MAX_PATHS, |o| o.max_paths);
346    (n > 0).then_some(n)
347}
348
349/// The session's `ursa.build_read_ahead`, if it was `SET`; `None` when it
350/// is `auto` (see `graph::in_order`).
351pub fn build_read_ahead_set(config: &SessionConfig) -> Option<u64> {
352    config
353        .options()
354        .extensions
355        .get::<UrsaOptions>()
356        .and_then(|o| o.build_read_ahead.bytes())
357}
358
359/// The session's `ursa.index_storage_limit`, if it was `SET`; `None` when it
360/// is `auto`, the database's default (`Database::index_storage_limit` gives
361/// the limit in effect).
362pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
363    config
364        .options()
365        .extensions
366        .get::<UrsaOptions>()
367        .and_then(|o| o.index_storage_limit.bytes())
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373
374    #[test]
375    fn sizes_parse_and_print() {
376        for (text, bytes) in [
377            ("0", 0),
378            ("1048576", 1 << 20),
379            ("512KiB", 512 << 10),
380            ("64 MiB", 64 << 20),
381            ("8GiB", 8 << 30),
382            ("8gib", 8 << 30),
383            ("1.5GiB", 3 << 29),
384            ("2TiB", 2 << 40),
385            ("100B", 100),
386        ] {
387            assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
388        }
389        for bad in [
390            "",
391            "GiB",
392            "8GB",
393            "-1",
394            "8 gigabytes",
395            "1e3",
396            "99999999999TiB",
397        ] {
398            assert!(ByteSize::parse(bad).is_err(), "{bad}");
399        }
400        assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
401        assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
402        assert_eq!(ByteSize(1000).to_string(), "1000");
403        assert_eq!(ByteSize(0).to_string(), "0");
404    }
405
406    #[test]
407    fn the_limit_is_auto_or_a_size() {
408        assert_eq!(IndexStorageLimit::default().to_string(), "auto");
409        for auto in ["auto", "AUTO", "default"] {
410            assert_eq!(
411                IndexStorageLimit::parse(auto).unwrap(),
412                IndexStorageLimit::Auto
413            );
414        }
415        let set = IndexStorageLimit::parse("50MiB").unwrap();
416        assert_eq!(set.to_string(), "50MiB");
417        assert_eq!(set.bytes(), Some(50 << 20));
418        assert!(IndexStorageLimit::parse("lots").is_err());
419    }
420
421    #[test]
422    fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
423        let gib = 1u64 << 30;
424        assert_eq!(default_index_storage_limit(None), 4 * gib);
425        assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
426        assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
427        // 25%, rounded down to a multiple of 4 GiB.
428        assert_eq!(default_index_storage_limit(Some(100 * gib)), 24 * gib);
429        assert_eq!(default_index_storage_limit(Some(103 * gib)), 24 * gib);
430        assert_eq!(default_index_storage_limit(Some(87 * gib)), 20 * gib);
431        assert_eq!(default_index_storage_limit(Some(95 * gib)), 20 * gib);
432        assert_eq!(default_index_storage_limit(Some(96 * gib)), 24 * gib);
433        assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
434        assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
435    }
436}