Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

feat(rust-sdk): SurrealDB mem:// embedded engine; SurrealDB tests run in the SDK suite (#2781)

LJ πŸ₯₯🌴c4008c9e3d30
diff --git a/Cargo.lock b/Cargo.lock
index aebf3869..e92448ea 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -52,6 +52,23 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "affinitypool"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4a46f56d354df11b6bcd8ca4f84fa03ac816cc41c72568a1b337d8f7e5af90e"
+dependencies = [
+ "arc-swap",
+ "async-task",
+ "crossbeam-deque",
+ "crossbeam-utils",
+ "libc",
+ "num_cpus",
+ "parking_lot",
+ "thiserror 2.0.20",
+ "winapi",
+]
+
[[package]]
name = "ahash"
version = "0.7.8"
@@ -1404,6 +1421,26 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bincode"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740"
+dependencies = [
+ "bincode_derive",
+ "serde",
+ "unty",
+]
+
+[[package]]
+name = "bincode_derive"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf95709a440f45e986983918d0e8a1f30a9b1df04918fc828670606804ac3c09"
+dependencies = [
+ "virtue",
+]
+
[[package]]
name = "bit-vec"
version = "0.9.1"
@@ -2724,6 +2761,16 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "crossbeam-skiplist"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df29de440c58ca2cc6e587ec3d22347551a32435fbde9d2bff64e78a9ffa151b"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
[[package]]
name = "crossbeam-utils"
version = "0.8.22"
@@ -4190,6 +4237,19 @@ dependencies = [
"zune-inflate",
]
+[[package]]
+name = "ext-sort"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05e74d1b500434b40de2a046ab65f27528040d272241da81ba9c5bf143d703fb"
+dependencies = [
+ "log",
+ "rayon",
+ "rmp-serde",
+ "serde",
+ "tempfile",
+]
+
[[package]]
name = "ext-trait"
version = "1.0.1"
@@ -5133,7 +5193,7 @@ version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c255bdf46e07fb840d120a36dcc81f385140d7191c76a7391672675c01a55d"
dependencies = [
- "bincode",
+ "bincode 1.3.3",
"byteorder",
"heed-traits",
"serde",
@@ -10747,6 +10807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cd76c36f8b545a9371eec050bb2ae83750a6f60bae8c6d92d06956943348f4c"
dependencies = [
"addr",
+ "affinitypool",
"ahash 0.8.12",
"ammonia",
"anyhow",
@@ -10765,6 +10826,7 @@ dependencies = [
"diskann-utils",
"diskann-vector",
"dmp",
+ "ext-sort",
"fastnum",
"fst",
"futures",
@@ -10817,7 +10879,9 @@ dependencies = [
"surrealdb-protocol",
"surrealdb-strand",
"surrealdb-types",
+ "surrealmx",
"sysinfo",
+ "tempfile",
"thiserror 2.0.20",
"tokio",
"tokio-util",
@@ -10909,6 +10973,28 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "surrealmx"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e8a87f050a4860832ccf4a53e43ea264e98d27618983602b5c575e6df296054"
+dependencies = [
+ "arc-swap",
+ "bincode 2.0.1",
+ "bytes",
+ "crossbeam-deque",
+ "crossbeam-queue",
+ "crossbeam-skiplist",
+ "lz4",
+ "papaya",
+ "parking_lot",
+ "serde",
+ "smallvec",
+ "thiserror 2.0.20",
+ "tracing",
+ "web-time",
+]
+
[[package]]
name = "syn"
version = "1.0.109"
@@ -12309,6 +12395,12 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+[[package]]
+name = "unty"
+version = "0.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae"
+
[[package]]
name = "ureq"
version = "2.12.1"
@@ -12426,6 +12518,12 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "virtue"
+version = "0.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "051eb1abcf10076295e815102942cc58f9d5e3b4560e46e53c21e8ff6f3af7b1"
+
[[package]]
name = "vsimd"
version = "0.8.0"
diff --git a/dev/run_cargo_test_sdk.sh b/dev/run_cargo_test_sdk.sh
index 0c78cd66..8416c82d 100755
--- a/dev/run_cargo_test_sdk.sh
+++ b/dev/run_cargo_test_sdk.sh
@@ -21,7 +21,7 @@ cargo check -p cocoindex --all-features --all-targets
# (cargo-clippy-sdk compiles it). Arguments narrow the run, e.g.
# `--test fs_live`.
SDK_TEST_FEATURES="azure_blob,bigquery,code_match,doris,embed_api,fs_live,google_drive,kafka,lancedb"
-SDK_TEST_FEATURES+=",oci_object_storage,postgres,snowflake,sqlite,testing,text,turbopuffer,valkey"
+SDK_TEST_FEATURES+=",oci_object_storage,postgres,snowflake,sqlite,surrealdb,surrealdb_mem,testing,text,turbopuffer,valkey"
# The zvec tests link the prebuilt `zvec_c_api` shared library that the
# `zvec-rust` build script downloads. On Windows Cargo does not put that DLL on
# the test binaries' search path (STATUS_DLL_NOT_FOUND), so the tests run on
diff --git a/docs/src/content/docs/connectors/surrealdb.mdx b/docs/src/content/docs/connectors/surrealdb.mdx
index 4500e8b2..9554445b 100644
--- a/docs/src/content/docs/connectors/surrealdb.mdx
+++ b/docs/src/content/docs/connectors/surrealdb.mdx
@@ -109,7 +109,7 @@ async fn main() -> Result<()> {
}
```
-`Graph::connect(url, ns, db, user, pass)` opens one WebSocket connection and signs in as a root user. `url` is the host and port, without the `ws://` scheme or `/rpc` path. A `Graph` has no `close()` method; `builder.on_shutdown(..)` in a `#[cocoindex::lifespan]` function is the place for teardown.
+`Graph::connect(url, ns, db, user, pass)` opens one connection and signs in as a root user. `url` is a WebSocket server, as `host:port` or with a `ws://` or `wss://` scheme (an `/rpc` path is optional), or `mem://` for SurrealDB's embedded in-memory engine (the `surrealdb_mem` feature): each `mem://` connection is a fresh, private database, which suits tests (connect with `Credentials::None`, below). A `Graph` has no `close()` method; `builder.on_shutdown(..)` in a `#[cocoindex::lifespan]` function is the place for teardown.
</Fragment>
</LangTabs>
@@ -138,9 +138,9 @@ let graph = Graph::connect_with_credentials(
- `Namespace { username, password }` β€” a user of the connection's namespace.
- `Database { username, password }` β€” a user of the connection's database.
- `Record { access, params }` β€” a record user, through the access method `access` of the connection's database, with the `params` (a `serde_json::Value`) that method expects.
-- `None` β€” no sign-in, for a server started without authentication.
+- `None` β€” no sign-in, for a server started without authentication or the embedded `mem://` engine.
-The graph's stable identity is the context key's name; the credentials are not part of any stored state. `graph.client()` returns the underlying `surrealdb::Surreal` client, for queries of your own.
+The graph's stable identity is the context key's name; the credentials are not part of any stored state. `graph.client()` returns the underlying `surrealdb::Surreal<surrealdb::engine::any::Any>` client, for queries of your own.
</Lang>
diff --git a/docs/src/content/docs/getting_started/installation.mdx b/docs/src/content/docs/getting_started/installation.mdx
index ea6152ff..117be0bd 100644
--- a/docs/src/content/docs/getting_started/installation.mdx
+++ b/docs/src/content/docs/getting_started/installation.mdx
@@ -107,6 +107,7 @@ cocoindex = { git = "https://github.com/cocoindex-io/cocoindex", features = [
| `sqlite` | SQLite target |
| `doris` | Apache Doris target |
| `surrealdb` | SurrealDB target |
+| `surrealdb_mem` | SurrealDB's embedded in-memory engine (`mem://`), for tests |
| `neo4j` | Neo4j target |
| `falkordb` | FalkorDB target |
| `lancedb` | LanceDB target (the build needs `protoc`) |
diff --git a/rust/sdk/cocoindex/Cargo.toml b/rust/sdk/cocoindex/Cargo.toml
index b70e3145..f7e60a17 100644
--- a/rust/sdk/cocoindex/Cargo.toml
+++ b/rust/sdk/cocoindex/Cargo.toml
@@ -96,6 +96,10 @@ surrealdb = [
"chrono",
"rust_decimal",
]
+# SurrealDB's embedded in-memory engine (`Graph::connect("mem://", ..)`), which
+# the SDK's SurrealDB tests run on. It builds the SurrealDB engine itself
+# (`surrealdb-core`), which the WebSocket client alone does not need.
+surrealdb_mem = ["surrealdb", "surrealdb/kv-mem"]
# Kafka source and target (pure-Rust `rskafka`); TLS via rustls with the
# Mozilla roots, client-side PEM parsing via `rustls-pki-types`.
kafka = [
diff --git a/rust/sdk/cocoindex/src/connectors/surrealdb.rs b/rust/sdk/cocoindex/src/connectors/surrealdb.rs
index 73cde87f..f14452a2 100644
--- a/rust/sdk/cocoindex/src/connectors/surrealdb.rs
+++ b/rust/sdk/cocoindex/src/connectors/surrealdb.rs
@@ -37,7 +37,7 @@ use cocoindex_utils::fingerprint::Fingerprint;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value as JsonValue};
use surrealdb::Surreal;
-use surrealdb::engine::remote::ws::{Client, Ws};
+use surrealdb::engine::any::{self, Any};
use surrealdb::opt::auth;
use surrealdb::types::{
Bytes, Datetime, Decimal, Duration, Number, Object, QueryError, RecordId, RecordIdKey,
@@ -263,7 +263,7 @@ impl IntoRecordId for &str {
#[derive(Clone)]
pub struct Graph {
- db: Arc<Surreal<Client>>,
+ db: Arc<Surreal<Any>>,
state_id: Arc<str>,
}
@@ -321,8 +321,22 @@ impl std::fmt::Debug for Credentials {
}
}
+/// The endpoint `url` names: a `host:port` without a scheme is a WebSocket
+/// server (`ws://host:port`); `ws://`, `wss://` and `mem://` (the embedded
+/// in-memory engine) are taken as they are.
+fn endpoint(url: &str) -> String {
+ if url.contains("://") {
+ url.to_string()
+ } else {
+ format!("ws://{url}")
+ }
+}
+
impl Graph {
- /// Connect over WebSocket and sign in as the root user `user`.
+ /// Connect and sign in as the root user `user`. `url` is a WebSocket
+ /// server, `host:port` or `ws://`/`wss://` (TLS) `host:port`, or `mem://`
+ /// for the embedded in-memory engine (a fresh, private database for each
+ /// connection).
pub async fn connect(
url: &str,
ns: &str,
@@ -342,14 +356,15 @@ impl Graph {
.await
}
- /// Connect over WebSocket and sign in with `credentials`.
+ /// Connect to `url` (as [`Graph::connect`] takes it) and sign in with
+ /// `credentials`.
pub async fn connect_with_credentials(
url: &str,
ns: &str,
db_name: &str,
credentials: Credentials,
) -> Result<Self> {
- let db = Surreal::new::<Ws>(url).await.map_err(surreal_err)?;
+ let db = any::connect(endpoint(url)).await.map_err(surreal_err)?;
match credentials {
Credentials::Root { username, password } => {
db.signin(auth::Root { username, password }).await.map(drop)
@@ -399,7 +414,7 @@ impl Graph {
/// The underlying client, for queries of your own (Python's
/// `ConnectionFactory.acquire()`).
- pub fn client(&self) -> &Surreal<Client> {
+ pub fn client(&self) -> &Surreal<Any> {
&self.db
}
diff --git a/rust/sdk/cocoindex/src/lib.rs b/rust/sdk/cocoindex/src/lib.rs
index c8429d41..892f8e23 100644
--- a/rust/sdk/cocoindex/src/lib.rs
+++ b/rust/sdk/cocoindex/src/lib.rs
@@ -97,6 +97,7 @@
//! | `sqlite` | [`connectors::sqlite`] target | |
//! | `doris` | [`connectors::doris`] target (MySQL protocol + Stream Load) | |
//! | `surrealdb` | [`connectors::surrealdb`] target | |
+//! | `surrealdb_mem` | SurrealDB's embedded in-memory engine for [`connectors::surrealdb`] (`mem://`) | |
//! | `lancedb` | [`connectors::lancedb`] target (embedded) | |
//! | `qdrant` | [`connectors::qdrant`] target | `protoc` |
//! | `turbopuffer` | [`connectors::turbopuffer`] target | |
diff --git a/rust/sdk/cocoindex/tests/surrealdb_scenarios.rs b/rust/sdk/cocoindex/tests/surrealdb_scenarios.rs
index f903ac6d..75772a46 100644
--- a/rust/sdk/cocoindex/tests/surrealdb_scenarios.rs
+++ b/rust/sdk/cocoindex/tests/surrealdb_scenarios.rs
@@ -1,7 +1,10 @@
//! Edge-case scenarios for the SurrealDB target: relation updates, record id
//! forms, payload values, vectors, failed batches and recovery, out-of-band
-//! changes and chunk boundaries. Each test needs a SurrealDB server at
-//! `SURREALDB_URL` (default `127.0.0.1:8787`) and skips without one.
+//! changes and chunk boundaries. Each test runs on the SurrealDB server
+//! `SURREALDB_URL` names (signing in as `SURREALDB_USER`/`SURREALDB_PASS`,
+//! default `root`/`root`), else on the embedded in-memory engine (feature
+//! `surrealdb_mem`), else on a local server at `127.0.0.1:8787`, skipping
+//! when none answers.
#![cfg(feature = "surrealdb")]
use cocoindex::connectors::surrealdb::{self, ColumnDef, Graph, TableSchema, VectorIndexOptions};
@@ -9,19 +12,37 @@ use cocoindex::prelude::*;
cocoindex::context_key!(static GRAPH: Graph, key = "surrealdb_scenarios_graph");
-/// A fresh database on the server `SURREALDB_URL` names, plus an app on it.
+/// Without `SURREALDB_URL`: the embedded in-memory engine when the
+/// `surrealdb_mem` feature is on, else a local server (the tests skip when
+/// none answers).
+fn default_url() -> &'static str {
+ if cfg!(feature = "surrealdb_mem") {
+ "mem://"
+ } else {
+ "127.0.0.1:8787"
+ }
+}
+
+/// A fresh database, plus an app on it.
async fn scenario(tag: &str) -> Option<(Graph, App, tempfile::TempDir)> {
- let url = std::env::var("SURREALDB_URL").unwrap_or_else(|_| "127.0.0.1:8787".to_string());
+ let url = std::env::var("SURREALDB_URL").unwrap_or_else(|_| default_url().to_string());
let ns = std::env::var("SURREALDB_NS").unwrap_or_else(|_| "cocoindex".to_string());
- let user = std::env::var("SURREALDB_USER").unwrap_or_else(|_| "root".to_string());
- let pass = std::env::var("SURREALDB_PASS").unwrap_or_else(|_| "root".to_string());
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let db_name = format!("rust_sdk_surrealdb_{tag}_{}_{nanos}", std::process::id());
- let Ok(graph) = Graph::connect(&url, &ns, &db_name, &user, &pass).await else {
- eprintln!("skipping SurrealDB {tag} test; no local SurrealDB connection");
+ let credentials = if url.starts_with("mem://") {
+ // The embedded engine runs without authentication.
+ surrealdb::Credentials::None
+ } else {
+ surrealdb::Credentials::Root {
+ username: std::env::var("SURREALDB_USER").unwrap_or_else(|_| "root".to_string()),
+ password: std::env::var("SURREALDB_PASS").unwrap_or_else(|_| "root".to_string()),
+ }
+ };
+ let Ok(graph) = Graph::connect_with_credentials(&url, &ns, &db_name, credentials).await else {
+ eprintln!("skipping SurrealDB {tag} test; no SurrealDB connection");
return None;
};
let dir = tempfile::tempdir().unwrap();
diff --git a/rust/sdk/cocoindex/tests/surrealdb_target.rs b/rust/sdk/cocoindex/tests/surrealdb_target.rs
index b8f9bb80..b57bac7b 100644
--- a/rust/sdk/cocoindex/tests/surrealdb_target.rs
+++ b/rust/sdk/cocoindex/tests/surrealdb_target.rs
@@ -5,9 +5,33 @@ use cocoindex::prelude::*;
cocoindex::context_key!(static GRAPH: Graph, key = "surrealdb_smoke_graph");
+/// Without `SURREALDB_URL`: the embedded in-memory engine when the
+/// `surrealdb_mem` feature is on, else a local server (the tests skip when
+/// none answers).
+fn default_url() -> &'static str {
+ if cfg!(feature = "surrealdb_mem") {
+ "mem://"
+ } else {
+ "127.0.0.1:8787"
+ }
+}
+
+/// The server `SURREALDB_URL` names, else [`default_url`].
+fn surrealdb_url() -> String {
+ std::env::var("SURREALDB_URL").unwrap_or_else(|_| default_url().to_string())
+}
+
async fn try_graph(db_name: &str) -> Option<Graph> {
- let url = std::env::var("SURREALDB_URL").unwrap_or_else(|_| "127.0.0.1:8787".to_string());
+ let url = surrealdb_url();
let ns = std::env::var("SURREALDB_NS").unwrap_or_else(|_| "cocoindex".to_string());
+ if url.starts_with("mem://") {
+ // The embedded engine runs without authentication.
+ return Some(
+ Graph::connect_with_credentials(&url, &ns, db_name, surrealdb::Credentials::None)
+ .await
+ .unwrap(),
+ );
+ }
let user = std::env::var("SURREALDB_USER").unwrap_or_else(|_| "root".to_string());
let pass = std::env::var("SURREALDB_PASS").unwrap_or_else(|_| "root".to_string());
Graph::connect(&url, &ns, db_name, &user, &pass).await.ok()
@@ -939,11 +963,17 @@ async fn surrealdb_connects_with_a_database_user_when_available() {
std::process::id(),
chrono_like_timestamp()
);
+ let url = surrealdb_url();
+ if url.starts_with("mem://") {
+ // Each embedded connection is a database of its own, and signs in to
+ // nothing.
+ eprintln!("skipping SurrealDB credentials test; it needs a server");
+ return;
+ }
let Some(root) = try_graph(&db_name).await else {
eprintln!("skipping SurrealDB credentials test; no local SurrealDB connection");
return;
};
- let url = std::env::var("SURREALDB_URL").unwrap_or_else(|_| "127.0.0.1:8787".to_string());
let ns = std::env::var("SURREALDB_NS").unwrap_or_else(|_| "cocoindex".to_string());
root.client()
.query("DEFINE USER writer ON DATABASE PASSWORD 'writer-pass' ROLES OWNER")