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