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    // The footer check (#332) changes nothing that is read.
402    if let Some(valid) = format.downcast_ref::<ursa_io::parquet_footer::ValidParquet>() {
403        return format_key(valid.inner().as_ref());
404    }
405    if let Some(csv) = format.downcast_ref::<CsvFormat>() {
406        let o = csv.options();
407        return format!(
408            "csv (header {:?}, delimiter {}, quote {}, terminator {:?}, escape {:?}, \
409             double_quote {:?}, comment {:?}, null_regex {:?}, null_value {:?}, \
410             truncated_rows {:?}, compression {:?}, formats {:?})",
411            o.has_header,
412            o.delimiter,
413            o.quote,
414            o.terminator,
415            o.escape,
416            o.double_quote,
417            o.comment,
418            o.null_regex,
419            o.null_value,
420            o.truncated_rows,
421            o.compression,
422            [
423                &o.date_format,
424                &o.datetime_format,
425                &o.timestamp_format,
426                &o.timestamp_tz_format,
427                &o.time_format
428            ],
429        );
430    }
431    if let Some(json) = format.downcast_ref::<JsonFormat>() {
432        let o = json.options();
433        return format!(
434            "json (newline_delimited {}, compression {:?})",
435            o.newline_delimited, o.compression
436        );
437    }
438    if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
439        let o = &parquet.options().global;
440        return format!(
441            "parquet (binary_as_string {}, schema_force_view_types {}, coerce_int96 {:?} {:?})",
442            o.binary_as_string, o.schema_force_view_types, o.coerce_int96, o.coerce_int96_tz
443        );
444    }
445    if format.downcast_ref::<ArrowFormat>().is_some() {
446        return "arrow".to_string();
447    }
448    // A format Ursa does not know: all of it, to be safe.
449    format!("{} {format:?}", format.get_ext())
450}
451
452/// What a path inside the database's directory becomes in a stored key: the
453/// directory is replaced by this marker, so a database moved together with
454/// its data keeps its keys (#327). The NUL characters keep it from meeting
455/// anything a path or a literal in a plan would hold.
456pub(crate) const DATABASE_DIR: &str = "\u{0}database\u{0}";
457
458/// The forms the absolute directory `dir` takes in a plan's text and in
459/// object store locations, longest first: `file:///a/b/`, `/a/b/`. Its
460/// canonical form too, if it differs (a symlinked temporary directory).
461/// Empty for the root directory, whose every path would match.
462fn dir_forms(dir: &Path) -> Vec<String> {
463    let mut forms = Vec::new();
464    let canonical = std::fs::canonicalize(dir).ok();
465    for dir in std::iter::once(dir).chain(canonical.as_deref()) {
466        let text = dir.to_string_lossy().replace('\\', "/");
467        let text = text.trim_end_matches('/');
468        if text.is_empty() {
469            continue;
470        }
471        let url = match text.strip_prefix('/') {
472            Some(rest) => format!("file:///{rest}/"),
473            None => format!("file:///{text}/"),
474        };
475        for form in [url, format!("{text}/")] {
476            if !forms.contains(&form) {
477                forms.push(form);
478            }
479        }
480    }
481    forms.sort_by_key(|f| std::cmp::Reverse(f.len()));
482    forms
483}
484
485/// `text` (a fingerprint or a location) with every path inside `dir` made
486/// relative to it, behind [`DATABASE_DIR`].
487pub(crate) fn portable(text: &str, dir: &Path) -> String {
488    let mut text = text.to_string();
489    for form in dir_forms(dir) {
490        text = text.replace(&form, &format!("{DATABASE_DIR}/"));
491    }
492    text
493}
494
495/// [`portable`] against the directory of the database of the session
496/// `config` belongs to; `text` as it is without one.
497pub(crate) fn portable_in(text: &str, config: &SessionConfig) -> String {
498    match database_of_config(config) {
499        Some(db) => portable(text, db.dir()),
500        None => text.to_string(),
501    }
502}
503
504/// A local file's path from its object store location, as the user wrote
505/// it: `/a/b.csv`, not `a/b.csv` (#327, N14).
506fn local_path(location: &str) -> String {
507    if cfg!(windows) || location.starts_with('/') {
508        location.to_string()
509    } else {
510        format!("/{location}")
511    }
512}
513
514/// The identity of every file `plan` reads, sorted, looked up in the object
515/// store now.
516pub async fn file_identities(
517    plan: &Arc<dyn ExecutionPlan>,
518    context: &TaskContext,
519) -> Result<Vec<FileIdentity>> {
520    let mut files = Vec::new();
521    let _ = plan.apply(|node| {
522        if let Some(config) = node
523            .downcast_ref::<DataSourceExec>()
524            .and_then(|exec| exec.data_source().downcast_ref::<FileScanConfig>())
525        {
526            for group in &config.file_groups {
527                for file in group.files() {
528                    files.push((
529                        config.object_store_url.clone(),
530                        file.object_meta.location.clone(),
531                    ));
532                }
533            }
534        }
535        Ok(TreeNodeRecursion::Continue)
536    });
537    files.sort();
538    files.dedup();
539    let database = database_of_config(context.session_config());
540    let mut identities = Vec::with_capacity(files.len());
541    for (url, location) in files {
542        let store = context.runtime_env().object_store(&url)?;
543        let meta = store.head(&location).await?;
544        let store = url.to_string();
545        // A local file by its path, inside a database's directory relative
546        // to it, so the key survives moving the two together.
547        let location = if store == LOCAL_STORE {
548            let path = local_path(location.as_ref());
549            match &database {
550                Some(db) => portable(&path, db.dir()),
551                None => path,
552            }
553        } else {
554            location.to_string()
555        };
556        identities.push(FileIdentity {
557            store,
558            location,
559            size: meta.size,
560            modified: meta.last_modified.timestamp_nanos_opt().unwrap_or(i64::MAX),
561            e_tag: meta.e_tag,
562        });
563    }
564    identities.sort();
565    Ok(identities)
566}
567
568/// The object store URL of the local file system.
569const LOCAL_STORE: &str = "file:///";
570
571/// How many fingerprints the cache keeps. A newer identity of a fingerprint
572/// replaces the older one, so this bounds the number of distinct edge plans.
573const CAPACITY: usize = 16;
574
575/// The session's graph indexes (a session config extension).
576#[derive(Debug, Default)]
577pub struct IndexCache {
578    slots: Mutex<HashMap<String, Slot>>,
579    /// Bumped on every use, to find the least recently used slot.
580    clock: AtomicU64,
581    builds: AtomicU64,
582    loads: AtomicU64,
583}
584
585#[derive(Debug)]
586struct Slot {
587    files: Vec<FileIdentity>,
588    cell: Arc<tokio::sync::OnceCell<Arc<GraphIndex>>>,
589    used: u64,
590}
591
592impl IndexCache {
593    /// How many indexes this cache has built.
594    pub fn builds(&self) -> u64 {
595        self.builds.load(Ordering::Relaxed)
596    }
597
598    /// How many indexes this cache has loaded from the database's stored
599    /// indexes instead of building them.
600    pub fn loads(&self) -> u64 {
601        self.loads.load(Ordering::Relaxed)
602    }
603
604    /// Count a build made outside the cache (an index that cannot be shared).
605    pub fn record_build(&self) {
606        self.builds.fetch_add(1, Ordering::Relaxed);
607    }
608
609    /// Uncount a load whose index turned out damaged (a checksum checked
610    /// after it loaded, see `crate::database::mapped`): it is built instead.
611    pub fn record_damaged_load(&self) {
612        let _ = self
613            .loads
614            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1));
615    }
616
617    /// The index for `key`, if it is built and cached; nothing is built.
618    pub fn get(&self, key: &(String, Vec<FileIdentity>)) -> Option<Arc<GraphIndex>> {
619        let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
620        let slot = slots.get_mut(&key.0).filter(|s| s.files == key.1)?;
621        let index = slot.cell.get().filter(|i| !i.is_damaged()).cloned()?;
622        slot.used = self.clock.fetch_add(1, Ordering::Relaxed);
623        Some(index)
624    }
625
626    /// Where the index for `key` is kept, if it is: in this cache, or stored
627    /// in the database of the session `config` belongs to. Nothing is built
628    /// or loaded (for `EXPLAIN`, #351).
629    pub fn holds(
630        &self,
631        config: &SessionConfig,
632        key: &(String, Vec<FileIdentity>),
633    ) -> Option<IndexHeld> {
634        let cached = {
635            let slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
636            slots
637                .get(&key.0)
638                .filter(|s| s.files == key.1)
639                .is_some_and(|s| s.cell.get().is_some_and(|i| !i.is_damaged()))
640        };
641        if cached {
642            return Some(IndexHeld::Cached);
643        }
644        let db = database_of_config(config)?;
645        let stored = IndexKey::new(portable(&key.0, db.dir()), key.1.clone());
646        db.index_store()
647            .contains(&stored)
648            .then_some(IndexHeld::Stored)
649    }
650
651    /// The index for `key` (a fingerprint and file identities), built by
652    /// `build` if it is not cached. With no fingerprint, always built. The
653    /// database's stored indexes are not consulted: see
654    /// [`Self::get_or_build_stored`].
655    pub async fn get_or_build(
656        &self,
657        key: Option<(String, Vec<FileIdentity>)>,
658        build: BoxFuture<'_, Result<GraphIndex>>,
659    ) -> Result<Arc<GraphIndex>> {
660        self.get_or_build_in(None, &Notifier::silent(), &BuildInfo::default(), key, build)
661            .await
662    }
663
664    /// As [`Self::get_or_build`], and on a miss, the index stored under the
665    /// same full key in the database of the session `config` belongs to, if
666    /// it has one. An index built in a writable database is stored there, in
667    /// the background, within the session's `ursa.index_storage_limit`.
668    pub async fn get_or_build_stored(
669        &self,
670        config: &SessionConfig,
671        key: Option<(String, Vec<FileIdentity>)>,
672        build: BoxFuture<'_, Result<GraphIndex>>,
673    ) -> Result<Arc<GraphIndex>> {
674        self.get_or_build_for(config, key, &BuildInfo::default(), build)
675            .await
676    }
677
678    /// As [`Self::get_or_build_stored`], with notices about the build
679    /// (`crate::notices`) naming the graph in `info`.
680    pub async fn get_or_build_for(
681        &self,
682        config: &SessionConfig,
683        key: Option<(String, Vec<FileIdentity>)>,
684        info: &BuildInfo,
685        build: BoxFuture<'_, Result<GraphIndex>>,
686    ) -> Result<Arc<GraphIndex>> {
687        let stored = database_of_config(config).map(|db| {
688            // The session's limit: what it SET, or the database's default.
689            db.use_index_storage_limit(config);
690            (db.index_store(), db.dir().to_path_buf())
691        });
692        let notifier = Notifier::of(config);
693        self.get_or_build_in(stored, &notifier, info, key, build)
694            .await
695    }
696
697    async fn get_or_build_in(
698        &self,
699        stored: Option<(Arc<IndexStore>, PathBuf)>,
700        notifier: &Notifier,
701        info: &BuildInfo,
702        key: Option<(String, Vec<FileIdentity>)>,
703        build: BoxFuture<'_, Result<GraphIndex>>,
704    ) -> Result<Arc<GraphIndex>> {
705        let Some((fingerprint, files)) = key else {
706            self.builds.fetch_add(1, Ordering::Relaxed);
707            return build_noticed(notifier, info, build, Kept::Never).await;
708        };
709        // The stored key is portable: paths inside the database's directory
710        // relative to it (the file identities already are).
711        let stored = stored.map(|(store, dir)| {
712            (
713                store,
714                IndexKey::new(portable(&fingerprint, &dir), files.clone()),
715            )
716        });
717        let cell = {
718            let mut slots = self.slots.lock().unwrap_or_else(|e| e.into_inner());
719            let used = self.clock.fetch_add(1, Ordering::Relaxed);
720            match slots.get_mut(&fingerprint) {
721                // A stored index found damaged is built again.
722                Some(slot)
723                    if slot.files == files && !slot.cell.get().is_some_and(|i| i.is_damaged()) =>
724                {
725                    slot.used = used;
726                    Arc::clone(&slot.cell)
727                }
728                _ => {
729                    if !slots.contains_key(&fingerprint) && slots.len() >= CAPACITY {
730                        if let Some(oldest) = slots
731                            .iter()
732                            .min_by_key(|(_, s)| s.used)
733                            .map(|(k, _)| k.clone())
734                        {
735                            slots.remove(&oldest);
736                        }
737                    }
738                    let cell = Arc::new(tokio::sync::OnceCell::new());
739                    slots.insert(
740                        fingerprint,
741                        Slot {
742                            files,
743                            cell: Arc::clone(&cell),
744                            used,
745                        },
746                    );
747                    cell
748                }
749            }
750        };
751        // A failed build leaves the cell empty, so the next query tries again.
752        let (builds, loads) = (&self.builds, &self.loads);
753        cell.get_or_try_init(|| async move {
754            if let Some((store, key)) = &stored {
755                let (store, key) = (Arc::clone(store), key.clone());
756                let started = clock(notifier, NoticeLevel::All);
757                let reader = notifier.clone();
758                // Reading a file and checking it is blocking work.
759                let loaded = crate::run_blocking(move || {
760                    let loaded = IndexStore::load(&store, &key, &reader);
761                    loaded.map(|(index, size)| (index, size, store))
762                })
763                .await
764                .ok()
765                .flatten();
766                if let Some((index, size, store)) = loaded {
767                    loads.fetch_add(1, Ordering::Relaxed);
768                    notifier.say(NoticeLevel::All, || {
769                        format!(
770                            "loaded the index for {} ({} edges) from {} ({}){}",
771                            info.graph(),
772                            notices::count(index.topology.n_edges() as u64),
773                            store.database(),
774                            notices::size(size),
775                            took(started)
776                        )
777                    });
778                    return Ok(index);
779                }
780            }
781            builds.fetch_add(1, Ordering::Relaxed);
782            let kept = match &stored {
783                Some((store, key)) => Kept::Stored(Arc::clone(store), key.clone()),
784                None => Kept::InMemory,
785            };
786            build_noticed(notifier, info, build, kept).await
787        })
788        .await
789        .cloned()
790    }
791}
792
793/// Where a session keeps an index ([`IndexCache::holds`]).
794#[derive(Debug, Clone, Copy, PartialEq, Eq)]
795pub enum IndexHeld {
796    /// Built or loaded in this session.
797    Cached,
798    /// Stored in the session's database.
799    Stored,
800}
801
802impl fmt::Display for IndexHeld {
803    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
804        f.write_str(match self {
805            IndexHeld::Cached => "cached",
806            IndexHeld::Stored => "stored",
807        })
808    }
809}
810
811/// What a build is for, as notices describe it.
812#[derive(Debug, Clone, Default)]
813pub struct BuildInfo {
814    /// The graph, as the query names it.
815    pub graph: Option<String>,
816    /// How much the build reads, if the plan's statistics say.
817    pub size: Option<BuildSize>,
818}
819
820/// How much a build reads, as its first notice says it.
821#[derive(Debug, Clone, Copy, PartialEq, Eq)]
822pub enum BuildSize {
823    /// About this many edge rows, or exactly this many if the flag is set.
824    Edges(u64, bool),
825    /// About this many rows, read from scans whose filter the statistics
826    /// cannot settle: how many edges they give is not known.
827    Reads(u64),
828}
829
830impl BuildInfo {
831    fn graph(&self) -> &str {
832        self.graph.as_deref().unwrap_or("a graph")
833    }
834
835    /// The notice that announces the build: `building the index for g
836    /// (95.7M edges)…`, or `reading about 2.4B rows to build the index for
837    /// g…` when only the rows read are known.
838    fn announcement(&self) -> String {
839        let graph = self.graph();
840        match self.size {
841            Some(BuildSize::Edges(n, true)) if n > 0 => {
842                format!(
843                    "building the index for {graph} ({} edges)…",
844                    notices::count(n)
845                )
846            }
847            Some(BuildSize::Edges(n, false)) if n > 0 => format!(
848                "building the index for {graph} (about {} edges)…",
849                notices::count(n)
850            ),
851            Some(BuildSize::Reads(n)) if n > 0 => format!(
852                "reading about {} rows to build the index for {graph}…",
853                notices::count(n)
854            ),
855            _ => format!("building the index for {graph}…"),
856        }
857    }
858}
859
860/// Where a built index is kept, for its notice.
861enum Kept {
862    /// In the session's cache, and the database's stored indexes under this
863    /// key.
864    Stored(Arc<IndexStore>, IndexKey),
865    /// In the session's cache only: the session has no database.
866    InMemory,
867    /// Nowhere: what its edges read has no stable identity.
868    Never,
869}
870
871/// Now, if notices at `level` are said (the browser has no clock to read
872/// otherwise).
873fn clock(notifier: &Notifier, level: NoticeLevel) -> Option<Instant> {
874    (notifier.level() >= level).then(Instant::now)
875}
876
877/// ` in 30.7 s`, since `started`, if it was read.
878fn took(started: Option<Instant>) -> String {
879    started
880        .map(|s| format!(" in {}", notices::duration(s.elapsed())))
881        .unwrap_or_default()
882}
883
884/// Run `build`, announcing it once it has run for a second (at once at
885/// `ursa.notices = all`), then keep the index as `kept` says (storing it in
886/// the database), and say what became of it: always at `all`, and at `on` if
887/// the build was announced or the index could not be stored (see
888/// `crate::notices`).
889async fn build_noticed(
890    notifier: &Notifier,
891    info: &BuildInfo,
892    build: BoxFuture<'_, Result<GraphIndex>>,
893    kept: Kept,
894) -> Result<Arc<GraphIndex>> {
895    let started = clock(notifier, NoticeLevel::On);
896    let delay = match notifier.level() {
897        NoticeLevel::All => Duration::ZERO,
898        _ => notices::BUILD_NOTICE_AFTER,
899    };
900    let announcement = notifier.announce_after(delay, info.announcement());
901    let built = build.await;
902    let announced = announcement.finish();
903    let index = Arc::new(built?);
904    let (outcome, loses_work) = match kept {
905        Kept::Stored(store, key) => {
906            let saved = store.save(key, Arc::clone(&index), info.graph(), notifier);
907            (
908                format!("; {}", saved.describe(store.database())),
909                saved.loses_work(),
910            )
911        }
912        Kept::InMemory => (
913            "; kept for this session only (open a .ursa database to store it)".to_string(),
914            false,
915        ),
916        Kept::Never => (
917            "; not kept: what its edges read can change (an in-memory table, or a volatile \
918             function such as random())"
919                .to_string(),
920            false,
921        ),
922    };
923    let level = if announced || loses_work {
924        NoticeLevel::On
925    } else {
926        NoticeLevel::All
927    };
928    notifier.say(level, || {
929        format!(
930            "built the index for {} ({} edges){}{outcome}",
931            info.graph(),
932            notices::count(index.topology.n_edges() as u64),
933            took(started)
934        )
935    });
936    Ok(index)
937}
938
939/// Install an empty index cache on `config`.
940pub(crate) fn with_index_cache(config: SessionConfig) -> SessionConfig {
941    config.with_extension(Arc::new(IndexCache::default()))
942}
943
944/// How many graph indexes `ctx` has built: for tests of the cache.
945pub fn index_builds(ctx: &SessionContext) -> u64 {
946    ctx.state()
947        .config()
948        .get_extension::<IndexCache>()
949        .map(|c| c.builds())
950        .unwrap_or(0)
951}
952
953/// How many graph indexes `ctx` has loaded from its database's stored
954/// indexes instead of building them: for tests of stored indexes.
955pub fn index_loads(ctx: &SessionContext) -> u64 {
956    ctx.state()
957        .config()
958        .get_extension::<IndexCache>()
959        .map(|c| c.loads())
960        .unwrap_or(0)
961}
962
963#[cfg(test)]
964mod tests {
965    use super::*;
966
967    #[test]
968    fn paths_inside_the_database_directory_are_portable() {
969        let dir = Path::new("/home/me/proj");
970        let text =
971            "TableScan: /home/me/proj/edges.csv\npaths [\"file:///home/me/proj/edges.csv\"] \
972                    /home/me/project2/x.csv /home/me/proj";
973        assert_eq!(
974            portable(text, dir),
975            format!(
976                "TableScan: {DATABASE_DIR}/edges.csv\npaths [\"{DATABASE_DIR}/edges.csv\"] \
977                 /home/me/project2/x.csv /home/me/proj"
978            )
979        );
980        // The root directory: nothing is replaced.
981        assert_eq!(portable("/a/b.csv", Path::new("/")), "/a/b.csv");
982        // Moved, the same file has the same portable form.
983        assert_eq!(
984            portable("/home/me/proj/edges.csv", dir),
985            portable("/mnt/elsewhere/edges.csv", Path::new("/mnt/elsewhere/"))
986        );
987    }
988
989    #[test]
990    fn local_locations_keep_their_leading_slash() {
991        #[cfg(not(windows))]
992        assert_eq!(local_path("home/me/a.csv"), "/home/me/a.csv");
993        assert_eq!(local_path("/home/me/a.csv"), "/home/me/a.csv");
994    }
995}