Skip to main content

ursa_engine/database/
index_store.rs

1//! The database's stored graph indexes: `club.ursa.d/indexes/`.
2//!
3//! ```text
4//! indexes/
5//!   manifest.json    one entry per stored index
6//!   <hash>.idx       one index per file (see `index_file`)
7//!   vertex_keys.json the vertex tables whose keys were counted and are one
8//!                    row each (#411; see `crate::graph::vertex_keys`)
9//! ```
10//!
11//! The manifest is the source of truth: an index file it does not list is
12//! removed when a writer first uses the store (a leftover of a process that
13//! stopped between writing a file and listing it), and a missing or
14//! unreadable manifest is an empty one. It is rewritten atomically
15//! (temporary file, `fsync`, rename) on every change.
16//!
17//! ```json
18//! {
19//!   "format": "ursa-indexes",
20//!   "version": 2,
21//!   "indexes": [
22//!     {"file": "…idx", "graph": "g", "size": 123, "created": 1730000000000,
23//!      "last_used": 1730000000000,
24//!      "key": {"version": 2, "fingerprint": "…", "files": […]}}
25//!   ]
26//! }
27//! ```
28//!
29//! `created` and `last_used` are milliseconds since the Unix epoch; `graph`
30//! names the graph the index was built for, for notices. **Version 2**
31//! (#327) has the portable key (`crate::graph::index`); a manifest of another
32//! version is an empty one, so a writer removes the files it lists, once, and
33//! says so (a notice), and every index is built again when first used. An
34//! index is never read under a key it was not written for.
35//!
36//! **Lookup** ([`IndexStore::load`]) uses an entry only if its full key
37//! matches, file identities included, and the file reads back whole; a file
38//! that does not (truncated, corrupt, another version) is a miss, and a
39//! writer drops its entry. A hit updates `last_used`. A file is
40//! memory-mapped where it can be, and the CRCs of its edge arrays are
41//! checked only before a whole-graph algorithm reads them (`super::mapped`):
42//! one found damaged then is dropped the same way (a read-only store only
43//! stops using it), and the index built again. A file 0.10 wrote (format
44//! version 2) is read whole, and one 0.11 wrote (version 3) is mapped but
45//! has no lookup table for its node ids, which is then built in memory when
46//! a query first looks an id up; a writer rewrites either in the current
47//! format, with a notice.
48//!
49//! **The limit** is the session's `ursa.index_storage_limit` in effect: what
50//! it `SET`, or the database's default, a share of the free space on its disk
51//! (`Database::index_storage_limit`, kept in step by
52//! [`IndexStore::set_limit`] whenever a session uses the store). A limit
53//! decides only whether something *new* is stored: lowering it never removes
54//! an index already stored (#353).
55//!
56//! **Storing** ([`IndexStore::save`]) decides at once, in the query that
57//! built the index, and says what it decided ([`Saved`]):
58//!
59//! 1. A read-only store stores nothing.
60//! 2. An index larger than the limit on its own is not stored.
61//! 3. If the stored indexes already take more than the limit (it was lowered
62//!    since), the index is not stored and nothing is evicted.
63//! 4. Otherwise it replaces any entry with the same fingerprint (an index of
64//!    the same edges over an older version of a file), and evicts entries,
65//!    least recently used first, only as many as it takes to fit within the
66//!    limit beside the indexes being written. Never evicted: an index a
67//!    running query holds. If the indexes in use leave no room, nothing is
68//!    evicted and the index is not stored.
69//!
70//! Evictions happen before the write, so the room is there on disk too, and
71//! each is a notice. The write itself runs on a background thread, so the
72//! query is not held up by the disk; [`IndexStore::flush`] waits for it. The
73//! database calls it when it closes (before it releases its lock), so a short
74//! `ursa -c` process does not exit with a write half done. A failed write is
75//! a notice, and leaves the store as it was less what it evicted.
76//!
77//! **The in-adjacency** is built after the index, by the first algorithm that
78//! needs it (PageRank, in-degree, `direction => 'both'`), usually after the
79//! index was stored. So it is stored as a chunk of the index file (see
80//! `index_file`): with the index if it exists when the index is stored, and
81//! otherwise appended by [`IndexStore::flush`], for every index this process
82//! stored or loaded whose in-adjacency has been built since. A later process
83//! lists the chunk when it loads the index and reads it only when an
84//! algorithm asks for the in-adjacency, so a query that does not need it does
85//! not pay for it. The manifest's `size` counts the chunks, and a chunk makes
86//! room for itself as an index does (evicting other indexes, never its own),
87//! or is not appended (a notice).
88//!
89//! **Evaluated weights** are stored the same way, one chunk per set, named by
90//! the weights' key (the weighted edge plan's fingerprint and the identity of
91//! the files it reads, which include the weight column's). They are used only
92//! with an index whose full key matched, and only under the same weights key,
93//! so a changed weight expression or source file is never served stale
94//! weights. A later process reads a set when a query asks for it, and reads
95//! no edge rows. They are evicted with their index, as part of its file.
96//!
97//! A read-only database reads the manifest afresh on each lookup (a writer
98//! may be changing it) and never writes.
99
100use std::collections::{HashMap, HashSet};
101use std::fs::File;
102use std::io::{BufWriter, Write};
103use std::path::{Path, PathBuf};
104use std::sync::atomic::{AtomicU64, Ordering};
105use std::sync::{Arc, Mutex, Weak};
106use std::thread::JoinHandle;
107use std::time::{SystemTime, UNIX_EPOCH};
108
109use serde_json::{json, Value};
110
111use super::index_file::{
112    self, Encoded, EncodedChunk, IndexKey, MainPart, CHUNK_INCOMING, CHUNK_WEIGHTS,
113};
114use crate::graph::GraphIndex;
115use crate::notices::{self, NoticeLevel, Notifier};
116use crate::options::ByteSize;
117
118/// The `format` field of the manifest.
119pub const MANIFEST_FORMAT: &str = "ursa-indexes";
120/// The manifest version this build reads and writes.
121pub const MANIFEST_VERSION: u64 = 2;
122const MANIFEST: &str = "manifest.json";
123/// How notices name an index whose entry names no graph.
124const UNNAMED: &str = "a graph";
125
126/// One stored index, as the manifest lists it.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Entry {
129    pub key: IndexKey,
130    /// The file's name in the index directory.
131    pub file: String,
132    /// The graph it was built for, as notices name it.
133    pub graph: String,
134    pub size: u64,
135    /// Milliseconds since the Unix epoch.
136    pub created: u64,
137    /// Milliseconds since the Unix epoch.
138    pub last_used: u64,
139}
140
141impl Entry {
142    fn to_json(&self) -> Value {
143        json!({
144            "file": self.file,
145            "graph": self.graph,
146            "size": self.size,
147            "created": self.created,
148            "last_used": self.last_used,
149            "key": self.key.to_json(),
150        })
151    }
152
153    fn from_json(value: &Value) -> Option<Self> {
154        let file = value.get("file")?.as_str()?.to_string();
155        // A file name, never a path out of the directory.
156        if file.is_empty() || file.contains(['/', '\\']) || file.starts_with('.') {
157            return None;
158        }
159        Some(Self {
160            key: IndexKey::from_json(value.get("key")?)?,
161            file,
162            graph: value
163                .get("graph")
164                .and_then(Value::as_str)
165                .unwrap_or(UNNAMED)
166                .to_string(),
167            size: value.get("size")?.as_u64()?,
168            created: value.get("created")?.as_u64()?,
169            last_used: value.get("last_used")?.as_u64()?,
170        })
171    }
172}
173
174/// What [`IndexStore::save`] decided for an index.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub enum Saved {
177    /// Being written, in `size` bytes. `grows_to` is about what the file
178    /// takes once an algorithm adds the in-adjacency, if it is not in it
179    /// yet; `None` when it is.
180    Stored { size: u64, grows_to: Option<u64> },
181    /// The database is open read-only.
182    ReadOnly,
183    /// `size` bytes is more than the limit on its own.
184    TooLarge { size: u64, limit: u64 },
185    /// The stored indexes already take `stored` bytes, more than the limit
186    /// (lowered since they were stored): they are kept, and no new index is
187    /// stored.
188    OverLimit { stored: u64, limit: u64 },
189    /// The indexes running queries hold leave less than `size` bytes of the
190    /// limit.
191    NoRoom { size: u64, limit: u64 },
192    /// It cannot be stored (node ids of a type the file cannot hold).
193    Unstorable(String),
194}
195
196impl Saved {
197    /// Whether this loses work a later process will do again, so it is said
198    /// however quick the build was.
199    pub fn loses_work(&self) -> bool {
200        matches!(
201            self,
202            Saved::TooLarge { .. }
203                | Saved::OverLimit { .. }
204                | Saved::NoRoom { .. }
205                | Saved::Unstorable(_)
206        )
207    }
208
209    /// What became of the index, as a notice says it, for the database
210    /// named `database`.
211    pub fn describe(&self, database: &str) -> String {
212        match self {
213            Saved::Stored {
214                size,
215                grows_to: None,
216            } => format!(
217                "stored in {database} ({}, with its reverse adjacency)",
218                notices::size(*size)
219            ),
220            Saved::Stored {
221                size,
222                grows_to: Some(grown),
223            } => format!(
224                "stored in {database} ({}; about {} once an algorithm adds the reverse \
225                 adjacency)",
226                notices::size(*size),
227                notices::size(*grown)
228            ),
229            Saved::ReadOnly => format!("not stored: {database} is open read-only"),
230            Saved::TooLarge { size, limit } => format!(
231                "not stored: it takes {}, more than ursa.index_storage_limit ({}); SET \
232                 ursa.index_storage_limit = '{}' to keep it",
233                notices::size(*size),
234                ByteSize(*limit),
235                ByteSize(suggested_limit(*size))
236            ),
237            Saved::OverLimit { stored, limit } => format!(
238                "not stored: the indexes {database} stores take {}, more than \
239                 ursa.index_storage_limit ({}); they are kept, and new indexes are not stored \
240                 until it is raised",
241                notices::size(*stored),
242                ByteSize(*limit)
243            ),
244            Saved::NoRoom { size, limit } => format!(
245                "not stored: the stored indexes running queries use leave less than its {} of \
246                 ursa.index_storage_limit ({})",
247                notices::size(*size),
248                ByteSize(*limit)
249            ),
250            Saved::Unstorable(why) => format!("not stored: {why}"),
251        }
252    }
253}
254
255/// A limit to suggest for an index of `size` bytes: room for it and as much
256/// again (its in-adjacency, which algorithms such as PageRank build, is about
257/// as large), rounded up to a power of two.
258pub fn suggested_limit(size: u64) -> u64 {
259    size.saturating_mul(2)
260        .checked_next_power_of_two()
261        .unwrap_or(u64::MAX)
262        .max(1 << 20)
263}
264
265/// The stored indexes of one database.
266#[derive(Debug)]
267pub struct IndexStore {
268    dir: PathBuf,
269    writable: bool,
270    /// The database as notices name it.
271    database: String,
272    /// The most bytes the store keeps: the limit in effect for the session
273    /// that last used it.
274    limit: AtomicU64,
275    state: Mutex<State>,
276    pending: Mutex<Vec<JoinHandle<()>>>,
277    /// The notifier of the session that last used the store: what notices
278    /// decided when the database closes are said with.
279    notifier: Mutex<Notifier>,
280}
281
282#[derive(Debug, Default)]
283struct State {
284    /// Whether `entries` has been read from disk (a writer reads it once).
285    loaded: bool,
286    entries: Vec<Entry>,
287    /// Bytes of the indexes being written, which `entries` does not list yet.
288    reserved: u64,
289    /// Indexes this process loaded or stored, by file: an entry whose index
290    /// a running query holds is not evicted (see `in_use`), and chunks built
291    /// since are appended to its file (see [`IndexStore::flush`]).
292    live: HashMap<String, Live>,
293    /// Index files found damaged after they loaded (a checksum checked late,
294    /// see `super::mapped`), by file and main part: not loaded again by this
295    /// process, which builds the index instead, even when the store is
296    /// read-only and cannot remove them.
297    damaged: HashSet<(String, MainPart)>,
298}
299
300/// An index this process loaded or stored, and what its file holds.
301#[derive(Debug)]
302struct Live {
303    index: Weak<GraphIndex>,
304    main: MainPart,
305    /// The chunks the file has, by kind and name.
306    chunks: HashSet<(u32, Vec<u8>)>,
307    /// Chunks not appended for want of room: said once, not tried again.
308    declined: HashSet<(u32, Vec<u8>)>,
309    graph: String,
310}
311
312impl IndexStore {
313    /// The store in `dir`, of the database `database` (as notices name it),
314    /// keeping at most `limit` bytes. A writable store creates `dir` on its
315    /// first write.
316    pub fn new(dir: PathBuf, writable: bool, database: String, limit: u64) -> Self {
317        Self {
318            dir,
319            writable,
320            database,
321            limit: AtomicU64::new(limit),
322            state: Mutex::new(State::default()),
323            pending: Mutex::new(Vec::new()),
324            notifier: Mutex::new(Notifier::silent()),
325        }
326    }
327
328    pub fn dir(&self) -> &Path {
329        &self.dir
330    }
331
332    pub fn is_writable(&self) -> bool {
333        self.writable
334    }
335
336    /// The database as notices name it.
337    pub fn database(&self) -> &str {
338        &self.database
339    }
340
341    /// The most bytes of indexes the store keeps.
342    pub fn limit(&self) -> u64 {
343        self.limit.load(Ordering::Relaxed)
344    }
345
346    /// Keep at most `limit` bytes from now on: the next index stored makes
347    /// room within it. Nothing is evicted now, nor later to bring indexes
348    /// already stored within a lower limit.
349    pub fn set_limit(&self, limit: u64) {
350        self.limit.store(limit, Ordering::Relaxed);
351    }
352
353    /// The bytes of the indexes stored, and being written, as this process
354    /// knows them.
355    pub fn stored_bytes(&self) -> u64 {
356        if !self.writable {
357            return manifest_bytes(&self.dir);
358        }
359        let state = self.state();
360        if !state.loaded {
361            return manifest_bytes(&self.dir);
362        }
363        state.reserved + state.entries.iter().map(|e| e.size).sum::<u64>()
364    }
365
366    fn state(&self) -> std::sync::MutexGuard<'_, State> {
367        self.state.lock().unwrap_or_else(|e| e.into_inner())
368    }
369
370    fn notifier(&self) -> Notifier {
371        self.notifier
372            .lock()
373            .unwrap_or_else(|e| e.into_inner())
374            .clone()
375    }
376
377    fn use_notifier(&self, notifier: &Notifier) {
378        *self.notifier.lock().unwrap_or_else(|e| e.into_inner()) = notifier.clone();
379    }
380
381    /// The manifest's entries, as this process knows them.
382    pub fn entries(&self) -> Vec<Entry> {
383        if !self.writable {
384            return read_manifest(&self.dir);
385        }
386        let mut state = self.state();
387        self.ensure_loaded(&mut state);
388        state.entries.clone()
389    }
390
391    /// Read the manifest and tidy the directory, once (writers only).
392    fn ensure_loaded(&self, state: &mut State) {
393        if state.loaded {
394            return;
395        }
396        state.loaded = true;
397        let manifest = read_manifest_checked(&self.dir);
398        let mut entries = manifest.entries;
399        let before = entries.len();
400        entries.retain(|e| self.dir.join(&e.file).is_file());
401        // One entry per file and per fingerprint, should a manifest have more.
402        let mut files = HashSet::new();
403        let mut fingerprints = HashSet::new();
404        entries.retain(|e| {
405            files.insert(e.file.clone()) && fingerprints.insert(e.key.fingerprint.clone())
406        });
407        let changed = entries.len() != before || manifest.foreign.is_some();
408        // Remove what the manifest does not list: index files written but
409        // never listed, and temporary files of interrupted writes.
410        let mut freed = 0;
411        if let Ok(listing) = std::fs::read_dir(&self.dir) {
412            for item in listing.flatten() {
413                let name = item.file_name().to_string_lossy().into_owned();
414                let ours = name.ends_with(".idx") || name.ends_with(".tmp");
415                if ours && !files.contains(&name) {
416                    freed += item.metadata().map_or(0, |m| m.len());
417                    let _ = std::fs::remove_file(item.path());
418                }
419            }
420        }
421        if let Some(n) = manifest.foreign.filter(|n| *n > 0) {
422            self.notifier().say(NoticeLevel::On, || {
423                format!(
424                    "removed {n} stored {} ({}) from {} written by another version of ursa; \
425                     each is built again when it is first used",
426                    if n == 1 { "index" } else { "indexes" },
427                    notices::size(freed),
428                    self.database
429                )
430            });
431        }
432        state.entries = entries;
433        if changed {
434            let _ = write_manifest(&self.dir, &state.entries);
435        }
436    }
437
438    /// Whether the keys `key` names (a vertex table's: the fingerprint of
439    /// their plan and the files it reads) were counted and found to be one
440    /// row each, by this process or an earlier one (#411; see
441    /// `crate::graph::vertex_keys`). Read from `vertex_keys.json` each time:
442    /// it is small, and another process may have written it.
443    pub fn keys_counted(&self, key: &IndexKey) -> bool {
444        read_key_counts(&self.dir).contains(key)
445    }
446
447    /// Record that the keys `key` names are one row each. A read-only store
448    /// records nothing. Best effort: a count that is not recorded is made
449    /// again.
450    pub fn record_keys_counted(&self, key: IndexKey) {
451        if !self.writable {
452            return;
453        }
454        // One writer at a time in this process; a database has one writing
455        // process.
456        let _state = self.state();
457        let mut counted = read_key_counts(&self.dir);
458        // A newer version of a table's files replaces the older one.
459        counted.retain(|k| k.fingerprint != key.fingerprint);
460        counted.push(key);
461        if counted.len() > KEY_COUNTS_KEPT {
462            counted.drain(..counted.len() - KEY_COUNTS_KEPT);
463        }
464        let _ = write_key_counts(&self.dir, &counted);
465    }
466
467    /// Whether the manifest lists an index stored under `key`. Nothing is
468    /// read but the manifest: [`Self::load`] still checks the file.
469    pub fn contains(&self, key: &IndexKey) -> bool {
470        self.entries().iter().any(|e| e.key == *key)
471    }
472
473    /// The stored index for `key`, if there is one whose full key matches
474    /// and whose file reads back whole, and the size of its file. Blocking:
475    /// it reads the file.
476    pub fn load(
477        self: &Arc<Self>,
478        key: &IndexKey,
479        notifier: &Notifier,
480    ) -> Option<(Arc<GraphIndex>, u64)> {
481        let entry = if self.writable {
482            self.use_notifier(notifier);
483            let mut state = self.state();
484            self.ensure_loaded(&mut state);
485            state.entries.iter().find(|e| e.key == *key)?.clone()
486        } else {
487            read_manifest(&self.dir)
488                .into_iter()
489                .find(|e| e.key == *key)?
490        };
491        let file = entry.file.clone();
492        let read = index_file::read_file(&self.dir.join(&file), key);
493        let mut state = self.state();
494        match read {
495            Ok(stored) if state.damaged.contains(&(file.clone(), stored.main)) => None,
496            Ok(stored) => {
497                let has_incoming = stored.chunks.iter().any(|c| c.kind == CHUNK_INCOMING);
498                let chunks = stored
499                    .chunks
500                    .iter()
501                    .map(|c| (c.kind, c.name.clone()))
502                    .collect();
503                let weights: Vec<index_file::ChunkInfo> = stored
504                    .chunks
505                    .into_iter()
506                    .filter(|c| c.kind == CHUNK_WEIGHTS)
507                    .collect();
508                let keys = weights
509                    .iter()
510                    .filter_map(|c| String::from_utf8(c.name.clone()).ok())
511                    .collect();
512                let (path, main) = (self.dir.join(&file), stored.main);
513                let n_edges = stored.topology.n_edges();
514                if let Some(checks) = &stored.unverified {
515                    // A checksum found not to match drops the file, so the
516                    // index is built again.
517                    let (store, file) = (Arc::downgrade(self), file.clone());
518                    checks.on_damage(Box::new(move || {
519                        if let Some(store) = store.upgrade() {
520                            store.discard(&file, main);
521                        }
522                    }));
523                }
524                let read = Box::new(move |key: &str| {
525                    let chunk = weights.iter().find(|c| c.name == key.as_bytes())?;
526                    index_file::read_weights(&path, main, chunk, n_edges).ok()
527                });
528                let index = Arc::new(
529                    GraphIndex::new(Arc::new(stored.topology), Arc::new(stored.ids))
530                        .with_dropped(stored.dropped.n_dropped, stored.dropped.kept)
531                        .with_stored_weights(keys, read)
532                        .with_unverified(stored.unverified),
533                );
534                state.live.insert(
535                    file.clone(),
536                    Live {
537                        index: Arc::downgrade(&index),
538                        main: stored.main,
539                        chunks,
540                        declined: HashSet::new(),
541                        graph: entry.graph.clone(),
542                    },
543                );
544                if self.writable {
545                    let now = tick(&state.entries);
546                    if let Some(entry) = state.entries.iter_mut().find(|e| e.file == file) {
547                        entry.last_used = now;
548                        let _ = write_manifest(&self.dir, &state.entries);
549                    }
550                }
551                drop(state);
552                if stored.version != index_file::VERSION && self.writable {
553                    let version = stored.version;
554                    self.upgrade(key, &index, &entry.graph, version, has_incoming, notifier);
555                }
556                Some((index, entry.size))
557            }
558            Err(_) => {
559                if self.writable {
560                    let before = state.entries.len();
561                    state.entries.retain(|e| e.file != file);
562                    if state.entries.len() != before {
563                        let _ = std::fs::remove_file(self.dir.join(&file));
564                        let _ = write_manifest(&self.dir, &state.entries);
565                    }
566                }
567                None
568            }
569        }
570    }
571
572    /// Store again, in the current format, `index`, just read from a file
573    /// of an older format `version`: one 0.10 wrote (version 2), so later
574    /// processes map it instead of reading it whole, or one 0.11 wrote
575    /// (version 3), so they find its node ids' lookup table in the file
576    /// instead of building it. Its in-adjacency, if the file has one, is
577    /// read first, to be stored with it; weights stored with it are
578    /// evaluated again when next needed.
579    fn upgrade(
580        self: &Arc<Self>,
581        key: &IndexKey,
582        index: &Arc<GraphIndex>,
583        graph: &str,
584        version: u32,
585        has_incoming: bool,
586        notifier: &Notifier,
587    ) {
588        // What a process pays for the old format, until the file is rewritten.
589        let until = match version {
590            index_file::VERSION_2 => "it is read whole",
591            _ => "each process that looks a node up by its id builds the ids' lookup table",
592        };
593        if has_incoming {
594            index.topology.incoming();
595        }
596        let saved = self.save(key.clone(), Arc::clone(index), graph, notifier);
597        notifier.say(NoticeLevel::On, || match saved {
598            Saved::Stored { size, .. } => format!(
599                "rewriting the stored index for {graph} in {} ({}) in the current format: an \
600                 older version of ursa stored it, and {until} until it is rewritten",
601                self.database,
602                notices::size(size)
603            ),
604            _ => format!(
605                "an older version of ursa stored the index for {graph} in {}; {until} \
606                 until it can be rewritten in the current format, and was {}",
607                self.database,
608                saved.describe(&self.database)
609            ),
610        });
611    }
612
613    /// Drop the entry and file of `file`, whose main part is `main`, found
614    /// damaged after it was loaded (a checksum checked late, see
615    /// `super::mapped`): the index is built again when next needed. A
616    /// read-only store, or a file replaced since, is left as it is; this
617    /// process does not load that main part again either way.
618    fn discard(&self, file: &str, main: MainPart) {
619        let mut state = self.state();
620        state.damaged.insert((file.to_string(), main));
621        if !self.writable {
622            return;
623        }
624        self.ensure_loaded(&mut state);
625        if state.live.get(file).is_some_and(|live| live.main != main) {
626            return;
627        }
628        let before = state.entries.len();
629        state.entries.retain(|e| e.file != file);
630        state.live.remove(file);
631        if state.entries.len() != before {
632            let _ = write_manifest(&self.dir, &state.entries);
633            drop(state);
634            let _ = std::fs::remove_file(self.dir.join(file));
635        }
636    }
637
638    /// Decide whether to store `index`, built for the graph `graph`, under
639    /// `key` (see the module docs), evict what that takes, and start the
640    /// write on a background thread. Evictions and a failed write are said
641    /// with `notifier`; what was decided is returned for the caller to say.
642    pub fn save(
643        self: &Arc<Self>,
644        key: IndexKey,
645        index: Arc<GraphIndex>,
646        graph: &str,
647        notifier: &Notifier,
648    ) -> Saved {
649        if !self.writable {
650            return Saved::ReadOnly;
651        }
652        self.use_notifier(notifier);
653        let limit = self.limit();
654        let encoded = match Encoded::with_dropped(
655            &key,
656            &index.topology,
657            &index.ids,
658            index.n_dropped(),
659            index.kept_rows(),
660        ) {
661            Ok(encoded) => encoded,
662            Err(e) => return Saved::Unstorable(e.to_string()),
663        };
664        let main = encoded.file_size();
665        let size = if main > limit {
666            main
667        } else {
668            // The in-adjacency, if it is built by now and fits.
669            index
670                .topology
671                .incoming_if_built()
672                .map(|incoming| EncodedChunk::incoming(incoming, main).end())
673                .filter(|end| *end <= limit)
674                .unwrap_or(main)
675        };
676        drop(encoded);
677        if size > limit {
678            return Saved::TooLarge { size, limit };
679        }
680        let with_incoming = size > main;
681        let grows_to = (!with_incoming).then(|| {
682            size.saturating_add(incoming_estimate(
683                index.topology.n_nodes() as u64,
684                index.topology.n_edges() as u64,
685            ))
686        });
687        let file = format!("{:016x}.idx", key.hash());
688
689        let mut state = self.state();
690        self.ensure_loaded(&mut state);
691        // Replaced: the same fingerprint (the same edges over files that have
692        // changed since), or the same file name.
693        let replaced: Vec<String> = state
694            .entries
695            .iter()
696            .filter(|e| e.key.fingerprint == key.fingerprint || e.file == file)
697            .map(|e| e.file.clone())
698            .collect();
699        let evicted = match room_for(&state, size, &replaced, &[], limit) {
700            Ok(evicted) => evicted,
701            Err(NoRoom::OverLimit { stored }) => return Saved::OverLimit { stored, limit },
702            Err(NoRoom::InUse) => return Saved::NoRoom { size, limit },
703        };
704        let gone = self.remove(&mut state, &replaced, &evicted, notifier, limit);
705        state.reserved += size;
706        drop(state);
707        for file in gone {
708            let _ = std::fs::remove_file(self.dir.join(file));
709        }
710
711        let store = Arc::clone(self);
712        let (graph, notifier) = (graph.to_string(), notifier.clone());
713        let spawned = std::thread::Builder::new()
714            .name("ursa-index-write".into())
715            .spawn(move || {
716                let written = store.write(&key, &index, &file, size, with_incoming, &graph);
717                if let Err(e) = written {
718                    store.state().reserved -= size;
719                    notifier.say(NoticeLevel::On, || {
720                        format!(
721                            "could not store the index for {graph} in {}: {e}; it is built \
722                             again when next needed",
723                            store.database
724                        )
725                    });
726                }
727            });
728        match spawned {
729            Ok(handle) => {
730                let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
731                pending.retain(|h| !h.is_finished());
732                pending.push(handle);
733                Saved::Stored { size, grows_to }
734            }
735            Err(e) => {
736                self.state().reserved -= size;
737                Saved::Unstorable(format!("cannot start its write: {e}"))
738            }
739        }
740    }
741
742    /// Remove the entries of `replaced` and `evicted` from the manifest,
743    /// saying each eviction. Returns the files to delete.
744    fn remove(
745        &self,
746        state: &mut State,
747        replaced: &[String],
748        evicted: &[String],
749        notifier: &Notifier,
750        limit: u64,
751    ) -> Vec<String> {
752        if replaced.is_empty() && evicted.is_empty() {
753            return Vec::new();
754        }
755        let mut gone = Vec::new();
756        state.entries.retain(|e| {
757            if evicted.contains(&e.file) {
758                notifier.say(NoticeLevel::On, || {
759                    format!(
760                        "evicted the stored index for {} ({}, the least recently used) from {} \
761                         to stay within ursa.index_storage_limit ({})",
762                        e.graph,
763                        notices::size(e.size),
764                        self.database,
765                        ByteSize(limit)
766                    )
767                });
768            }
769            let keep = !replaced.contains(&e.file) && !evicted.contains(&e.file);
770            if !keep {
771                gone.push(e.file.clone());
772            }
773            keep
774        });
775        let _ = write_manifest(&self.dir, &state.entries);
776        gone
777    }
778
779    /// Wait for every write [`save`](Self::save) started, then append to
780    /// each index file this process stored or loaded the parts of its index
781    /// built since (the in-adjacency, evaluated weights), within the storage
782    /// limit.
783    pub fn flush(&self) {
784        let handles = std::mem::take(&mut *self.pending.lock().unwrap_or_else(|e| e.into_inner()));
785        for handle in handles {
786            let _ = handle.join();
787        }
788        if self.writable {
789            self.append_chunks();
790        }
791    }
792
793    /// Append to every live index file the in-adjacency and the weight sets
794    /// its index has built since and the file lacks, each making room for
795    /// itself as an index does. A failed append leaves the file as it was
796    /// (less any partial chunk); what it held is built again by the next
797    /// process that needs it.
798    fn append_chunks(&self) {
799        let notifier = self.notifier();
800        let limit = self.limit();
801        let mut state = self.state();
802        self.ensure_loaded(&mut state);
803        let files: Vec<String> = state.live.keys().cloned().collect();
804        let mut gone = Vec::new();
805        for file in files {
806            let live = &state.live[&file];
807            let Some(index) = live.index.upgrade() else {
808                continue;
809            };
810            let (main, graph) = (live.main, live.graph.clone());
811            let mut todo: Vec<(u32, Vec<u8>)> = Vec::new();
812            if index.topology.incoming_if_built().is_some() {
813                todo.push((CHUNK_INCOMING, Vec::new()));
814            }
815            let weight_sets = index.weight_sets();
816            todo.extend(
817                weight_sets
818                    .iter()
819                    .map(|(key, _)| (CHUNK_WEIGHTS, key.as_bytes().to_vec())),
820            );
821            todo.retain(|chunk| !live.chunks.contains(chunk) && !live.declined.contains(chunk));
822            for (kind, name) in todo {
823                let Some(entry) = state.entries.iter().position(|e| e.file == file) else {
824                    break;
825                };
826                let columns: Vec<&[f64]> = match kind {
827                    CHUNK_WEIGHTS => weight_sets
828                        .iter()
829                        .find(|(key, _)| key.as_bytes() == name.as_slice())
830                        .map(|(_, w)| w.iter().map(|c| c.as_slice()).collect())
831                        .unwrap_or_default(),
832                    _ => Vec::new(),
833                };
834                let encode = |start| match kind {
835                    CHUNK_WEIGHTS => EncodedChunk::weights(
836                        std::str::from_utf8(&name).unwrap_or_default(),
837                        &columns,
838                        start,
839                    ),
840                    _ => EncodedChunk::incoming(
841                        index.topology.incoming_if_built().expect("checked above"),
842                        start,
843                    ),
844                };
845                let size = state.entries[entry].size;
846                let need = encode(size).size();
847                let what = chunk_noun(kind);
848                let room = room_for(&state, need, &[], std::slice::from_ref(&file), limit);
849                let Ok(evicted) = room else {
850                    notifier.say(NoticeLevel::On, || match room {
851                        Err(NoRoom::OverLimit { stored }) => format!(
852                            "did not store the {what} of the index for {graph} ({}) in {}: the \
853                             stored indexes already take {}, more than \
854                             ursa.index_storage_limit ({})",
855                            notices::size(need),
856                            self.database,
857                            notices::size(stored),
858                            ByteSize(limit)
859                        ),
860                        _ => format!(
861                            "did not store the {what} of the index for {graph} ({}) in {}: it \
862                             would take the stored indexes past ursa.index_storage_limit ({})",
863                            notices::size(need),
864                            self.database,
865                            ByteSize(limit)
866                        ),
867                    });
868                    if let Some(live) = state.live.get_mut(&file) {
869                        live.declined.insert((kind, name));
870                    }
871                    continue;
872                };
873                gone.extend(self.remove(&mut state, &[], &evicted, &notifier, limit));
874                let Some(entry) = state.entries.iter().position(|e| e.file == file) else {
875                    break;
876                };
877                let result =
878                    index_file::append_chunk(&self.dir.join(&file), main, kind, &name, encode);
879                match result {
880                    Ok(appended_len) => {
881                        if let Some(live) = state.live.get_mut(&file) {
882                            live.chunks.insert((kind, name));
883                        }
884                        if let Some(len) = appended_len {
885                            state.entries[entry].size = len;
886                            let _ = write_manifest(&self.dir, &state.entries);
887                            let stored =
888                                state.reserved + state.entries.iter().map(|e| e.size).sum::<u64>();
889                            say_appended(
890                                &notifier,
891                                &Appended {
892                                    what: chunk_noun(kind),
893                                    graph: &graph,
894                                    database: &self.database,
895                                    added: len.saturating_sub(size),
896                                    total: len,
897                                    stored,
898                                    limit,
899                                },
900                            );
901                        }
902                    }
903                    Err(e) => notifier.say(NoticeLevel::On, || {
904                        format!(
905                            "could not store the {} of {graph} in {}: {e}",
906                            chunk_noun(kind),
907                            self.database
908                        )
909                    }),
910                }
911            }
912        }
913        drop(state);
914        for file in gone {
915            let _ = std::fs::remove_file(self.dir.join(file));
916        }
917    }
918
919    /// Write `index` under `key` to `file`, in `planned` bytes (with its
920    /// in-adjacency as a chunk if `with_incoming`), then list it. Room was
921    /// made by [`Self::save`].
922    fn write(
923        &self,
924        key: &IndexKey,
925        index: &Arc<GraphIndex>,
926        file: &str,
927        planned: u64,
928        with_incoming: bool,
929        graph: &str,
930    ) -> std::io::Result<()> {
931        let encoded = Encoded::with_dropped(
932            key,
933            &index.topology,
934            &index.ids,
935            index.n_dropped(),
936            index.kept_rows(),
937        )?;
938        let incoming = index
939            .topology
940            .incoming_if_built()
941            .filter(|_| with_incoming)
942            .map(|incoming| EncodedChunk::incoming(incoming, encoded.file_size()));
943        let size = incoming
944            .as_ref()
945            .map_or(encoded.file_size(), EncodedChunk::end);
946        std::fs::create_dir_all(&self.dir)?;
947        let path = self.dir.join(file);
948        let temp = self.dir.join(format!("{file}.tmp"));
949        let written = (|| {
950            let out = File::create(&temp)?;
951            let mut writer = BufWriter::with_capacity(1 << 20, out);
952            let main = encoded.write_to(&mut writer)?;
953            if let Some(chunk) = &incoming {
954                chunk.write_to(&mut writer)?;
955            }
956            let out = writer.into_inner().map_err(|e| e.into_error())?;
957            out.sync_all()?;
958            std::fs::rename(&temp, &path)?;
959            Ok(main)
960        })();
961        let main = match written {
962            Ok(main) => main,
963            Err(e) => {
964                let _ = std::fs::remove_file(&temp);
965                return Err(e);
966            }
967        };
968
969        let mut state = self.state();
970        state.reserved -= planned;
971        state.entries.retain(|e| e.file != file);
972        let now = tick(&state.entries);
973        state.entries.push(Entry {
974            key: key.clone(),
975            file: file.to_string(),
976            graph: graph.to_string(),
977            size,
978            created: now,
979            last_used: now,
980        });
981        let chunks = incoming
982            .iter()
983            .map(|_| (CHUNK_INCOMING, Vec::new()))
984            .collect();
985        state.live.insert(
986            file.to_string(),
987            Live {
988                index: Arc::downgrade(index),
989                main,
990                chunks,
991                declined: HashSet::new(),
992                graph: graph.to_string(),
993            },
994        );
995        state.live.retain(|_, live| live.index.strong_count() > 0);
996        let saved = write_manifest(&self.dir, &state.entries);
997        drop(state);
998        sync_dir(&self.dir);
999        saved
1000    }
1001}
1002
1003impl Drop for IndexStore {
1004    fn drop(&mut self) {
1005        self.flush();
1006    }
1007}
1008
1009/// Why [`room_for`] found no room.
1010#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1011enum NoRoom {
1012    /// The stored indexes already take `stored` bytes, more than the limit
1013    /// (it was lowered): nothing is evicted, and nothing new is stored.
1014    OverLimit { stored: u64 },
1015    /// Evicting every index no running query holds would not make room.
1016    InUse,
1017}
1018
1019/// The entries to evict, least recently used first, to fit `need` more bytes
1020/// within `limit`, beside the indexes being written and every entry but
1021/// those of `dropping` (which are going anyway). Entries of `keep` and any
1022/// index a running query holds are never chosen. Eviction only makes room for
1023/// something new, never more than it needs: if the stored indexes are
1024/// already over `limit`, or no choice makes room, nothing is evicted.
1025fn room_for(
1026    state: &State,
1027    need: u64,
1028    dropping: &[String],
1029    keep: &[String],
1030    limit: u64,
1031) -> Result<Vec<String>, NoRoom> {
1032    let staying = |e: &&Entry| !dropping.contains(&e.file);
1033    let mut total: u64 = state.reserved
1034        + state
1035            .entries
1036            .iter()
1037            .filter(staying)
1038            .map(|e| e.size)
1039            .sum::<u64>();
1040    if total > limit {
1041        return Err(NoRoom::OverLimit { stored: total });
1042    }
1043    let mut candidates: Vec<&Entry> = state
1044        .entries
1045        .iter()
1046        .filter(staying)
1047        .filter(|e| !keep.contains(&e.file) && !in_use(&state.live, &e.file))
1048        .collect();
1049    candidates.sort_by_key(|e| (e.last_used, e.created));
1050    let mut evicted = Vec::new();
1051    let mut candidates = candidates.into_iter();
1052    while total.saturating_add(need) > limit {
1053        let entry = candidates.next().ok_or(NoRoom::InUse)?;
1054        total -= entry.size;
1055        evicted.push(entry.file.clone());
1056    }
1057    Ok(evicted)
1058}
1059
1060/// Whether a running query holds the index stored in `file`: the session's
1061/// index cache holds one reference to an index it keeps, and a query using it
1062/// holds another.
1063fn in_use(live: &HashMap<String, Live>, file: &str) -> bool {
1064    live.get(file)
1065        .is_some_and(|live| live.index.strong_count() > 1)
1066}
1067
1068/// Now, in milliseconds since the Unix epoch, and after every time in
1069/// `entries`, so the order of uses is the order of their times.
1070fn tick(entries: &[Entry]) -> u64 {
1071    let now = SystemTime::now()
1072        .duration_since(UNIX_EPOCH)
1073        .map(|d| d.as_millis() as u64)
1074        .unwrap_or(0);
1075    let latest = entries
1076        .iter()
1077        .map(|e| e.last_used.max(e.created))
1078        .max()
1079        .map_or(0, |t| t + 1);
1080    now.max(latest)
1081}
1082
1083/// A manifest as read: its entries, and, for a manifest of another version,
1084/// how many indexes it lists (they are not read).
1085struct Manifest {
1086    entries: Vec<Entry>,
1087    foreign: Option<usize>,
1088}
1089
1090/// The manifest in `dir`: empty if it is missing or not a manifest this
1091/// build reads. Entries it cannot read are skipped.
1092pub fn read_manifest(dir: &Path) -> Vec<Entry> {
1093    read_manifest_checked(dir).entries
1094}
1095
1096/// The bytes of the indexes the manifest in `dir` lists.
1097pub fn manifest_bytes(dir: &Path) -> u64 {
1098    read_manifest(dir).iter().map(|e| e.size).sum()
1099}
1100
1101/// About how many bytes the in-adjacency of an index of `n_nodes` nodes and
1102/// `n_edges` edges adds to its file: its offsets, targets and edge ids, and
1103/// a little for the chunk's header and table.
1104pub fn incoming_estimate(n_nodes: u64, n_edges: u64) -> u64 {
1105    n_nodes
1106        .saturating_add(1)
1107        .saturating_mul(8)
1108        .saturating_add(n_edges.saturating_mul(8))
1109        .saturating_add(4096)
1110}
1111
1112fn read_manifest_checked(dir: &Path) -> Manifest {
1113    let empty = |foreign| Manifest {
1114        entries: Vec::new(),
1115        foreign,
1116    };
1117    let Ok(text) = std::fs::read_to_string(dir.join(MANIFEST)) else {
1118        return empty(None);
1119    };
1120    let Ok(value) = serde_json::from_str::<Value>(&text) else {
1121        return empty(None);
1122    };
1123    if value.get("format").and_then(Value::as_str) != Some(MANIFEST_FORMAT) {
1124        return empty(None);
1125    }
1126    let listed = value.get("indexes").and_then(Value::as_array);
1127    if value.get("version").and_then(Value::as_u64) != Some(MANIFEST_VERSION) {
1128        return empty(Some(listed.map_or(0, Vec::len)));
1129    }
1130    Manifest {
1131        entries: listed
1132            .map(|entries| entries.iter().filter_map(Entry::from_json).collect())
1133            .unwrap_or_default(),
1134        foreign: None,
1135    }
1136}
1137
1138/// The record of the vertex tables whose keys were counted: beside the
1139/// manifest, as `{"format": "ursa-vertex-keys", "version": 1, "counted":
1140/// [key, …]}`, each key as a stored index's.
1141const KEY_COUNTS: &str = "vertex_keys.json";
1142const KEY_COUNTS_FORMAT: &str = "ursa-vertex-keys";
1143const KEY_COUNTS_VERSION: u64 = 1;
1144/// How many vertex tables' counts a database keeps, the newest.
1145const KEY_COUNTS_KEPT: usize = 64;
1146
1147/// The keys recorded in `dir`: none if the record is missing or is not one
1148/// this build reads.
1149fn read_key_counts(dir: &Path) -> Vec<IndexKey> {
1150    let Ok(text) = std::fs::read_to_string(dir.join(KEY_COUNTS)) else {
1151        return Vec::new();
1152    };
1153    let Ok(value) = serde_json::from_str::<Value>(&text) else {
1154        return Vec::new();
1155    };
1156    if value.get("format").and_then(Value::as_str) != Some(KEY_COUNTS_FORMAT)
1157        || value.get("version").and_then(Value::as_u64) != Some(KEY_COUNTS_VERSION)
1158    {
1159        return Vec::new();
1160    }
1161    value
1162        .get("counted")
1163        .and_then(Value::as_array)
1164        .map(|keys| keys.iter().filter_map(IndexKey::from_json).collect())
1165        .unwrap_or_default()
1166}
1167
1168/// Rewrite the record of counted keys in `dir` atomically.
1169fn write_key_counts(dir: &Path, counted: &[IndexKey]) -> std::io::Result<()> {
1170    std::fs::create_dir_all(dir)?;
1171    let value = json!({
1172        "format": KEY_COUNTS_FORMAT,
1173        "version": KEY_COUNTS_VERSION,
1174        "counted": counted.iter().map(IndexKey::to_json).collect::<Vec<_>>(),
1175    });
1176    let mut text = serde_json::to_string_pretty(&value).map_err(std::io::Error::other)?;
1177    text.push('\n');
1178    // Not `.tmp`: a writer removes those when it tidies the directory.
1179    let temp = dir.join(format!("{KEY_COUNTS}.new"));
1180    {
1181        let mut file = File::create(&temp)?;
1182        file.write_all(text.as_bytes())?;
1183        file.sync_all()?;
1184    }
1185    std::fs::rename(&temp, dir.join(KEY_COUNTS))?;
1186    sync_dir(dir);
1187    Ok(())
1188}
1189
1190/// Rewrite the manifest in `dir` atomically.
1191fn write_manifest(dir: &Path, entries: &[Entry]) -> std::io::Result<()> {
1192    std::fs::create_dir_all(dir)?;
1193    let value = json!({
1194        "format": MANIFEST_FORMAT,
1195        "version": MANIFEST_VERSION,
1196        "indexes": entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
1197    });
1198    let mut text = serde_json::to_string_pretty(&value).map_err(std::io::Error::other)?;
1199    text.push('\n');
1200    let temp = dir.join(format!("{MANIFEST}.tmp"));
1201    {
1202        let mut file = File::create(&temp)?;
1203        file.write_all(text.as_bytes())?;
1204        file.sync_all()?;
1205    }
1206    std::fs::rename(&temp, dir.join(MANIFEST))?;
1207    sync_dir(dir);
1208    Ok(())
1209}
1210
1211/// `fsync` a directory so a rename in it is durable. Best effort.
1212fn sync_dir(dir: &Path) {
1213    #[cfg(unix)]
1214    if let Ok(dir) = File::open(dir) {
1215        let _ = dir.sync_all();
1216    }
1217    #[cfg(not(unix))]
1218    let _ = dir;
1219}
1220
1221/// What a chunk of an index file holds, as notices name it.
1222fn chunk_noun(kind: u32) -> &'static str {
1223    match kind {
1224        CHUNK_WEIGHTS => "evaluated weights",
1225        _ => "reverse adjacency",
1226    }
1227}
1228
1229/// The share of `ursa.index_storage_limit`, in percent, past which storing a
1230/// chunk is said at `ursa.notices = 'on'`, not only at `'all'`.
1231const NEAR_LIMIT_PERCENT: u64 = 90;
1232
1233/// A chunk appended to an index file (#381).
1234struct Appended<'a> {
1235    what: &'static str,
1236    graph: &'a str,
1237    database: &'a str,
1238    /// The bytes it added to the file.
1239    added: u64,
1240    /// The file's bytes now.
1241    total: u64,
1242    /// The bytes of every stored index now.
1243    stored: u64,
1244    limit: u64,
1245}
1246
1247/// Say that a chunk was stored: at `'all'`, and at `'on'` too when it brings
1248/// the stored indexes close to the limit, which the next index stored may
1249/// then have to make room under.
1250fn say_appended(notifier: &Notifier, appended: &Appended) {
1251    let near =
1252        appended.stored.saturating_mul(100) >= appended.limit.saturating_mul(NEAR_LIMIT_PERCENT);
1253    let level = if near {
1254        NoticeLevel::On
1255    } else {
1256        NoticeLevel::All
1257    };
1258    notifier.say(level, || appended_notice(appended, near));
1259}
1260
1261fn appended_notice(appended: &Appended, near: bool) -> String {
1262    let mut text = format!(
1263        "stored the {} of {} in {} (+{}, {} in all)",
1264        appended.what,
1265        appended.graph,
1266        appended.database,
1267        notices::size(appended.added),
1268        notices::size(appended.total)
1269    );
1270    if near {
1271        text.push_str(&format!(
1272            "; the stored indexes now take {} of ursa.index_storage_limit ({})",
1273            notices::size(appended.stored),
1274            ByteSize(appended.limit)
1275        ));
1276    }
1277    text
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use super::*;
1283
1284    #[test]
1285    fn the_notice_for_a_stored_reverse_adjacency() {
1286        let gib = 1u64 << 30;
1287        let appended = Appended {
1288            what: "reverse adjacency",
1289            graph: "bsky23p",
1290            database: "bsky10.ursa",
1291            added: gib + gib / 10,
1292            total: 2 * gib + gib / 2,
1293            stored: 2 * gib + gib / 2,
1294            limit: 20 * gib,
1295        };
1296        assert_eq!(
1297            appended_notice(&appended, false),
1298            "stored the reverse adjacency of bsky23p in bsky10.ursa (+1.1 GiB, 2.5 GiB in all)"
1299        );
1300        assert_eq!(
1301            appended_notice(&appended, true),
1302            "stored the reverse adjacency of bsky23p in bsky10.ursa (+1.1 GiB, 2.5 GiB in all); \
1303             the stored indexes now take 2.5 GiB of ursa.index_storage_limit (20GiB)"
1304        );
1305    }
1306
1307    #[test]
1308    fn eviction_only_makes_room_and_never_below_a_lowered_limit() {
1309        let entry = |file: &str, size, last_used| Entry {
1310            key: IndexKey::new(file.into(), Vec::new()),
1311            file: file.into(),
1312            graph: file.into(),
1313            size,
1314            created: 0,
1315            last_used,
1316        };
1317        let state = State {
1318            loaded: true,
1319            entries: vec![entry("a", 300, 1), entry("b", 300, 2), entry("c", 300, 3)],
1320            ..State::default()
1321        };
1322        // Room already: nothing is evicted.
1323        assert_eq!(room_for(&state, 100, &[], &[], 1000), Ok(vec![]));
1324        // Only as many as it takes, least recently used first.
1325        assert_eq!(room_for(&state, 200, &[], &[], 1000), Ok(vec!["a".into()]));
1326        assert_eq!(
1327            room_for(&state, 700, &[], &[], 1000),
1328            Ok(vec!["a".into(), "b".into()])
1329        );
1330        // A limit lowered below what is stored evicts nothing, even to store
1331        // something small.
1332        assert_eq!(
1333            room_for(&state, 1, &[], &[], 500),
1334            Err(NoRoom::OverLimit { stored: 900 })
1335        );
1336        // ... unless what is going anyway brings it within.
1337        assert_eq!(room_for(&state, 100, &["c".into()], &[], 700), Ok(vec![]));
1338        // Kept entries are never chosen.
1339        assert_eq!(
1340            room_for(&state, 900, &[], &["a".into(), "b".into()], 1000),
1341            Err(NoRoom::InUse)
1342        );
1343    }
1344
1345    #[test]
1346    fn a_stored_notice_says_how_the_index_grows() {
1347        let gib = 1u64 << 30;
1348        assert_eq!(
1349            Saved::Stored {
1350                size: 768 << 20,
1351                grows_to: Some(3 * gib / 2)
1352            }
1353            .describe("club.ursa"),
1354            "stored in club.ursa (768.0 MiB; about 1.5 GiB once an algorithm adds the reverse \
1355             adjacency)"
1356        );
1357        assert_eq!(
1358            Saved::Stored {
1359                size: 3 * gib / 2,
1360                grows_to: None
1361            }
1362            .describe("club.ursa"),
1363            "stored in club.ursa (1.5 GiB, with its reverse adjacency)"
1364        );
1365        // 95.7M edges over 10M nodes: about 806 MiB more.
1366        let more = incoming_estimate(10_000_000, 95_700_000);
1367        assert!((800 << 20..810 << 20).contains(&more), "{more}");
1368    }
1369
1370    #[test]
1371    fn the_suggested_limit_leaves_room_for_the_in_adjacency() {
1372        let gib = 1u64 << 30;
1373        assert_eq!(suggested_limit(21 * gib), 64 * gib);
1374        assert_eq!(suggested_limit(1_503_238_554), 4 * gib);
1375        assert_eq!(suggested_limit(3000), 1 << 20);
1376        assert_eq!(ByteSize(suggested_limit(13 * gib)).to_string(), "32GiB");
1377    }
1378}