From 8d4e92999f586bcb35f930d845797c85741b1be1 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Sat, 21 Nov 2026 16:14:53 -0500 Subject: [PATCH] feat(csr): load stored CSRs without writing, and report failed writes Add persist_csr="load" (PersistCsr::Load in Rust, persistCsr: "load" in Node): an engine loads a stored CSR when it can and otherwise builds in memory, never writing to its datasets. delete_stored_csr() refuses on such an engine. With storing on, check that _lance_csr takes writes before encoding the file, so read-only storage no longer pays for an encode it can't upload. A failed write is now reported as store_error in csr_stats() and as a Python RuntimeWarning or a Node process warning. Closes #180. --- crates/lance-csr-node/src/engine.rs | 17 +- crates/lance-csr-python/src/graph.rs | 32 +++- crates/lance-csr/src/csr_store.rs | 12 +- crates/lance-csr/src/engine.rs | 150 +++++++++++++++--- crates/lance-csr/src/lib.rs | 4 +- docs/csr.md | 13 +- docs/index.md | 4 +- docs/internals/indexes.md | 3 + docs/rust.md | 8 +- docs/typescript.md | 1 + nodejs/native.d.ts | 3 +- nodejs/src/cypher.ts | 55 +++++-- nodejs/src/types.ts | 5 + nodejs/test/cypher-engine.test.ts | 8 + nodejs/test/lance.test.ts | 46 +++++- nodejs/typedoc/api.md | 12 +- python/python/lance_csr/_internal/graph.pyi | 3 +- python/python/lance_csr/_types.py | 1 + python/python/lance_csr/cypher.py | 57 +++++-- .../python/tests/test_engine_csr_persist.py | 45 +++++- 20 files changed, 400 insertions(+), 79 deletions(-) diff --git a/crates/lance-csr-node/src/engine.rs b/crates/lance-csr-node/src/engine.rs index f8afa4d5..d12a29b1 100644 --- a/crates/lance-csr-node/src/engine.rs +++ b/crates/lance-csr-node/src/engine.rs @@ -6,7 +6,9 @@ use std::sync::Arc; use datafusion::physical_plan::SendableRecordBatchStream; use futures::StreamExt; -use lance_csr::engine::{CypherEngine as RustCypherEngine, EngineOptions, MAX_TARGET_PARTITIONS}; +use lance_csr::engine::{ + CypherEngine as RustCypherEngine, EngineOptions, PersistCsr, MAX_TARGET_PARTITIONS, +}; use lance_csr::SqlEngine as RustSqlEngine; use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer}; use napi_derive::napi; @@ -47,6 +49,7 @@ pub struct CsrStats { pub version: Option, pub base_version: Option, pub build_ms: f64, + pub store_error: Option, } #[napi(object)] @@ -93,9 +96,16 @@ pub async fn open_cypher_engine( datasets_in: HashMap, use_csr: bool, target_partitions: Option, - persist_csr: bool, + // "off", "load" or "store"; the TypeScript facade maps `persistCsr` to these. + persist_csr: String, ) -> napi::Result { - if persist_csr && !use_csr { + let persist_csr = match persist_csr.as_str() { + "off" => PersistCsr::Off, + "load" => PersistCsr::Load, + "store" => PersistCsr::LoadAndStore, + _ => return Err(invalid("persistCsr must be true, false or \"load\"")), + }; + if persist_csr != PersistCsr::Off && !use_csr { return Err(invalid("persistCsr requires useCsr: true")); } let target_partitions = target_partitions @@ -242,6 +252,7 @@ impl CypherEngine { version: entry.version.map(|v| v as i64), base_version: entry.base_version.map(|v| v as i64), build_ms: entry.build_ms, + store_error: entry.store_error, }; (rel_type, stats) }) diff --git a/crates/lance-csr-python/src/graph.rs b/crates/lance-csr-python/src/graph.rs index 3b4cd822..0b9106de 100644 --- a/crates/lance-csr-python/src/graph.rs +++ b/crates/lance-csr-python/src/graph.rs @@ -24,7 +24,10 @@ use arrow_schema::Schema; use futures::StreamExt; use lance_csr::{ ast::{DistanceMetric as RustDistanceMetric, GraphPattern, ReadingClause}, - engine::{CypherEngine as RustCypherEngine, EngineOptions, EngineSource, MAX_TARGET_PARTITIONS}, + engine::{ + CypherEngine as RustCypherEngine, EngineOptions, EngineSource, PersistCsr, + MAX_TARGET_PARTITIONS, + }, CypherQuery as RustCypherQuery, ExecutionStrategy as RustExecutionStrategy, GraphConfig as RustGraphConfig, GraphError as RustGraphError, SqlDialect as RustSqlDialect, SqlEngine as RustSqlEngine, SqlQuery as RustSqlQuery, VectorSearch as RustVectorSearch, @@ -1098,16 +1101,36 @@ pub struct CypherEngine { #[pymethods] impl CypherEngine { #[new] - #[pyo3(signature = (config, datasets, use_csr = false, *, target_partitions = None, persist_csr = false))] + // `persist_csr` is a bool or "load"; None (left out) is False. + #[pyo3( + signature = (config, datasets, use_csr = false, *, target_partitions = None, persist_csr = None), + text_signature = "(config, datasets, use_csr=False, *, target_partitions=None, persist_csr=False)" + )] fn new( py: Python, config: &GraphConfig, datasets: &Bound<'_, PyDict>, use_csr: bool, target_partitions: Option<&Bound<'_, PyAny>>, - persist_csr: bool, + persist_csr: Option<&Bound<'_, PyAny>>, ) -> PyResult { - if persist_csr && !use_csr { + let persist_csr = match persist_csr { + None => PersistCsr::Off, + Some(value) if value.is_instance_of::() => { + if value.extract::()? { + PersistCsr::LoadAndStore + } else { + PersistCsr::Off + } + } + Some(value) if value.extract::<&str>().is_ok_and(|v| v == "load") => PersistCsr::Load, + Some(_) => { + return Err(PyValueError::new_err( + "persist_csr must be True, False or \"load\"", + )) + } + }; + if persist_csr != PersistCsr::Off && !use_csr { return Err(PyValueError::new_err("persist_csr requires use_csr=True")); } let target_partitions = target_partitions @@ -1248,6 +1271,7 @@ impl CypherEngine { item.set_item("version", entry.version)?; item.set_item("base_version", entry.base_version)?; item.set_item("build_ms", entry.build_ms)?; + item.set_item("store_error", entry.store_error)?; stats.set_item(rel_type, item)?; } Ok(stats.into_any().unbind()) diff --git a/crates/lance-csr/src/csr_store.rs b/crates/lance-csr/src/csr_store.rs index 9f305701..55e906f4 100644 --- a/crates/lance-csr/src/csr_store.rs +++ b/crates/lance-csr/src/csr_store.rs @@ -145,12 +145,20 @@ pub(crate) async fn save( .into_iter() .map(|f| f.metadata().clone()) .collect(); - let bytes = encode(version, src, dst, &fields, &fragments, outgoing, incoming)?; - let store = ds .object_store(None) .await .map_err(|e| store_error(format!("Lance: {e}")))?; + // Encoding takes seconds on large graphs: find out first that the folder takes writes + // (read-only storage or credentials fail here). A probe left behind is never listed. + let probe = dir(ds).join(".write-probe"); + store + .put(&probe, &[]) + .await + .map_err(|e| store_error(format!("Failed to write {probe}: {e}")))?; + let _ = store.delete(&probe).await; + let bytes = encode(version, src, dst, &fields, &fragments, outgoing, incoming)?; + let path = file_path(ds, version); // shortcut: the compressed file is held whole in memory before the upload (150 MiB for SF1); write it through a multipart upload if files get much larger. let payload = object_store::PutPayload::from(bytes); diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index e4a4ac57..d615e5a6 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -249,6 +249,9 @@ pub struct CsrStats { pub base_version: Option, /// Wall time of that build or delta, both directions. pub build_ms: f64, + /// Why the base CSR couldn't be stored (see [`PersistCsr::LoadAndStore`]), or `None`. + /// It stays set while the engine keeps that base, through deltas and reuse. + pub store_error: Option, } /// What [`CypherEngine::optimize_datasets`] did to one Lance dataset. @@ -384,6 +387,8 @@ struct CsrEntry { build_ms: f64, /// How the last build, `checkout_latest()` or optimize produced this entry: build, rebuild, loaded, delta or reused. update: &'static str, + /// Why the full build of the base couldn't be stored, if storing was on and failed. + store_error: Option, } /// Rebuild instead of applying a delta once pending changes (appended edges + @@ -445,6 +450,7 @@ async fn try_apply_csr_delta( base_version: old.base_version, build_ms: elapsed(), update: "delta", + store_error: old.store_error.clone(), }) } @@ -500,6 +506,7 @@ async fn load_stored_csr(source: &EngineSource, src: &str, dst: &str) -> Option< base_version: Some(stored.version), build_ms: started.elapsed().as_secs_f64() * 1e3, update: "loaded", + store_error: None, }) } @@ -941,8 +948,9 @@ const MAX_CONCURRENT_CSR_LOADS: usize = 10; /// target ids. Relationship types with non-integer endpoints get no entry and /// queries over them use the join path. /// -/// With `persist`, a Lance relationship dataset's stored CSR is loaded instead of the -/// first build when it can be brought up to date, and every full build is stored. +/// Unless `persist` is [`PersistCsr::Off`], a Lance relationship dataset's stored CSR is +/// loaded instead of the first build when it can be brought up to date. With +/// [`PersistCsr::LoadAndStore`], every full build is stored too. /// Later rebuilds don't look for a file: the stored base is the one the engine already /// had, whose delta just grew too large. async fn build_csr_entries( @@ -951,7 +959,7 @@ async fn build_csr_entries( schemas: &HashMap, previous: Option<&EngineState>, rebuild_deltas: bool, - persist: bool, + persist: PersistCsr, ) -> Result> { // Types run concurrently so stored loads, which decode on the blocking pool, overlap. // Deltas and builds run on this task, where overlapping gains nothing and would blur @@ -993,7 +1001,7 @@ async fn build_csr_entries( } let previous_entry = previous.and_then(|p| p.csr.get(rel_type)); - if persist && previous_entry.is_none() { + if persist != PersistCsr::Off && previous_entry.is_none() { if let Some(entry) = load_stored_csr(source, src.name(), dst.name()).await { return Ok(Some((rel_type.clone(), entry))); } @@ -1015,12 +1023,16 @@ async fn build_csr_entries( let outgoing = Adjacency::build(scan().await?, src.name(), dst.name()).await?; let incoming = Adjacency::build(scan().await?, dst.name(), src.name()).await?; let build_ms = started.elapsed().as_secs_f64() * 1e3; - if let (true, EngineSource::Lance { dataset, .. }) = (persist, source) { + let mut store_error = None; + if let (PersistCsr::LoadAndStore, EngineSource::Lance { dataset, .. }) = + (persist, source) + { // A failed write (read-only dataset or credentials) only costs the next start a build. if let Err(e) = csr_store::save(dataset, src.name(), dst.name(), &outgoing, &incoming).await { log::warn!("Could not store the CSR of {rel_type}: {e}"); + store_error = Some(e.to_string()); } } Ok::<_, GraphError>(Some(( @@ -1037,6 +1049,7 @@ async fn build_csr_entries( } else { "build" }, + store_error, }, ))) }) @@ -1050,6 +1063,23 @@ async fn build_csr_entries( Ok(entries.into_iter().flatten().collect()) } +/// How an engine over Lance datasets uses CSR files stored at +/// `_lance_csr/.arrow` inside each relationship dataset. Ignored without +/// `use_csr` and for Arrow input. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum PersistCsr { + /// Build every CSR in memory; never read or write stored files. + #[default] + Off, + /// Load a stored CSR when one can be brought up to date, and otherwise build in + /// memory. Never writes to the dataset, and [`CypherEngine::delete_stored_csr`] refuses. + Load, + /// Load as [`Load`](Self::Load) does, and store every full build, including those + /// from `checkout_latest()` and `optimize_csr()`. A failed write doesn't fail the + /// engine: it is logged and reported in [`CsrStats::store_error`]. + LoadAndStore, +} + /// Options for [`CypherEngine::with_options`]. #[derive(Debug, Clone, Default, PartialEq)] pub struct EngineOptions { @@ -1057,12 +1087,10 @@ pub struct EngineOptions { pub use_csr: bool, /// DataFusion `target_partitions`; see [`CypherEngine::with_target_partitions`]. pub target_partitions: Option, - /// Store each fully built CSR inside its Lance relationship dataset, at - /// `_lance_csr/.arrow`, and load it instead of building when an engine - /// starts. Changes since the stored version apply as a delta, under - /// the same 25% threshold as `checkout_latest()`. Ignored without `use_csr` and for Arrow - /// input. A failed write is logged and doesn't fail the engine. - pub persist_csr: bool, + /// Whether to load stored CSR files instead of building, and whether to store full + /// builds; see [`PersistCsr`]. Changes since a stored version apply as a delta, under + /// the same 25% threshold as `checkout_latest()`. + pub persist_csr: PersistCsr, } /// Cypher query engine with a cached catalog for efficient multi-query execution. @@ -1490,10 +1518,19 @@ impl CypherEngine { /// (see [`EngineOptions::persist_csr`]), returning how many files were deleted. /// /// The engine keeps the CSR it has in memory, so queries are unaffected. An - /// engine with `persist_csr` stores a new file at its next full build; create - /// engines without it to stay in memory only. Runs one at a time with `checkout_latest()` - /// and `optimize_csr()`. + /// engine with [`PersistCsr::LoadAndStore`] stores a new file at its next full build; + /// create engines without it to stay in memory only. An engine with + /// [`PersistCsr::Load`] never writes, so this returns a configuration error. Runs one + /// at a time with `checkout_latest()` and `optimize_csr()`. pub async fn delete_stored_csr(&self) -> Result { + if self.options.persist_csr == PersistCsr::Load { + return Err(GraphError::ConfigError { + message: "delete_stored_csr() is unavailable on a load-only engine, which \ + never writes to its datasets" + .to_string(), + location: snafu::Location::new(file!(), line!(), column!()), + }); + } let _updating = self.update_lock.lock().await; let current = self.snapshot(); let mut deleted = 0; @@ -1526,6 +1563,7 @@ impl CypherEngine { version: entry.source.lance_version(), base_version: entry.base_version, build_ms: entry.build_ms, + store_error: entry.store_error.clone(), }; (rel_type.clone(), stats) }) @@ -2029,7 +2067,7 @@ mod tests { } /// Every `(a, b)` reachable in two hops, sorted, from an engine over `uri`. - async fn two_hops(uri: &str, persist_csr: bool) -> (Vec<(i64, i64)>, CsrStats) { + async fn two_hops(uri: &str, persist_csr: PersistCsr) -> (Vec<(i64, i64)>, CsrStats) { let config = GraphConfig::builder() .node_table("Person", "id") .rel_table("KNOWS", "Person", "Person", "src", "dst") @@ -2107,18 +2145,18 @@ mod tests { edges.extend([(3, 3), (3, 21), (3, 21)]); write_knows(&uri, &edges, WriteMode::Create).await; - let (expected, stats) = two_hops(&uri, false).await; + let (expected, stats) = two_hops(&uri, PersistCsr::Off).await; assert_eq!(stats.update, "build"); assert!( stored_files(&uri).is_empty(), "nothing is stored without persist_csr" ); - let (rows, stats) = two_hops(&uri, true).await; + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; assert_eq!((rows == expected, stats.update), (true, "build")); assert_eq!(stored_files(&uri), ["1.arrow"]); - let (rows, stats) = two_hops(&uri, true).await; + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; assert_eq!((rows == expected, stats.update), (true, "loaded")); assert_eq!((stats.edges, stats.base_version), (103, Some(1))); @@ -2126,8 +2164,8 @@ mod tests { write_knows(&uri, &[(1, 2), (2, 1), (40, 3)], WriteMode::Append).await; let mut ds = Dataset::open(&uri).await.unwrap(); ds.delete("src = 3 AND dst = 21").await.unwrap(); - let (expected, _) = two_hops(&uri, false).await; - let (rows, stats) = two_hops(&uri, true).await; + let (expected, _) = two_hops(&uri, PersistCsr::Off).await; + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; assert_eq!((rows == expected, stats.update), (true, "loaded")); assert_eq!( ( @@ -2150,7 +2188,7 @@ mod tests { b"not arrow", ) .unwrap(); - let (rows, stats) = two_hops(&uri, true).await; + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; assert_eq!((rows == expected, stats.update), (true, "build")); assert_eq!(stored_files(&uri), ["3.arrow"], "older files are pruned"); @@ -2166,7 +2204,7 @@ mod tests { .unwrap(); let options = EngineOptions { use_csr: true, - persist_csr: true, + persist_csr: PersistCsr::LoadAndStore, ..Default::default() }; let engine = CypherEngine::with_options( @@ -2181,9 +2219,9 @@ mod tests { let stats = &engine.csr_stats()["KNOWS"]; assert_eq!((stats.update, stats.base_version), ("rebuild", Some(4))); assert_eq!(stored_files(&uri), ["4.arrow"]); - let (rows, stats) = two_hops(&uri, true).await; + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; assert_eq!(stats.update, "loaded"); - assert_eq!(rows, two_hops(&uri, false).await.0); + assert_eq!(rows, two_hops(&uri, PersistCsr::Off).await.0); // Deleting the stored files leaves the engine's CSR in place. assert_eq!(engine.delete_stored_csr().await.unwrap(), 1); @@ -2191,7 +2229,69 @@ mod tests { assert!(!dir.path().join("knows.lance/_lance_csr").exists()); assert_eq!(engine.csr_stats()["KNOWS"].edges, 104); assert_eq!(engine.delete_stored_csr().await.unwrap(), 0); - assert_eq!(two_hops(&uri, true).await.1.update, "build"); + assert_eq!( + two_hops(&uri, PersistCsr::LoadAndStore).await.1.update, + "build" + ); + } + + /// A load-only engine loads a stored CSR but never writes: a miss builds in memory, + /// and `delete_stored_csr()` refuses. A store that can't be written fails before the + /// encode and is reported in `csr_stats()`. + #[tokio::test] + async fn load_only_csr_never_writes() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().join("knows.lance").display().to_string(); + let edges: Vec<(i64, i64)> = (0..100).map(|i| (i % 50, (i * 7) % 60)).collect(); + write_knows(&uri, &edges, WriteMode::Create).await; + let (expected, _) = two_hops(&uri, PersistCsr::Off).await; + + let (rows, stats) = two_hops(&uri, PersistCsr::Load).await; + assert_eq!((rows == expected, stats.update), (true, "build")); + assert!( + stored_files(&uri).is_empty(), + "a load-only miss writes nothing" + ); + + two_hops(&uri, PersistCsr::LoadAndStore).await; + let (rows, stats) = two_hops(&uri, PersistCsr::Load).await; + assert_eq!((rows == expected, stats.update), (true, "loaded")); + assert_eq!(stats.store_error, None); + + let knows = EngineSource::open_lance(&uri, None, HashMap::new()) + .await + .unwrap(); + let config = GraphConfig::builder() + .node_table("Person", "id") + .rel_table("KNOWS", "Person", "Person", "src", "dst") + .build() + .unwrap(); + let options = EngineOptions { + use_csr: true, + persist_csr: PersistCsr::Load, + ..Default::default() + }; + let engine = CypherEngine::with_options( + config, + HashMap::from([("KNOWS".to_string(), knows)]), + options, + ) + .await + .unwrap(); + let error = engine.delete_stored_csr().await.unwrap_err(); + assert!(matches!(error, GraphError::ConfigError { .. }), "{error}"); + assert_eq!(stored_files(&uri), ["1.arrow"]); + + // A file where the folder should be makes every write fail, on any platform. + std::fs::remove_dir_all(dir.path().join("knows.lance/_lance_csr")).unwrap(); + std::fs::write(dir.path().join("knows.lance/_lance_csr"), b"").unwrap(); + let (rows, stats) = two_hops(&uri, PersistCsr::LoadAndStore).await; + assert_eq!((rows == expected, stats.update), (true, "build")); + let error = stats.store_error.expect("the failed write is reported"); + assert!( + error.contains(".write-probe"), + "fails before the encode: {error}" + ); } /// An engine over Lance `Person(id)` and `KNOWS(src, dst)` datasets in `dir`. diff --git a/crates/lance-csr/src/lib.rs b/crates/lance-csr/src/lib.rs index a86851a5..e84bafd2 100644 --- a/crates/lance-csr/src/lib.rs +++ b/crates/lance-csr/src/lib.rs @@ -82,7 +82,9 @@ pub const MAX_VARIABLE_LENGTH_HOPS: u32 = 20; pub use config::{GraphConfig, NodeMapping, RelationshipMapping}; pub use csr_index::{CsrIndex, CsrIndexBuilder}; -pub use engine::{open_lance_dataset, CypherEngine, DatasetOptimizeStats, EngineSource, SqlEngine}; +pub use engine::{ + open_lance_dataset, CypherEngine, DatasetOptimizeStats, EngineSource, PersistCsr, SqlEngine, +}; pub use error::{GraphError, Result}; pub use graph_export::GraphExport; pub use lance_vector_search::VectorSearch; diff --git a/docs/csr.md b/docs/csr.md index 8f34af1c..05ce7f85 100644 --- a/docs/csr.md +++ b/docs/csr.md @@ -479,10 +479,19 @@ files it recognises. once a newer one is written. - **A file that can't be used** (corrupt, written for other endpoint columns or by another format) is ignored and rebuilt, so a bad file costs a build, never a wrong answer. -- **A dataset that can't be written**, because of read-only storage or credentials, is built as without the option, - and nothing is stored. Rust applications see the failed write as a `log` warning. +- **A dataset that can't be written**, because of read-only storage or credentials, is built in memory and nothing + is stored. The engine checks that it can write before it compresses the file, so this costs about as much as a + start without the option. Python emits a `RuntimeWarning`, and + [`csr_stats()`][lance_csr.CypherEngine.csr_stats] reports the error as `store_error` for as long as the engine + keeps that CSR. Rust applications also see it as a `log` warning. - **PyArrow inputs** are never stored. That includes Lance data loaded into memory with `to_table()` first. +Some applications only read datasets that another process writes, such as a graph browser over published Lance +tables, and must never change them. They can still use the files a writer stored: with `persist_csr="load"`, an +engine loads a stored CSR exactly as above but never writes. When no file can be used, it builds in memory as +without the option, and the rebuilds of `checkout_latest()` and `optimize_csr()` aren't stored either. +`delete_stored_csr()` raises `ValueError` on such an engine. + To go back to building in memory only, create engines without `persist_csr` and delete the stored files once with [`delete_stored_csr()`][lance_csr.CypherEngine.delete_stored_csr]. It removes the `_lance_csr` folder of every relationship dataset the engine reads and returns how many files it deleted; the engine keeps the CSR it already diff --git a/docs/index.md b/docs/index.md index cfd47b0c..7a962fb9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -140,8 +140,8 @@ The primary purpose of lance-csr is to serve as a fast, lightweight query engine distributed graph processing, [HDC Labs](https://hyperdimensionalcomputing.ai/contact/) builds that separately. -- **Read-only.** The engine queries your tables; it never writes them (the experimental `persist_csr` option - stores only the CSR's own files beside them). Create and update your tables with +- **Read-only.** The engine queries your tables; it never writes them (the experimental `persist_csr=True` + option stores only the CSR's own files beside them, and `persist_csr="load"` only reads them). Create and update your tables with [`pylance`](https://pypi.org/project/pylance/), LanceDB or PyArrow, then query them here. - **Not a server.** There's no network protocol, authentication or multi-tenant process. It's a library. - **Not all of openCypher.** See [supported Cypher](cypher.md#supported-cypher) for what is and isn't diff --git a/docs/internals/indexes.md b/docs/internals/indexes.md index 855caa0e..206f4297 100644 --- a/docs/internals/indexes.md +++ b/docs/internals/indexes.md @@ -179,3 +179,6 @@ node indexes scan on the engine's task. At most 10 load at once: each holds its until it finishes, so peak memory would otherwise grow with the core count. Deltas and full builds gain nothing from overlapping there, so they still run one type at a time, and each `build_ms` measures one build. Writes go through the dataset's object store with `put_if_absent`, which publishes the whole file at once on local disk and object storage; the compressed file is encoded in memory first. +Encoding takes seconds on large graphs, so the store first writes and deletes an empty `.write-probe` in +`_lance_csr`: storage that can't be written fails there, before the encode. With `persist_csr="load"` nothing is +written at all. diff --git a/docs/rust.md b/docs/rust.md index 32c04132..9870a0f9 100644 --- a/docs/rust.md +++ b/docs/rust.md @@ -63,8 +63,9 @@ get [CSR adjacencies](csr.md) and node labels with unique integer ids get a node `use_csr=True` in Python. `CypherEngine::with_target_partitions(config, sources, use_csr, Some(n))` also sets DataFusion's query partition target (1 to 1024), like `target_partitions=` in Python; see [Query parallelism](lance.md#query-parallelism). `CypherEngine::with_options(config, sources, options)` takes every -setting at once as an `EngineOptions` (in `lance_csr::engine`), including `persist_csr`, which -[stores the CSR](csr.md#storing-the-csr) as in Python. +setting at once as an `EngineOptions` (in `lance_csr::engine`), including `persist_csr`, a `PersistCsr` that +[loads and stores the CSR](csr.md#storing-the-csr) as in Python: `Off`, `Load` (`"load"`) or `LoadAndStore` +(`True`). ## Run queries @@ -191,7 +192,8 @@ case for `DirNamespace`. | `engine.explain(query, analyze=True)` | `engine.explain_analyze(query, params).await` | | `engine.execute(query, timeout=2.0)` | `timeout_at(deadline, with_execution_deadline(Some(deadline), engine.execute(...)))` | | `CypherEngine(..., target_partitions=4)` | `CypherEngine::with_target_partitions(config, sources, use_csr, Some(4)).await` | -| `CypherEngine(..., persist_csr=True)` | `CypherEngine::with_options(config, sources, EngineOptions { use_csr: true, persist_csr: true, ..Default::default() }).await` | +| `CypherEngine(..., persist_csr=True)` | `CypherEngine::with_options(config, sources, EngineOptions { use_csr: true, persist_csr: PersistCsr::LoadAndStore, ..Default::default() }).await` | +| `CypherEngine(..., persist_csr="load")` | The same, with `persist_csr: PersistCsr::Load` | | `engine.csr_stats()` → `dict` | `engine.csr_stats()` → `HashMap` | | `ValueError`, `RuntimeError`, ... | `GraphError` variants | diff --git a/docs/typescript.md b/docs/typescript.md index 1d92987b..3033893d 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -204,6 +204,7 @@ method, so your editor shows the details on hover. | `GraphConfig.builder().node_table(...).rel_table(...).build()` | `GraphConfig.builder().nodeTable(...).relTable(...).build()` | | `config.node_labels()`, `config.relationship_types()` | `config.nodeLabels()`, `config.relationshipTypes()` | | `CypherEngine(config, datasets, use_csr=True, target_partitions=4, persist_csr=True)` | `await CypherEngine.create(config, datasets, { useCsr: true, targetPartitions: 4, persistCsr: true })` | +| `persist_csr="load"`, and the `RuntimeWarning` for a failed write | `persistCsr: "load"`, and a `LanceCsrWarning` process warning | | `engine.execute(query, params, timeout=2.5)` | `await engine.execute(query, params, { timeoutMs: 2500 })` | | `engine.execute_batches(query, params, timeout=...)`, a `RecordBatchReader` | `await engine.executeBatches(query, params, { timeoutMs })`, an async iterable `RecordBatchStream` | | `engine.explain(query, params, analyze=True)` | `await engine.explain(query, params, { analyze: true })` | diff --git a/nodejs/native.d.ts b/nodejs/native.d.ts index 4e568c86..6ed8bbf4 100644 --- a/nodejs/native.d.ts +++ b/nodejs/native.d.ts @@ -55,6 +55,7 @@ export interface CsrStats { version?: number baseVersion?: number buildMs: number + storeError?: string } export declare function cypherQueryExecute(spec: CypherQuerySpec, datasetsIn: Record, executionStrategy?: ExecutionStrategy | undefined | null, timeoutMs?: number | undefined | null): Promise @@ -136,7 +137,7 @@ export interface NodeTableSpec { primaryKey: string } -export declare function openCypherEngine(config: GraphConfigSpec, datasetsIn: Record, useCsr: boolean, targetPartitions: number | undefined | null, persistCsr: boolean): Promise +export declare function openCypherEngine(config: GraphConfigSpec, datasetsIn: Record, useCsr: boolean, targetPartitions: number | undefined | null, persistCsr: string): Promise export declare function openSqlEngine(datasetsIn: Record, config: GraphConfigSpec | undefined | null, useCsr: boolean): Promise diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 28859df2..8e437081 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -47,14 +47,17 @@ export interface CypherEngineOptions { */ targetPartitions?: number; /** - * Experimental, needs `useCsr`. Store each relationship dataset's CSR inside the - * dataset's own directory, at `_lance_csr/.arrow`, and load it instead of - * building when an engine starts. Changes since the stored version apply as a delta - * under the same 25% threshold as `checkoutLatest`; past it, the CSR is rebuilt and - * stored again. Arrow inputs aren't stored, and a dataset that can't be written is - * built as without it. + * Experimental, needs `useCsr` unless `false`. With `true`, store each relationship + * dataset's CSR inside the dataset's own directory, at `_lance_csr/.arrow`, + * and load it instead of building when an engine starts. Changes since the stored + * version apply as a delta under the same 25% threshold as `checkoutLatest`; past it, + * the CSR is rebuilt and stored again. Arrow inputs aren't stored. A dataset that + * can't be written is built in memory, and the engine emits a process warning and + * reports the error as `storeError` in `csrStats()`. With `"load"`, load stored files + * the same way but never write to the datasets: a CSR that can't be loaded is built in + * memory, as with `false`. */ - persistCsr?: boolean; + persistCsr?: boolean | "load"; } /** Options for running a query. */ @@ -200,8 +203,8 @@ export class CypherEngine { * @param options - CSR and partitioning options. * @throws {@link LanceCsrError} with code `InvalidArgument` if `datasets` is empty, a * configured key or endpoint column is missing, `targetPartitions` is outside 1 to - * 1024, or `persistCsr` is set without `useCsr`; `Runtime` if a dataset can't be - * opened. + * 1024, `persistCsr` isn't `true`, `false` or `"load"`, or it is set without `useCsr`; + * `Runtime` if a dataset can't be opened. * @throws `TypeError` if `config` isn't a `GraphConfig` or a dataset has an * unsupported type. */ @@ -216,10 +219,29 @@ export class CypherEngine { if (targetPartitions !== undefined && typeof targetPartitions !== "number") { throw new TypeError("targetPartitions must be a number or undefined"); } + const modes = new Map([ + [false, "off"], + [true, "store"], + ["load", "load"], + ]); + // Anything else reaches the native check as an unknown mode. + const mode = modes.get(persistCsr) ?? "invalid"; const inner = await call(() => - native.openCypherEngine(spec, inputs, useCsr, targetPartitions, persistCsr), + native.openCypherEngine(spec, inputs, useCsr, targetPartitions, mode), ); - return new CypherEngine(inner, config); + const engine = new CypherEngine(inner, config); + engine.#warnStoreErrors({}); + return engine; + } + + // The engine only logs a failed CSR write; callers see it here once. + #warnStoreErrors(before: Record): void { + for (const [relType, stats] of Object.entries(this.#inner.csrStats())) { + const error = stats.storeError; + if (error && error !== before[relType]?.storeError) { + process.emitWarning(`Could not store the CSR of ${relType}: ${error}`, "LanceCsrWarning"); + } + } } /** @internal The native engine, for `SqlEngine.fromEngine`. */ @@ -307,7 +329,9 @@ export class CypherEngine { * [Lance datasets](https://lance-csr.hdclabs.ai/lance/#checkout-latest). */ async checkoutLatest(): Promise { + const before = this.#inner.csrStats(); await call(() => this.#inner.checkoutLatest()); + this.#warnStoreErrors(before); } /** @@ -335,7 +359,10 @@ export class CypherEngine { async optimizeDatasets( options: { cleanupOlderThanMs?: number } = {}, ): Promise> { - return await call(() => this.#inner.optimizeDatasets(options.cleanupOlderThanMs)); + const before = this.#inner.csrStats(); + const result = await call(() => this.#inner.optimizeDatasets(options.cleanupOlderThanMs)); + this.#warnStoreErrors(before); + return result; } /** @@ -349,7 +376,9 @@ export class CypherEngine { * [Rebuilding the CSR](https://lance-csr.hdclabs.ai/csr/#rebuilding-the-csr). */ async optimizeCsr(): Promise { + const before = this.#inner.csrStats(); await call(() => this.#inner.optimizeCsr()); + this.#warnStoreErrors(before); } /** @@ -360,6 +389,8 @@ export class CypherEngine { * affected. See [Storing the CSR](https://lance-csr.hdclabs.ai/csr/#storing-the-csr). * * @returns The number of files deleted; 0 when nothing was stored. + * @throws {@link LanceCsrError} `InvalidArgument` if the engine was created with + * `persistCsr: "load"`, which never writes to its datasets. */ async deleteStoredCsr(): Promise { return call(() => this.#inner.deleteStoredCsr()); diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index dc6e43a2..5c8971e7 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -86,6 +86,11 @@ export interface CsrStats { baseVersion?: number; /** Wall time of that build or delta, both directions, in milliseconds. */ buildMs: number; + /** + * Why the base CSR couldn't be stored with `persistCsr: true`; absent when it was, or + * when nothing is stored. It stays set while the engine keeps that base, through deltas. + */ + storeError?: string; } /** diff --git a/nodejs/test/cypher-engine.test.ts b/nodejs/test/cypher-engine.test.ts index dbc611cf..e563669b 100644 --- a/nodejs/test/cypher-engine.test.ts +++ b/nodejs/test/cypher-engine.test.ts @@ -151,6 +151,14 @@ describe("CypherEngine options", () => { code: "InvalidArgument", message: /persistCsr requires useCsr/, }); + await assert.rejects(CypherEngine.create(config, datasets, { persistCsr: "load" }), { + code: "InvalidArgument", + message: /persistCsr requires useCsr/, + }); + await assert.rejects( + CypherEngine.create(config, datasets, { useCsr: true, persistCsr: "store" as never }), + { code: "InvalidArgument", message: /persistCsr must be true, false or "load"/ }, + ); }); test("argument types", async () => { diff --git a/nodejs/test/lance.test.ts b/nodejs/test/lance.test.ts index ee3d2996..f507b499 100644 --- a/nodejs/test/lance.test.ts +++ b/nodejs/test/lance.test.ts @@ -1,7 +1,7 @@ // CypherEngine over on-disk Lance datasets: pinned snapshots, checkoutLatest, streaming and // the stored CSR. Expected values are computed independently of the engine. import assert from "node:assert/strict"; -import { existsSync, readdirSync } from "node:fs"; +import { existsSync, readdirSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { describe, test } from "node:test"; import { Table, tableFromArrays } from "apache-arrow"; @@ -218,6 +218,50 @@ describe("Lance datasets", () => { assert.equal(await countPeople(second), N); }); + test('persistCsr "load" never writes, and a failed write is reported', async () => { + const { person, knows } = await graph(); + const datasets = { Person: person, KNOWS: knows }; + const folder = join(knows.uri, "_lance_csr"); + const missed = await CypherEngine.create(config, datasets, { + useCsr: true, + persistCsr: "load", + }); + assert.equal(missed.csrStats().KNOWS!.update, "build"); + assert.equal(existsSync(folder), false); + await CypherEngine.create(config, datasets, { useCsr: true, persistCsr: true }); + const loaded = await CypherEngine.create(config, datasets, { + useCsr: true, + persistCsr: "load", + }); + assert.equal(loaded.csrStats().KNOWS!.update, "loaded"); + await assert.rejects(loaded.deleteStoredCsr(), { + code: "InvalidArgument", + message: /load-only/, + }); + assert.deepEqual(readdirSync(folder), ["1.arrow"]); + + // A file where the folder should be makes the write fail. + rmSync(folder, { recursive: true }); + writeFileSync(folder, ""); + const warnings: string[] = []; + const listener = (warning: Error) => warnings.push(warning.message); + process.on("warning", listener); + try { + const failed = await CypherEngine.create(config, datasets, { + useCsr: true, + persistCsr: true, + }); + assert.match(failed.csrStats().KNOWS!.storeError ?? "", /\.write-probe/); + await new Promise((resolve) => setImmediate(resolve)); + } finally { + process.off("warning", listener); + } + assert.ok( + warnings.some((m) => m.startsWith("Could not store the CSR of KNOWS")), + `${warnings}`, + ); + }); + test("optimizeDatasets compacts, moves the engine and deletes old versions", async () => { const { person, knows } = await graph(); const engine = await CypherEngine.create( diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index 06900939..214ea4dd 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -130,6 +130,11 @@ affected. See [Storing the CSR](https://lance-csr.hdclabs.ai/csr/#storing-the-cs The number of files deleted; 0 when nothing was stored. +###### Throws + +[LanceCsrError](#lancecsrerror) `InvalidArgument` if the engine was created with + `persistCsr: "load"`, which never writes to its datasets. + ##### execute() @@ -395,8 +400,8 @@ Open the datasets and build the engine. Lance datasets are pinned, not read; wit [LanceCsrError](#lancecsrerror) with code `InvalidArgument` if `datasets` is empty, a configured key or endpoint column is missing, `targetPartitions` is outside 1 to -1024, or `persistCsr` is set without `useCsr`; `Runtime` if a dataset can't be -opened. +1024, `persistCsr` isn't `true`, `false` or `"load"`, or it is set without `useCsr`; +`Runtime` if a dataset can't be opened. ###### Throws @@ -1545,6 +1550,7 @@ Statistics for one CSR adjacency index, from `CypherEngine.csrStats()`. | `buildMs` | `number` | Wall time of that build or delta, both directions, in milliseconds. | | `deltaEdges` | `number` | Edges appended since the last full build, held outside the base CSR. | | `edges` | `number` | Live indexed edges (null endpoints are skipped). | +| `storeError?` | `string` | Why the base CSR couldn't be stored with `persistCsr: true`; absent when it was, or when nothing is stored. It stays set while the engine keeps that base, through deltas. | | `tombstones` | `number` | Edges removed since the last full build, held outside the base CSR. | | `unindexedEdges` | `number` | Live edges outside the base CSR: appended since its last full build and not since removed. | | `update` | `"build"` \| `"rebuild"` \| `"loaded"` \| `"delta"` \| `"reused"` | How the last build, `checkoutLatest()` or `optimizeCsr()` produced it. | @@ -1562,7 +1568,7 @@ Options for [CypherEngine.create](#create). | Property | Type | Description | | ------ | ------ | ------ | -| `persistCsr?` | `boolean` | Experimental, needs `useCsr`. Store each relationship dataset's CSR inside the dataset's own directory, at `_lance_csr/.arrow`, and load it instead of building when an engine starts. Changes since the stored version apply as a delta under the same 25% threshold as `checkoutLatest`; past it, the CSR is rebuilt and stored again. Arrow inputs aren't stored, and a dataset that can't be written is built as without it. | +| `persistCsr?` | `boolean` \| `"load"` | Experimental, needs `useCsr` unless `false`. With `true`, store each relationship dataset's CSR inside the dataset's own directory, at `_lance_csr/.arrow`, and load it instead of building when an engine starts. Changes since the stored version apply as a delta under the same 25% threshold as `checkoutLatest`; past it, the CSR is rebuilt and stored again. Arrow inputs aren't stored. A dataset that can't be written is built in memory, and the engine emits a process warning and reports the error as `storeError` in `csrStats()`. With `"load"`, load stored files the same way but never write to the datasets: a CSR that can't be loaded is built in memory, as with `false`. | | `targetPartitions?` | `number` | A target from 1 to 1024 for DataFusion query partitioning; left out, DataFusion's default. `checkoutLatest` preserves it. It is not a thread or memory limit. | | `useCsr?` | `boolean` | Build the experimental [CSR index](https://lance-csr.hdclabs.ai/csr/) for relationship types with integer endpoints, and node indexes for labels with unique integer keys. | diff --git a/python/python/lance_csr/_internal/graph.pyi b/python/python/lance_csr/_internal/graph.pyi index 9cfa3904..519541a6 100644 --- a/python/python/lance_csr/_internal/graph.pyi +++ b/python/python/lance_csr/_internal/graph.pyi @@ -45,6 +45,7 @@ class _CsrStats(TypedDict): version: int | None base_version: int | None build_ms: float + store_error: str | None class _DatasetOptimizeStats(TypedDict): fragments_removed: int @@ -127,7 +128,7 @@ class CypherEngine: use_csr: bool = False, *, target_partitions: int | None = None, - persist_csr: bool = False, + persist_csr: bool | Literal["load"] = False, ) -> None: ... def execute( self, diff --git a/python/python/lance_csr/_types.py b/python/python/lance_csr/_types.py index 6fd300df..daae9c9c 100644 --- a/python/python/lance_csr/_types.py +++ b/python/python/lance_csr/_types.py @@ -58,6 +58,7 @@ class CsrStats(TypedDict): version: int | None base_version: int | None build_ms: float + store_error: str | None class DatasetOptimizeStats(TypedDict): diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index d9ed8c3f..64eafade 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -2,8 +2,9 @@ from __future__ import annotations +import warnings from enum import IntEnum -from typing import TYPE_CHECKING, Any, Self, final +from typing import TYPE_CHECKING, Any, Literal, Self, final from ._internal import graph as _graph from ._types import inner @@ -87,23 +88,27 @@ class CypherEngine: Keyword-only. A target from 1 to 1024 for DataFusion query partitioning; `None` keeps DataFusion's default. `checkout_latest` preserves it. It is not a thread or memory limit. See [Query parallelism](lance.md#query-parallelism). - persist_csr : bool - Keyword-only, experimental, needs `use_csr=True`. Store each relationship - dataset's CSR inside the dataset's own directory, at + persist_csr : bool or "load" + Keyword-only, experimental, needs `use_csr=True` unless `False`. With `True`, + store each relationship dataset's CSR inside the dataset's own directory, at `_lance_csr/.arrow`, and load it instead of building when an engine starts. Changes since the stored version apply as a delta under the same 25% threshold as `checkout_latest`; past it, the CSR is rebuilt and stored again. Lance's `cleanup_old_versions` leaves the folder alone. PyArrow inputs aren't - stored, and a dataset that can't be written (read-only storage or credentials) - is built as without it. See [Storing the CSR](csr.md#storing-the-csr). + stored. A dataset that can't be written (read-only storage or credentials) is + built in memory, and the engine emits a `RuntimeWarning` and reports the error + as `store_error` in [`csr_stats`][lance_csr.CypherEngine.csr_stats]. With + `"load"`, load stored files the same way but never write to the datasets: a + CSR that can't be loaded is built in memory, as with `False`. See [Storing the + CSR](csr.md#storing-the-csr). Raises ------ ValueError If `datasets` is empty, a configured key or endpoint column is missing, a Lance dataset was opened through a namespace client and can't be reopened by URI, - `target_partitions` is outside 1 to 1024, or `persist_csr` is set without - `use_csr`. + `target_partitions` is outside 1 to 1024, `persist_csr` isn't `True`, `False` + or `"load"`, or it is set without `use_csr`. TypeError If `config` isn't a `GraphConfig`, a dataset has an unsupported type, or `target_partitions` is a boolean or another non-integer other than `None`. @@ -140,7 +145,7 @@ def __init__[DatasetT: Dataset]( use_csr: bool = False, *, target_partitions: int | None = None, - persist_csr: bool = False, + persist_csr: bool | Literal["load"] = False, ) -> None: self._inner = _graph.CypherEngine( inner(config, GraphConfig, "config"), @@ -149,6 +154,18 @@ def __init__[DatasetT: Dataset]( target_partitions=target_partitions, persist_csr=persist_csr, ) + self._warn_store_errors({}) + + def _warn_store_errors(self, before: dict[str, CsrStats]) -> None: + # The engine only logs a failed CSR write; Python callers see it here once. + for rel_type, stats in self._inner.csr_stats().items(): + error = stats["store_error"] + if error and error != before.get(rel_type, {}).get("store_error"): + warnings.warn( + f"Could not store the CSR of {rel_type}: {error}", + RuntimeWarning, + stacklevel=3, + ) def __repr__(self) -> str: return repr(self._inner) @@ -294,7 +311,9 @@ def checkout_latest(self) -> None: calls run one at a time, and `target_partitions` is preserved. See [Lance datasets](lance.md#checkout-latest). """ + before = self._inner.csr_stats() self._inner.checkout_latest() + self._warn_store_errors(before) def optimize_csr(self) -> None: """Rebuild each CSR that carries a delta (experimental; needs `use_csr=True`). @@ -314,14 +333,16 @@ def optimize_csr(self) -> None: and the two run one at a time. See [Rebuilding the CSR](csr.md#rebuilding-the-csr). """ + before = self._inner.csr_stats() self._inner.optimize_csr() + self._warn_store_errors(before) def delete_stored_csr(self) -> int: """Delete the CSR files stored with `persist_csr=True` (experimental). Removes the `_lance_csr` folder of every Lance relationship dataset this - engine reads, whether or not the engine itself was created with - `persist_csr`. The engine keeps the CSR it already holds in memory, so queries + engine reads, whether the engine itself was created with `persist_csr=True` + or `False`. The engine keeps the CSR it already holds in memory, so queries aren't affected. To go back to in-memory builds only, create later engines without `persist_csr`: an engine with it stores a new file at its next full build. Runs one at a time with `checkout_latest` and `optimize_csr`. See @@ -331,6 +352,12 @@ def delete_stored_csr(self) -> int: ------- int The number of files deleted; 0 when nothing was stored. + + Raises + ------ + ValueError + If the engine was created with `persist_csr="load"`, which never writes + to its datasets. """ return self._inner.delete_stored_csr() @@ -375,6 +402,9 @@ def csr_stats(self) -> dict[str, CsrStats]: - `base_version`: the relationship dataset version of the last full build (`None` for PyArrow). It trails `version` while deltas apply. - `build_ms`: wall time of that build or delta, both directions. + - `store_error`: why the base CSR couldn't be stored with + `persist_csr=True`, or `None`. It stays set while the engine keeps that + base, through deltas. """ return self._inner.csr_stats() @@ -429,7 +459,10 @@ def optimize_datasets( users who keep them still run `table.optimize()` for that, followed by `checkout_latest()`. """ - return self._inner.optimize_datasets(cleanup_older_than=cleanup_older_than) + before = self._inner.csr_stats() + result = self._inner.optimize_datasets(cleanup_older_than=cleanup_older_than) + self._warn_store_errors(before) + return result def export_graph( self, rel_types: list[str] | None = None, *, directed: bool = True diff --git a/python/python/tests/test_engine_csr_persist.py b/python/python/tests/test_engine_csr_persist.py index b45bbd66..d73dca61 100644 --- a/python/python/tests/test_engine_csr_persist.py +++ b/python/python/tests/test_engine_csr_persist.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The Lance Authors -"""Stored CSR files (`persist_csr=True`). +"""Stored CSR files (`persist_csr=True` and `"load"`). An engine that loads a stored CSR must return exactly what a join-path engine returns, after appends, deletes, compaction and cleanup of old versions. @@ -63,9 +63,9 @@ def knows(tmp_path): return uri -def engine(uri, **kwargs): +def engine(uri, persist_csr=True): datasets = {"Person": PEOPLE, "KNOWS": lance.dataset(uri)} - return CypherEngine(CONFIG, datasets, use_csr=True, persist_csr=True, **kwargs) + return CypherEngine(CONFIG, datasets, use_csr=True, persist_csr=persist_csr) def check(persisted, uri): @@ -120,14 +120,38 @@ def test_rebuild_stores_a_new_base(knows): def test_read_only_dataset_still_builds(knows): os.chmod(knows, 0o555) try: - read_only = engine(knows) + with pytest.warns(RuntimeWarning, match="Could not store the CSR of KNOWS"): + read_only = engine(knows) finally: os.chmod(knows, 0o755) - assert read_only.csr_stats()["KNOWS"]["update"] == "build" + s = read_only.csr_stats()["KNOWS"] + assert s["update"] == "build" + assert s["store_error"] and ".write-probe" in s["store_error"] assert stored(knows) == [] check(read_only, knows) +def test_load_only_never_writes(knows): + missed = engine(knows, persist_csr="load") + s = missed.csr_stats()["KNOWS"] + assert (s["update"], s["store_error"]) == ("build", None) + assert stored(knows) == [] + check(missed, knows) + engine(knows) # a writer stores the file + loaded = engine(knows, persist_csr="load") + assert loaded.csr_stats()["KNOWS"]["update"] == "loaded" + check(loaded, knows) + # Past the rebuild threshold a load-only engine builds without replacing the file. + lance.write_dataset(edges(BASE[:60], 5000), knows, mode="append") + loaded.checkout_latest() + loaded.optimize_csr() + assert loaded.csr_stats()["KNOWS"]["update"] == "rebuild" + assert stored(knows) == ["1.arrow"] + with pytest.raises(ValueError, match="load-only"): + loaded.delete_stored_csr() + assert stored(knows) == ["1.arrow"] + + def test_delete_stored_csr(knows): persisted = engine(knows) assert stored(knows) == ["1.arrow"] @@ -148,6 +172,13 @@ def test_pyarrow_input_is_not_stored(): assert e.csr_stats()["KNOWS"]["update"] == "build" -def test_persist_csr_needs_use_csr(knows): +@pytest.mark.parametrize("persist_csr", [True, "load"]) +def test_persist_csr_needs_use_csr(knows, persist_csr): with pytest.raises(ValueError, match="persist_csr requires use_csr"): - CypherEngine(CONFIG, {"KNOWS": lance.dataset(knows)}, persist_csr=True) + CypherEngine(CONFIG, {"KNOWS": lance.dataset(knows)}, persist_csr=persist_csr) + + +@pytest.mark.parametrize("persist_csr", ["store", 1]) +def test_persist_csr_rejects_other_values(knows, persist_csr): + with pytest.raises(ValueError, match='True, False or "load"'): + engine(knows, persist_csr=persist_csr)