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