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 share of the space available to indexes that the default
28/// `ursa.index_storage_limit` takes, in percent.
29pub const DEFAULT_INDEX_STORAGE_SHARE: u64 = 25;
30
31/// The default `ursa.index_storage_limit` of a database whose indexes could
32/// use `available` bytes (the free space on its disk plus what its stored
33/// indexes already take; `None` if the free space cannot be read): 25% of
34/// it, in whole GiB, at least 4 GiB and at most 64 GiB (#353).
35///
36/// Relative, so a large disk keeps the indexes of several large graphs (an
37/// index of 95.7M edges takes about 1.3 GiB, and 2.3 GiB once an algorithm
38/// adds its reverse adjacency) instead of evicting one to store another; and
39/// a share, so indexes, which are a cache, never take most of a disk: three
40/// quarters of it stays free for everything else. Capped, so a vast disk does
41/// not keep an unbounded cache; and at least the 4 GiB earlier versions kept,
42/// so no database keeps less than it did. The stored indexes count as
43/// available, so storing them does not shrink the limit at the next open.
44pub fn default_index_storage_limit(available: Option<u64>) -> u64 {
45    let Some(available) = available else {
46        return MIN_DEFAULT_INDEX_STORAGE_LIMIT;
47    };
48    let share = (available as u128 * DEFAULT_INDEX_STORAGE_SHARE as u128 / 100) as u64;
49    (share >> 30 << 30).clamp(
50        MIN_DEFAULT_INDEX_STORAGE_LIMIT,
51        MAX_DEFAULT_INDEX_STORAGE_LIMIT,
52    )
53}
54
55/// `ursa.index_storage_limit`: `auto` (the default, see
56/// [`default_index_storage_limit`]) or a size `SET` for the session.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum IndexStorageLimit {
59    /// The database's default, relative to the free space on its disk.
60    #[default]
61    Auto,
62    /// A size `SET` for the session.
63    Bytes(ByteSize),
64}
65
66impl IndexStorageLimit {
67    /// `auto` (or `default`), in any case, or a size ([`ByteSize::parse`]).
68    pub fn parse(text: &str) -> Result<Self> {
69        match text.trim().to_ascii_lowercase().as_str() {
70            "auto" | "default" => Ok(Self::Auto),
71            _ => ByteSize::parse(text).map(Self::Bytes),
72        }
73    }
74
75    /// The size `SET`, if one was.
76    pub fn bytes(&self) -> Option<u64> {
77        match self {
78            Self::Auto => None,
79            Self::Bytes(b) => Some(b.0),
80        }
81    }
82}
83
84impl fmt::Display for IndexStorageLimit {
85    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86        match self {
87            Self::Auto => f.write_str("auto"),
88            Self::Bytes(b) => b.fmt(f),
89        }
90    }
91}
92
93impl ConfigField for IndexStorageLimit {
94    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
95        v.some(key, self, description)
96    }
97
98    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
99        *self = IndexStorageLimit::parse(value)?;
100        Ok(())
101    }
102}
103
104/// A number of bytes, written as plain bytes (`1048576`) or with a binary
105/// unit (`512KiB`, `64MiB`, `8GiB`, `1TiB`; `B` for bytes).
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct ByteSize(pub u64);
108
109const UNITS: [(&str, u64); 5] = [
110    ("TiB", 1 << 40),
111    ("GiB", 1 << 30),
112    ("MiB", 1 << 20),
113    ("KiB", 1 << 10),
114    ("B", 1),
115];
116
117impl ByteSize {
118    /// Parse `512KiB`, `8 GiB`, `1.5GiB` or `1048576`. Units are binary and
119    /// matched without regard to case.
120    pub fn parse(text: &str) -> Result<Self> {
121        let invalid = || {
122            DataFusionError::Configuration(format!(
123                "'{text}' is not a size; write bytes (1048576) or a number with KiB, MiB, GiB \
124                 or TiB (8GiB)"
125            ))
126        };
127        let text = text.trim();
128        let split = text
129            .find(|c: char| !(c.is_ascii_digit() || c == '.'))
130            .unwrap_or(text.len());
131        let (number, unit) = (text[..split].trim(), text[split..].trim());
132        let scale = match unit {
133            "" => 1,
134            unit => {
135                UNITS
136                    .iter()
137                    .find(|(name, _)| name.eq_ignore_ascii_case(unit))
138                    .ok_or_else(invalid)?
139                    .1
140            }
141        };
142        if let Ok(n) = number.parse::<u64>() {
143            return n.checked_mul(scale).map(ByteSize).ok_or_else(invalid);
144        }
145        let n: f64 = number.parse().map_err(|_| invalid())?;
146        let bytes = n * scale as f64;
147        if !bytes.is_finite() || bytes < 0.0 || bytes >= u64::MAX as f64 {
148            return Err(invalid());
149        }
150        Ok(ByteSize(bytes as u64))
151    }
152}
153
154impl fmt::Display for ByteSize {
155    /// In the largest binary unit that divides it, as `SHOW` prints it.
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        let (name, scale) = UNITS
158            .iter()
159            .find(|(_, scale)| self.0 != 0 && self.0.is_multiple_of(*scale))
160            .copied()
161            .unwrap_or(("B", 1));
162        if name == "B" {
163            write!(f, "{}", self.0)
164        } else {
165            write!(f, "{}{name}", self.0 / scale)
166        }
167    }
168}
169
170impl ConfigField for ByteSize {
171    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
172        v.some(key, self, description)
173    }
174
175    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
176        *self = ByteSize::parse(value)?;
177        Ok(())
178    }
179}
180
181/// Which notices a session prints (`ursa.notices`): one line each, to the
182/// sink the host installed (`crate::notices`; the CLI's is stderr).
183#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
184pub enum NoticeLevel {
185    /// None.
186    Off,
187    /// Index builds that take more than a second, and every stored-index
188    /// decision that loses work: an index not stored, an index evicted, a
189    /// failed write.
190    #[default]
191    On,
192    /// Every index build, load and store, however quick.
193    All,
194}
195
196impl NoticeLevel {
197    /// `on`, `off` or `all` (`true` and `false` too), in any case.
198    pub fn parse(text: &str) -> Result<Self> {
199        match text.trim().to_ascii_lowercase().as_str() {
200            "off" | "false" => Ok(Self::Off),
201            "on" | "true" => Ok(Self::On),
202            "all" => Ok(Self::All),
203            _ => Err(DataFusionError::Configuration(format!(
204                "'{text}' is not a notice level; use 'on', 'off' or 'all'"
205            ))),
206        }
207    }
208}
209
210impl fmt::Display for NoticeLevel {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        f.write_str(match self {
213            Self::Off => "off",
214            Self::On => "on",
215            Self::All => "all",
216        })
217    }
218}
219
220impl ConfigField for NoticeLevel {
221    fn visit<V: Visit>(&self, v: &mut V, key: &str, description: &'static str) {
222        v.some(key, self, description)
223    }
224
225    fn set(&mut self, _key: &str, value: &str) -> Result<()> {
226        *self = NoticeLevel::parse(value)?;
227        Ok(())
228    }
229}
230
231extensions_options! {
232    /// Ursa's settings (`SET ursa.<name> = …`).
233    pub struct UrsaOptions {
234        /// The most bytes of graph indexes a `.ursa` database keeps on disk:
235        /// a new index is stored only within it, removing the least recently
236        /// used to make room. Lowering it removes nothing. Default auto: 25%
237        /// of the free space on the database's disk (counting its stored
238        /// indexes), at least 4GiB and at most 64GiB. Lasts for the session.
239        pub index_storage_limit: IndexStorageLimit, default = IndexStorageLimit::Auto
240        /// Which notices to print on stderr: 'on' (slow index builds, and
241        /// indexes not stored or evicted), 'all' (every index build, load
242        /// and store) or 'off'. Default on.
243        pub notices: NoticeLevel, default = NoticeLevel::On
244    }
245}
246
247impl ConfigExtension for UrsaOptions {
248    const PREFIX: &'static str = "ursa";
249}
250
251/// `config` with Ursa's settings, unless it has them.
252pub(crate) fn with_options(mut config: SessionConfig) -> SessionConfig {
253    if config.options().extensions.get::<UrsaOptions>().is_none() {
254        config
255            .options_mut()
256            .extensions
257            .insert(UrsaOptions::default());
258    }
259    config
260}
261
262/// The session's `ursa.notices`.
263pub fn notice_level(config: &SessionConfig) -> NoticeLevel {
264    config
265        .options()
266        .extensions
267        .get::<UrsaOptions>()
268        .map_or(NoticeLevel::default(), |o| o.notices)
269}
270
271/// The session's `ursa.index_storage_limit`, if it was `SET`; `None` when it
272/// is `auto`, the database's default (`Database::index_storage_limit` gives
273/// the limit in effect).
274pub fn index_storage_limit_set(config: &SessionConfig) -> Option<u64> {
275    config
276        .options()
277        .extensions
278        .get::<UrsaOptions>()
279        .and_then(|o| o.index_storage_limit.bytes())
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn sizes_parse_and_print() {
288        for (text, bytes) in [
289            ("0", 0),
290            ("1048576", 1 << 20),
291            ("512KiB", 512 << 10),
292            ("64 MiB", 64 << 20),
293            ("8GiB", 8 << 30),
294            ("8gib", 8 << 30),
295            ("1.5GiB", 3 << 29),
296            ("2TiB", 2 << 40),
297            ("100B", 100),
298        ] {
299            assert_eq!(ByteSize::parse(text).unwrap(), ByteSize(bytes), "{text}");
300        }
301        for bad in [
302            "",
303            "GiB",
304            "8GB",
305            "-1",
306            "8 gigabytes",
307            "1e3",
308            "99999999999TiB",
309        ] {
310            assert!(ByteSize::parse(bad).is_err(), "{bad}");
311        }
312        assert_eq!(ByteSize(4 << 30).to_string(), "4GiB");
313        assert_eq!(ByteSize(1536 << 20).to_string(), "1536MiB");
314        assert_eq!(ByteSize(1000).to_string(), "1000");
315        assert_eq!(ByteSize(0).to_string(), "0");
316    }
317
318    #[test]
319    fn the_limit_is_auto_or_a_size() {
320        assert_eq!(IndexStorageLimit::default().to_string(), "auto");
321        for auto in ["auto", "AUTO", "default"] {
322            assert_eq!(
323                IndexStorageLimit::parse(auto).unwrap(),
324                IndexStorageLimit::Auto
325            );
326        }
327        let set = IndexStorageLimit::parse("50MiB").unwrap();
328        assert_eq!(set.to_string(), "50MiB");
329        assert_eq!(set.bytes(), Some(50 << 20));
330        assert!(IndexStorageLimit::parse("lots").is_err());
331    }
332
333    #[test]
334    fn the_default_limit_is_a_quarter_of_the_space_within_bounds() {
335        let gib = 1u64 << 30;
336        assert_eq!(default_index_storage_limit(None), 4 * gib);
337        assert_eq!(default_index_storage_limit(Some(0)), 4 * gib);
338        assert_eq!(default_index_storage_limit(Some(10 * gib)), 4 * gib);
339        // 25%, in whole GiB.
340        assert_eq!(default_index_storage_limit(Some(100 * gib)), 25 * gib);
341        assert_eq!(default_index_storage_limit(Some(103 * gib)), 25 * gib);
342        assert_eq!(default_index_storage_limit(Some(1 << 50)), 64 * gib);
343        assert_eq!(default_index_storage_limit(Some(u64::MAX)), 64 * gib);
344    }
345}