Skip to main content

ursa_engine/graph/
index.rs

1//! Graph indexes, and the session's cache of them.
2//!
3//! A graph node builds its index (the CSR topology and the id map) from the
4//! rows of its edge plan when it executes. The cache keeps built indexes for
5//! the session, keyed by what the edges are:
6//!
7//! - **the edge plan's fingerprint**: the optimized logical plan under the
8//!   node, rendered with its schema, plus, for each file table it scans, the
9//!   table's paths and the options that change what is read (format, CSV
10//!   parsing options, partition columns, declared order: two CSV tables over
11//!   one file with different delimiters render alike but read differently).
12//!   Writer options, statistics and partitioning settings are left out, and
13//!   so is DataFusion's `Debug` text of the options, so an unrelated default
14//!   or a DataFusion upgrade does not change it (#327). A file named in
15//!   `FROM` is a table named by its path as written; in the plan its name is
16//!   replaced by its place among the scans, as its paths say what it reads;
17//! - **the identity of every file the plan reads**: its location, size,
18//!   modification time and e-tag, from the object store's metadata when the
19//!   node executes (a `HEAD` per file, not DataFusion's listing cache, which
20//!   can be stale);
21//! - for a graph with a vertex table, whose keys are its nodes (#311), **the
22//!   keys' plan's fingerprint and the identity of the files it reads** too,
23//!   so a change to the vertex table builds afresh.
24//!
25//! A local file's location is its path (`/a/b.csv`). In a session with a
26//! database, the key is **portable**: every path inside the database's
27//! directory, in the fingerprint and the file identities, is written relative
28//! to it (behind a marker, [`DATABASE_DIR`]), as the catalog stores such paths
29//! (#253), so a database directory moved together with its data still finds
30//! its stored indexes. Paths outside it stay absolute.
31//!
32//! Rewriting a file changes its identity, so the next query builds afresh.
33//! An edge plan that reads anything other than files, literal rows or nothing
34//! (an in-memory table, which `INSERT` can change, or a volatile function such
35//! as `random()`) has no stable identity and is never cached.
36//!
37//! Concurrent requests for one key wait on one build, so several algorithms
38//! over one graph in one query share one index even when DataFusion runs
39//! their nodes at the same time.
40//!
41//! In a session with a `.ursa` database, a miss here looks in the database's
42//! stored indexes under the same full key before building
43//! ([`IndexCache::get_or_build_stored`]), and an index built in a writable
44//! session is stored there (`crate::database::index_store`). Loads from disk
45//! are counted apart from builds ([`index_loads`], [`index_builds`]).
46//! Evaluated weights are kept on the index in memory, and stored with it in
47//! the database (`crate::database::index_store`), so a weighted query over a
48//! stored index in a later process reads no edge rows.
49
50use std::collections::HashMap;
51use std::fmt::{self, Write as _};
52use std::path::{Path, PathBuf};
53use std::sync::atomic::{AtomicU64, Ordering};
54use std::sync::{Arc, Mutex, OnceLock};
55use std::time::{Duration, Instant};
56
57use datafusion::arrow::buffer::BooleanBuffer;
58use datafusion::catalog::default_table_source::source_as_provider;
59use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
60use datafusion::datasource::file_format::arrow::ArrowFormat;
61use datafusion::datasource::file_format::csv::CsvFormat;
62use datafusion::datasource::file_format::json::JsonFormat;
63use datafusion::datasource::file_format::parquet::ParquetFormat;
64use datafusion::datasource::file_format::FileFormat as DataFusionFileFormat;
65use datafusion::datasource::listing::ListingTable;
66use datafusion::datasource::physical_plan::FileScanConfig;
67use datafusion::datasource::source::DataSourceExec;
68use datafusion::error::Result;
69use datafusion::execution::TaskContext;
70use datafusion::logical_expr::LogicalPlan;
71use datafusion::physical_plan::ExecutionPlan;
72use datafusion::prelude::{SessionConfig, SessionContext};
73use futures::future::BoxFuture;
74use object_store::ObjectStoreExt;
75use ursa_core::{IdMap, Topology};
76
77use crate::database::mapped::Unverified;
78use crate::database::{database_of_config, IndexKey, IndexStore};
79use crate::notices::{self, NoticeLevel, Notifier};
80
81/// A built graph: its topology, and the map from dense node indexes back to
82/// the edges' ids.
83///
84/// A graph with a vertex table has the vertex table's keys as its nodes, in
85/// the table's order, and only the edges whose endpoints are both keys (see
86/// `ursa_core::EdgeInterner`): its edge ids number the edges kept, and
87/// [`Self::edge_row`] maps them back to rows of the edge table.
88#[derive(Debug)]
89pub struct GraphIndex {
90    pub topology: Arc<Topology>,
91    pub ids: Arc<IdMap>,
92    /// Edge rows dropped because an endpoint is not a node.
93    n_dropped: u64,
94    /// Which edge rows were kept, one bit per row of the edge plan, when any
95    /// was dropped.
96    kept: Option<BooleanBuffer>,
97    /// Per edge id, its row in the edge plan, when any row was dropped.
98    rows: OnceLock<Vec<u64>>,
99    /// Weights evaluated over the edge rows this index was built from.
100    weights: WeightCache,
101    /// Weights stored with the index on disk, read on first use.
102    stored: Option<StoredWeights>,
103    /// The checksums of a memory-mapped stored index not checked yet
104    /// (`crate::database::mapped`).
105    unverified: Option<Arc<Unverified>>,
106}
107
108/// Reads the weight columns stored under a key, one `f64` per edge row each
109/// (blocking: it reads a file). `None` if they cannot be read.
110pub type WeightReader = Box<dyn Fn(&str) -> Option<Vec<Vec<f64>>> + Send + Sync>;
111
112/// The weights stored with an index on disk: their keys, and how to read them.
113struct StoredWeights {
114    keys: Vec<String>,
115    read: WeightReader,
116}
117
118impl fmt::Debug for StoredWeights {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        write!(f, "StoredWeights({} sets)", self.keys.len())
121    }
122}
123
124impl GraphIndex {
125    pub fn new(topology: Arc<Topology>, ids: Arc<IdMap>) -> Self {
126        Self {
127            topology,
128            ids,
129            n_dropped: 0,
130            kept: None,
131            rows: OnceLock::new(),
132            weights: WeightCache::default(),
133            stored: None,
134            unverified: None,
135        }
136    }
137
138    /// This index, read from a memory-mapped file whose checksums
139    /// `unverified` has not checked yet.
140    pub fn with_unverified(mut self, unverified: Option<Arc<Unverified>>) -> Self {
141        self.unverified = unverified;
142        self
143    }
144
145    /// Check the checksums of the stored index this was mapped from that
146    /// were deferred (its edge arrays, and its in-adjacency once read), before
147    /// something reads it whole: a whole-graph algorithm. Nothing to do for an
148    /// index built in this process or read whole. `Err` says what is damaged.
149    /// Blocking: it reads the arrays.
150    pub fn verify_stored(&self) -> std::result::Result<(), String> {
151        self.unverified.as_ref().map_or(Ok(()), |u| u.verify())
152    }
153
154    /// Whether a checksum of the stored index this was mapped from has been
155    /// found not to match: it is not used again.
156    pub fn is_damaged(&self) -> bool {
157        self.unverified.as_ref().is_some_and(|u| u.is_damaged())
158    }
159
160    /// This index, built from edge rows of which `kept` says which were kept
161    /// (`None`: all of them), `n_dropped` having been dropped.
162    pub fn with_dropped(mut self, n_dropped: u64, kept: Option<BooleanBuffer>) -> Self {
163        self.n_dropped = n_dropped;
164        self.kept = kept.filter(|_| n_dropped > 0);
165        self
166    }
167
168    /// Edge rows dropped because an endpoint is not a node of the graph's
169    /// vertex table.
170    pub fn n_dropped(&self) -> u64 {
171        self.n_dropped
172    }
173
174    /// Which rows of the edge plan were kept, one bit per row, if any was
175    /// dropped.
176    pub fn kept_rows(&self) -> Option<&BooleanBuffer> {
177        self.kept.as_ref()
178    }
179
180    /// The row of the edge plan edge `edge` was read from: the edge id itself
181    /// when no row was dropped.
182    pub fn edge_row(&self, edge: u32) -> u64 {
183        match &self.kept {
184            None => u64::from(edge),
185            Some(kept) => self
186                .rows
187                .get_or_init(|| kept.set_indices().map(|i| i as u64).collect())[edge as usize],
188        }
189    }
190
191    /// This index, with the weight sets stored on disk under `keys`, which
192    /// `read` reads when one is first asked for.
193    pub fn with_stored_weights(mut self, keys: Vec<String>, read: WeightReader) -> Self {
194        if !keys.is_empty() {
195            self.stored = Some(StoredWeights { keys, read });
196        }
197        self
198    }
199
200    /// The weight columns stored under `key` in memory, if they are.
201    pub fn weights(&self, key: &str) -> Option<Weights> {
202        self.weights.get(key)
203    }
204
205    /// Whether weights are stored under `key` on disk.
206    pub fn has_stored_weights(&self, key: &str) -> bool {
207        self.stored
208            .as_ref()
209            .is_some_and(|s| s.keys.iter().any(|k| k == key))
210    }
211
212    /// The weight columns stored under `key`, in memory or else on disk, if
213    /// they are and have `n_columns` columns of one value per edge row. Read
214    /// from disk, they are kept in memory too. Blocking: it may read a file.
215    pub fn stored_weights(&self, key: &str, n_columns: usize) -> Option<Weights> {
216        if let Some(weights) = self.weights(key) {
217            return Some(weights);
218        }
219        if !self.has_stored_weights(key) {
220            return None;
221        }
222        let columns = (self.stored.as_ref()?.read)(key)?;
223        let n_edges = self.topology.n_edges();
224        if columns.len() != n_columns || columns.iter().any(|c| c.len() != n_edges) {
225            return None;
226        }
227        let weights: Weights = Arc::new(columns.into_iter().map(Arc::new).collect());
228        self.store_weights(key.to_string(), Arc::clone(&weights));
229        Some(weights)
230    }
231
232    /// Every set of weight columns held in memory, with its key.
233    pub fn weight_sets(&self) -> Vec<(String, Weights)> {
234        self.weights.all()
235    }
236
237    /// Store weight columns under `key`. They must be one per edge row of this
238    /// index, in its edge-row order.
239    pub fn store_weights(&self, key: String, weights: Weights) {
240        self.weights.put(key, weights)
241    }
242}
243
244/// Weight columns, one `f64` per edge row each, in the order of a node's
245/// weight expressions.
246pub type Weights = Arc<Vec<Arc<Vec<f64>>>>;
247
248/// How many sets of weight columns an index keeps. Each column is one `f64`
249/// per edge (80 MB at 10M edges), so the bound is small, as in ursa-plan's
250/// `WeightCache`: enough for a few weightings alternating over one graph.
251const WEIGHT_CAPACITY: usize = 4;
252
253/// Evaluated weights, held on the index so they live exactly as long as the
254/// edge rows they were evaluated over. Keyed by the weighted edge plan's
255/// fingerprint and file identities (see `exec`), most recently used last.
256#[derive(Default)]
257struct WeightCache {
258    entries: Mutex<Vec<(String, Weights)>>,
259}
260
261impl fmt::Debug for WeightCache {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
264        write!(f, "WeightCache({} entries)", entries.len())
265    }
266}
267
268impl WeightCache {
269    fn get(&self, key: &str) -> Option<Weights> {
270        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
271        let i = entries.iter().position(|(k, _)| k == key)?;
272        let entry = entries.remove(i);
273        let weights = Arc::clone(&entry.1);
274        entries.push(entry);
275        Some(weights)
276    }
277
278    fn all(&self) -> Vec<(String, Weights)> {
279        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
280        entries
281            .iter()
282            .map(|(k, w)| (k.clone(), Arc::clone(w)))
283            .collect()
284    }
285
286    fn put(&self, key: String, weights: Weights) {
287        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
288        entries.retain(|(k, _)| *k != key);
289        if entries.len() >= WEIGHT_CAPACITY {
290            entries.remove(0);
291        }
292        entries.push((key, weights));
293    }
294}
295
296/// The identity of one source file, as its store reports it.
297#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
298pub struct FileIdentity {
299    pub store: String,
300    pub location: String,
301    pub size: u64,
302    /// Modification time, in nanoseconds since the epoch.
303    pub modified: i64,
304    pub e_tag: Option<String>,
305}
306
307/// The fingerprint of an edge plan, or `None` if what it reads has no stable
308/// identity (see the module docs).
309pub fn fingerprint(plan: &LogicalPlan) -> Option<String> {
310    let mut rendered = plan.display_indent_schema().to_string();
311    let mut cacheable = true;
312    let mut locations: Vec<String> = Vec::new();
313    let mut scans: Vec<(String, String)> = Vec::new();
314    let _ = plan.apply_with_subqueries(|node| {
315        if node.expressions().iter().any(|e| e.is_volatile()) {
316            cacheable = false;
317            return Ok(TreeNodeRecursion::Stop);
318        }
319        if let LogicalPlan::TableScan(scan) = node {
320            let listing = source_as_provider(&scan.source)
321                .ok()
322                .and_then(|p| p.downcast_ref::<ListingTable>().map(listing_key));
323            match listing {
324                Some(listing) => {
325                    let name = scan.table_name.to_string();
326                    scans.push((name.clone(), listing));
327                    if crate::paths::looks_like_location(&name) && !locations.contains(&name) {
328                        locations.push(name);
329                    }
330                }
331                None => {
332                    cacheable = false;
333                    return Ok(TreeNodeRecursion::Stop);
334                }
335            }
336        }
337        Ok(TreeNodeRecursion::Continue)
338    });
339    if !cacheable {
340        return None;
341    }
342    // A file named in `FROM` is a table named by its path as written:
343    // relative to the current directory in the statement that defined it,
344    // absolute when a database replays it. What it reads is its paths, listed
345    // after the plan, so in the plan its name is replaced by its place among
346    // the scans (longest name first, as a name may be part of another).
347    let placeholder = |name: &str| {
348        locations
349            .iter()
350            .position(|l| l == name)
351            .map(|i| format!("\u{0}file {i}\u{0}"))
352    };
353    let mut by_length: Vec<&String> = locations.iter().collect();
354    by_length.sort_by_key(|name| std::cmp::Reverse(name.len()));
355    for name in by_length {
356        if let Some(placeholder) = placeholder(name) {
357            rendered = rendered.replace(name.as_str(), &placeholder);
358        }
359    }
360    for (name, listing) in &scans {
361        let name = placeholder(name).unwrap_or_else(|| name.clone());
362        let _ = write!(rendered, "\n{name}: {listing}");
363    }
364    Some(rendered)
365}
366
367/// What a file table reads, for the fingerprint: its paths, and only the
368/// options that change which rows and values are read (the format and its
369/// parsing options, partition columns, declared order). Writer options,
370/// statistics and partitioning settings, and DataFusion's `Debug` text of
371/// them, are left out, so an unrelated default or a DataFusion upgrade does
372/// not change the key (#327).
373fn listing_key(table: &ListingTable) -> String {
374    let paths: Vec<String> = table.table_paths().iter().map(|p| p.to_string()).collect();
375    let options = table.options();
376    let partitions: Vec<String> = options
377        .table_partition_cols
378        .iter()
379        .map(|(name, data_type)| format!("{name} {data_type}"))
380        .collect();
381    let order: Vec<String> = options
382        .file_sort_order
383        .iter()
384        .map(|exprs| {
385            exprs
386                .iter()
387                .map(ToString::to_string)
388                .collect::<Vec<_>>()
389                .join(", ")
390        })
391        .collect();
392    format!(
393        "paths {paths:?}; extension {:?}; {}; partitions {partitions:?}; order {order:?}",
394        options.file_extension,
395        format_key(options.format.as_ref())
396    )
397}
398
399/// A file format and the options of it that change what is read.
400fn format_key(format: &dyn DataFusionFileFormat) -> String {
401    if let Some(csv) = format.downcast_ref::<CsvFormat>() {
402        let o = csv.options();
403        return format!(
404            "csv (header {:?}, delimiter {}, quote {}, terminator {:?}, escape {:?}, \
405             double_quote {:?}, comment {:?}, null_regex {:?}, null_value {:?}, \
406             truncated_rows {:?}, compression {:?}, formats {:?})",
407            o.has_header,
408            o.delimiter,
409            o.quote,
410            o.terminator,
411            o.escape,
412            o.double_quote,
413            o.comment,
414            o.null_regex,
415            o.null_value,
416            o.truncated_rows,
417            o.compression,
418            [
419                &o.date_format,
420                &o.datetime_format,
421                &o.timestamp_format,
422                &o.timestamp_tz_format,
423                &o.time_format
424            ],
425        );
426    }
427    if let Some(json) = format.downcast_ref::<JsonFormat>() {
428        let o = json.options();
429        return format!(
430            "json (newline_delimited {}, compression {:?})",
431            o.newline_delimited, o.compression
432        );
433    }
434    if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
435        let o = &parquet.options().global;
436        return format!(
437            "parquet (binary_as_string {}, schema_force_view_types {}, coerce_int96 {:?} {:?})",
438            o.binary_as_string, o.schema_force_view_types, o.coerce_int96, o.coerce_int96_tz
439        );
440    }
441    if format.downcast_ref::<ArrowFormat>().is_some() {
442        return "arrow".to_string();
443    }
444    // A format Ursa does not know: all of it, to be safe.
445    format!("{} {format:?}", format.get_ext())
446}
447
448/// What a path inside the database's directory becomes in a stored key: the
449/// directory is replaced by this marker, so a database moved together with
450/// its data keeps its keys (#327). The NUL characters keep it from meeting
451/// anything a path or a literal in a plan would hold.
452pub(crate) const DATABASE_DIR: &str = "\u{0}database\u{0}";
453
454/// The forms the absolute directory `dir` takes in a plan's text and in
455/// object store locations, longest first: `file:///a/b/`, `/a/b/`. Its
456/// canonical form too, if it differs (a symlinked temporary directory).
457/// Empty for the root directory, whose every path would match.
458fn dir_forms(dir: &Path) -> Vec<String> {
459    let mut forms = Vec::new();
460    let canonical = std::fs::canonicalize(dir).ok();
461    for dir in std::iter::once(dir).chain(canonical.as_deref()) {
462        let text = dir.to_string_lossy().replace('\\', "/");
463        let text = text.trim_end_matches('/');
464        if text.is_empty() {
465            continue;
466        }
467        let url = match text.strip_prefix('/') {
468            Some(rest) => format!("file:///{rest}/"),
469            None => format!("file:///{text}/"),
470        };
471        for form in [url, format!("{text}/")] {
472            if !forms.contains(&form) {
473                forms.push(form);
474            }
475        }
476    }
477    forms.sort_by_key(|f| std::cmp::Reverse(f.len()));
478    forms
479}
480
481/// `text` (a fingerprint or a location) with every path inside `dir` made
482/// relative to it, behind [`DATABASE_DIR`].
483pub(crate) fn portable(text: &str, dir: &Path) -> String {
484    let mut text = text.to_string();
485    for form in dir_forms(dir) {
486        text = text.replace(&form, &format!("{DATABASE_DIR}/"));
487    }
488    text
489}
490
491/// [`portable`] against the directory of the database of the session
492/// `config` belongs to; `text` as it is without one.
493pub(crate) fn portable_in(text: &str, config: &SessionConfig) -> String {
494    match database_of_config(config) {
495        Some(db) => portable(text, db.dir()),
496        None => text.to_string(),
497    }
498}
499
500/// A local file's path from its object store location, as the user wrote
501/// it: `/a/b.csv`, not `a/b.csv` (#327, N14).
502fn local_path(location: &str) -> String {
503    if cfg!(windows) || location.starts_with('/') {
504        location.to_string()
505    } else {
506        format!("/{location}")
507    }
508}
509
510/// The identity of every file `plan` reads, sorted, looked up in the object
511/// store now.
512pub async fn file_identities(
513    plan: &Arc<dyn ExecutionPlan>,
514    context: &TaskContext,
515) -> Result<Vec<FileIdentity>> {
516    let mut files = Vec::new();
517    let _ = plan.apply(|node| {
518        if let Some(config) = node
519            .downcast_ref::<DataSourceExec>()
520            .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
521        {
522            for group in &config.file_groups {
523                for file in group.files() {
524                    files.push((
525                        config.object_store_url.clone(),
526                        file.object_meta.location.clone(),
527                    ));
528                }
529            }
530        }
531        Ok(TreeNodeRecursion::Continue)
532    });
533    files.sort();
534    files.dedup();
535    let database = database_of_config(context.session_config());
536    let mut identities = Vec::with_capacity(files.len());
537    for (url, location) in files {
538        let store = context.runtime_env().object_store(&url)?;
539        let meta = store.head(&location).await?;
540        let store = url.to_string();
541        // A local file by its path, inside a database's directory relative
542        // to it, so the key survives moving the two together.
543        let location = if store == LOCAL_STORE {
544            let path = local_path(location.as_ref());
545            match &database {
546                Some(db) => portable(&path, db.dir()),
547                None => path,
548            }
549        } else {
550            location.to_string()
551        };
552        identities.push(FileIdentity {
553            store,
554            location,
555            size: meta.size,
556            modified: meta.last_modified.timestamp_nanos_opt().unwrap_or(i64::MAX),
557            e_tag: meta.e_tag,
558        });
559    }
560    identities.sort();
561    Ok(identities)
562}
563
564/// The object store URL of the local file system.
565const LOCAL_STORE: &str = "file:///";
566
567/// How many fingerprints the cache keeps. A newer identity of a fingerprint
568/// replaces the older one, so this bounds the number of distinct edge plans.
569const CAPACITY: usize = 16;
570
571/// The session's graph indexes (a session config extension).
572#[derive(Debug, Default)]
573pub struct IndexCache {
574    slots: Mutex<HashMap<String, Slot>>,
575    /// Bumped on every use, to find the least recently used slot.
576    clock: AtomicU64,
577    builds: AtomicU64,
578    loads: AtomicU64,
579}
580
581#[derive(Debug)]
582struct Slot {
583    files: Vec<FileIdentity>,
584    cell: Arc<tokio::sync::OnceCell<Arc<GraphIndex>>>,
585    used: u64,
586}
587
588impl IndexCache {
589    /// How many indexes this cache has built.
590    pub fn builds(&self) -> u64 {
591        self.builds.load(Ordering::Relaxed)
592    }
593
594    /// How many indexes this cache has loaded from the database's stored
595    /// indexes instead of building them.
596    pub fn loads(&self) -> u64 {
597        self.loads.load(Ordering::Relaxed)
598    }
599
600    /// Count a build made outside the cache (an index that cannot be shared).
601    pub fn record_build(&self) {
602        self.builds.fetch_add(1, Ordering::Relaxed);
603    }
604
605    /// Uncount a load whose index turned out damaged (a checksum checked
606    /// after it loaded, see `crate::database::mapped`): it is built instead.
607    pub fn record_damaged_load(&self) {
608        let _ = self
609            .loads
610            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
611    }
612
613    /// The index for `key`, if it is built and cached; nothing is built.
614    pub fn get(&self, key: &(String, Vec<FileIdentity>)) -> Option<Arc<GraphIndex>> {
615        let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
616        let slot = slots.get_mut(&key.0).filter(|s| s.files == key.1)?;
617        let index = slot.cell.get().filter(|i| !i.is_damaged()).cloned()?;
618        slot.used = self.clock.fetch_add(1, Ordering::Relaxed);
619        Some(index)
620    }
621
622    /// Where the index for `key` is kept, if it is: in this cache, or stored
623    /// in the database of the session `config` belongs to. Nothing is built
624    /// or loaded (for `EXPLAIN`, #351).
625    pub fn holds(
626        &self,
627        config: &SessionConfig,
628        key: &(String, Vec<FileIdentity>),
629    ) -> Option<IndexHeld> {
630        let cached = {
631            let slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
632            slots
633                .get(&key.0)
634                .filter(|s| s.files == key.1)
635                .is_some_and(|s| s.cell.get().is_some_and(|i| !i.is_damaged()))
636        };
637        if cached {
638            return Some(IndexHeld::Cached);
639        }
640        let db = database_of_config(config)?;
641        let stored = IndexKey::new(portable(&key.0, db.dir()), key.1.clone());
642        db.index_store()
643            .contains(&stored)
644            .then_some(IndexHeld::Stored)
645    }
646
647    /// The index for `key` (a fingerprint and file identities), built by
648    /// `build` if it is not cached. With no fingerprint, always built. The
649    /// database's stored indexes are not consulted: see
650    /// [`Self::get_or_build_stored`].
651    pub async fn get_or_build(
652        &self,
653        key: Option<(String, Vec<FileIdentity>)>,
654        build: BoxFuture<'_, Result<GraphIndex>>,
655    ) -> Result<Arc<GraphIndex>> {
656        self.get_or_build_in(None, &Notifier::silent(), &BuildInfo::default(), key, build)
657            .await
658    }
659
660    /// As [`Self::get_or_build`], and on a miss, the index stored under the
661    /// same full key in the database of the session `config` belongs to, if
662    /// it has one. An index built in a writable database is stored there, in
663    /// the background, within the session's `ursa.index_storage_limit`.
664    pub async fn get_or_build_stored(
665        &self,
666        config: &SessionConfig,
667        key: Option<(String, Vec<FileIdentity>)>,
668        build: BoxFuture<'_, Result<GraphIndex>>,
669    ) -> Result<Arc<GraphIndex>> {
670        self.get_or_build_for(config, key, &BuildInfo::default(), build)
671            .await
672    }
673
674    /// As [`Self::get_or_build_stored`], with notices about the build
675    /// (`crate::notices`) naming the graph in `info`.
676    pub async fn get_or_build_for(
677        &self,
678        config: &SessionConfig,
679        key: Option<(String, Vec<FileIdentity>)>,
680        info: &BuildInfo,
681        build: BoxFuture<'_, Result<GraphIndex>>,
682    ) -> Result<Arc<GraphIndex>> {
683        let stored = database_of_config(config).map(|db| {
684            // The session's limit: what it SET, or the database's default.
685            db.use_index_storage_limit(config);
686            (db.index_store(), db.dir().to_path_buf())
687        });
688        let notifier = Notifier::of(config);
689        self.get_or_build_in(stored, &notifier, info, key, build)
690            .await
691    }
692
693    async fn get_or_build_in(
694        &self,
695        stored: Option<(Arc<IndexStore>, PathBuf)>,
696        notifier: &Notifier,
697        info: &BuildInfo,
698        key: Option<(String, Vec<FileIdentity>)>,
699        build: BoxFuture<'_, Result<GraphIndex>>,
700    ) -> Result<Arc<GraphIndex>> {
701        let Some((fingerprint, files)) = key else {
702            self.builds.fetch_add(1, Ordering::Relaxed);
703            return build_noticed(notifier, info, build, Kept::Never).await;
704        };
705        // The stored key is portable: paths inside the database's directory
706        // relative to it (the file identities already are).
707        let stored = stored.map(|(store, dir)| {
708            (
709                store,
710                IndexKey::new(portable(&fingerprint, &dir), files.clone()),
711            )
712        });
713        let cell = {
714            let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
715            let used = self.clock.fetch_add(1, Ordering::Relaxed);
716            match slots.get_mut(&fingerprint) {
717                // A stored index found damaged is built again.
718                Some(slot)
719                    if slot.files == files && !slot.cell.get().is_some_and(|i| i.is_damaged()) =>
720                {
721                    slot.used = used;
722                    Arc::clone(&slot.cell)
723                }
724                _ => {
725                    if !slots.contains_key(&fingerprint) && slots.len() >= CAPACITY {
726                        if let Some(oldest) = slots
727                            .iter()
728                            .min_by_key(|(_, s)| s.used)
729                            .map(|(k, _)| k.clone())
730                        {
731                            slots.remove(&oldest);
732                        }
733                    }
734                    let cell = Arc::new(tokio::sync::OnceCell::new());
735                    slots.insert(
736                        fingerprint,
737                        Slot {
738                            files,
739                            cell: Arc::clone(&cell),
740                            used,
741                        },
742                    );
743                    cell
744                }
745            }
746        };
747        // A failed build leaves the cell empty, so the next query tries again.
748        let (builds, loads) = (&self.builds, &self.loads);
749        cell.get_or_try_init(|| async move {
750            if let Some((store, key)) = &stored {
751                let (store, key) = (Arc::clone(store), key.clone());
752                let started = clock(notifier, NoticeLevel::All);
753                let reader = notifier.clone();
754                // Reading a file and checking it is blocking work.
755                let loaded = crate::run_blocking(move || {
756                    let loaded = IndexStore::load(&store, &key, &reader);
757                    loaded.map(|(index, size)| (index, size, store))
758                })
759                .await
760                .ok()
761                .flatten();
762                if let Some((index, size, store)) = loaded {
763                    loads.fetch_add(1, Ordering::Relaxed);
764                    notifier.say(NoticeLevel::All, || {
765                        format!(
766                            "loaded the index for {} ({} edges) from {} ({}){}",
767                            info.graph(),
768                            notices::count(index.topology.n_edges() as u64),
769                            store.database(),
770                            notices::size(size),
771                            took(started)
772                        )
773                    });
774                    return Ok(index);
775                }
776            }
777            builds.fetch_add(1, Ordering::Relaxed);
778            let kept = match &stored {
779                Some((store, key)) => Kept::Stored(Arc::clone(store), key.clone()),
780                None => Kept::InMemory,
781            };
782            build_noticed(notifier, info, build, kept).await
783        })
784        .await
785        .cloned()
786    }
787}
788
789/// Where a session keeps an index ([`IndexCache::holds`]).
790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791pub enum IndexHeld {
792    /// Built or loaded in this session.
793    Cached,
794    /// Stored in the session's database.
795    Stored,
796}
797
798impl fmt::Display for IndexHeld {
799    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
800        f.write_str(match self {
801            IndexHeld::Cached => "cached",
802            IndexHeld::Stored => "stored",
803        })
804    }
805}
806
807/// What a build is for, as notices describe it.
808#[derive(Debug, Clone, Default)]
809pub struct BuildInfo {
810    /// The graph, as the query names it.
811    pub graph: Option<String>,
812    /// How much the build reads, if the plan's statistics say.
813    pub size: Option<BuildSize>,
814}
815
816/// How much a build reads, as its first notice says it.
817#[derive(Debug, Clone, Copy, PartialEq, Eq)]
818pub enum BuildSize {
819    /// About this many edge rows, or exactly this many if the flag is set.
820    Edges(u64, bool),
821    /// About this many rows, read from scans whose filter the statistics
822    /// cannot settle: how many edges they give is not known.
823    Reads(u64),
824}
825
826impl BuildInfo {
827    fn graph(&self) -> &str {
828        self.graph.as_deref().unwrap_or("a graph")
829    }
830
831    /// The notice that announces the build: `building the index for g
832    /// (95.7M edges)…`, or `reading about 2.4B rows to build the index for
833    /// g…` when only the rows read are known.
834    fn announcement(&self) -> String {
835        let graph = self.graph();
836        match self.size {
837            Some(BuildSize::Edges(n, true)) if n > 0 => {
838                format!(
839                    "building the index for {graph} ({} edges)…",
840                    notices::count(n)
841                )
842            }
843            Some(BuildSize::Edges(n, false)) if n > 0 => format!(
844                "building the index for {graph} (about {} edges)…",
845                notices::count(n)
846            ),
847            Some(BuildSize::Reads(n)) if n > 0 => format!(
848                "reading about {} rows to build the index for {graph}…",
849                notices::count(n)
850            ),
851            _ => format!("building the index for {graph}…"),
852        }
853    }
854}
855
856/// Where a built index is kept, for its notice.
857enum Kept {
858    /// In the session's cache, and the database's stored indexes under this
859    /// key.
860    Stored(Arc<IndexStore>, IndexKey),
861    /// In the session's cache only: the session has no database.
862    InMemory,
863    /// Nowhere: what its edges read has no stable identity.
864    Never,
865}
866
867/// Now, if notices at `level` are said (the browser has no clock to read
868/// otherwise).
869fn clock(notifier: &Notifier, level: NoticeLevel) -> Option<Instant> {
870    (notifier.level() >= level).then(Instant::now)
871}
872
873/// ` in 30.7 s`, since `started`, if it was read.
874fn took(started: Option<Instant>) -> String {
875    started
876        .map(|s| format!(" in {}", notices::duration(s.elapsed())))
877        .unwrap_or_default()
878}
879
880/// Run `build`, announcing it once it has run for a second (at once at
881/// `ursa.notices = all`), then keep the index as `kept` says (storing it in
882/// the database), and say what became of it: always at `all`, and at `on` if
883/// the build was announced or the index could not be stored (see
884/// `crate::notices`).
885async fn build_noticed(
886    notifier: &Notifier,
887    info: &BuildInfo,
888    build: BoxFuture<'_, Result<GraphIndex>>,
889    kept: Kept,
890) -> Result<Arc<GraphIndex>> {
891    let started = clock(notifier, NoticeLevel::On);
892    let delay = match notifier.level() {
893        NoticeLevel::All => Duration::ZERO,
894        _ => notices::BUILD_NOTICE_AFTER,
895    };
896    let announcement = notifier.announce_after(delay, info.announcement());
897    let built = build.await;
898    let announced = announcement.finish();
899    let index = Arc::new(built?);
900    let (outcome, loses_work) = match kept {
901        Kept::Stored(store, key) => {
902            let saved = store.save(key, Arc::clone(&index), info.graph(), notifier);
903            (
904                format!("; {}", saved.describe(store.database())),
905                saved.loses_work(),
906            )
907        }
908        Kept::InMemory => (
909            "; kept for this session only (open a .ursa database to store it)".to_string(),
910            false,
911        ),
912        Kept::Never => (
913            "; not kept: what its edges read can change (an in-memory table, or a volatile \
914             function such as random())"
915                .to_string(),
916            false,
917        ),
918    };
919    let level = if announced || loses_work {
920        NoticeLevel::On
921    } else {
922        NoticeLevel::All
923    };
924    notifier.say(level, || {
925        format!(
926            "built the index for {} ({} edges){}{outcome}",
927            info.graph(),
928            notices::count(index.topology.n_edges() as u64),
929            took(started)
930        )
931    });
932    Ok(index)
933}
934
935/// Install an empty index cache on `config`.
936pub(crate) fn with_index_cache(config: SessionConfig) -> SessionConfig {
937    config.with_extension(Arc::new(IndexCache::default()))
938}
939
940/// How many graph indexes `ctx` has built: for tests of the cache.
941pub fn index_builds(ctx: &SessionContext) -> u64 {
942    ctx.state()
943        .config()
944        .get_extension::<IndexCache>()
945        .map(|c| c.builds())
946        .unwrap_or(0)
947}
948
949/// How many graph indexes `ctx` has loaded from its database's stored
950/// indexes instead of building them: for tests of stored indexes.
951pub fn index_loads(ctx: &SessionContext) -> u64 {
952    ctx.state()
953        .config()
954        .get_extension::<IndexCache>()
955        .map(|c| c.loads())
956        .unwrap_or(0)
957}
958
959#[cfg(test)]
960mod tests {
961    use super::*;
962
963    #[test]
964    fn paths_inside_the_database_directory_are_portable() {
965        let dir = Path::new("/home/me/proj");
966        let text =
967            "TableScan: /home/me/proj/edges.csv\npaths [\"file:///home/me/proj/edges.csv\"] \
968                    /home/me/project2/x.csv /home/me/proj";
969        assert_eq!(
970            portable(text, dir),
971            format!(
972                "TableScan: {DATABASE_DIR}/edges.csv\npaths [\"{DATABASE_DIR}/edges.csv\"] \
973                 /home/me/project2/x.csv /home/me/proj"
974            )
975        );
976        // The root directory: nothing is replaced.
977        assert_eq!(portable("/a/b.csv", Path::new("/")), "/a/b.csv");
978        // Moved, the same file has the same portable form.
979        assert_eq!(
980            portable("/home/me/proj/edges.csv", dir),
981            portable("/mnt/elsewhere/edges.csv", Path::new("/mnt/elsewhere/"))
982        );
983    }
984
985    #[test]
986    fn local_locations_keep_their_leading_slash() {
987        #[cfg(not(windows))]
988        assert_eq!(local_path("home/me/a.csv"), "/home/me/a.csv");
989        assert_eq!(local_path("/home/me/a.csv"), "/home/me/a.csv");
990    }
991}