Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(rust-sdk): SurrealDB, LanceDB and graph handles serialize to their stable key (#2739)
LJ π₯₯π΄492d968b2867
diff --git a/docs/src/content/docs/advanced_topics/memoization_keys.mdx b/docs/src/content/docs/advanced_topics/memoization_keys.mdxindex 9dc6976e..7a27817b 100644--- a/docs/src/content/docs/advanced_topics/memoization_keys.mdx+++ b/docs/src/content/docs/advanced_topics/memoization_keys.mdx@@ -214,7 +214,7 @@ It works for every parameter kind:`memo_key` is validated at decoration time: unknown parameter names raise `ValueError`, and values that are neither callable nor `None` raise `TypeError`. In Rust the macro checks the names at compile time. A transform also suppresses the argument type's `memo_state` validation; use a newtype when the freshness check must stay.-**Target handles in Rust.** `DirTarget`, `TableTarget` and the other target handles are `Clone` but not `MemoInput`: a target handle is where output goes, not an input of the computation. Skip it in the memo key:+**Target handles in Rust.** A target handle is where output goes, not an input of the computation, so it is not `MemoInput`. `DirTarget` and the Postgres, SQLite, Doris, SurrealDB, LanceDB, Neo4j and FalkorDB table and relation targets are `Serialize` instead: as an argument of a memoized function or of `mount!`, `use_mount!` or `mount_each!`, one is keyed by its stable key, as in Python. The other connectors' handles are only `Clone`. Skip those in the memo key; you can skip any handle the same way:{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (target_state_of_nested_memo_survives_outer_memo_hit) */}```rustdiff --git a/docs/src/content/docs/programming_guide/serialization.mdx b/docs/src/content/docs/programming_guide/serialization.mdxindex e5ac3b9c..a9598f71 100644--- a/docs/src/content/docs/programming_guide/serialization.mdx+++ b/docs/src/content/docs/programming_guide/serialization.mdx@@ -164,7 +164,7 @@ If you see this error after upgrading, previously cached data may reference typeThe Rust SDK has no pickle path and no registration: three traits cover what this page describes for Python.- **Memoized return values** are stored through `serde::Serialize` and read back through `serde::Deserialize`.-- **Memo keys** (function arguments, `deps` values, change-detected context values) are fingerprinted through the `MemoInput` trait. Derive it with `#[derive(cocoindex::MemoInput)]`; every field is handled recursively, so the type needs no `Serialize`. It composes through `Option`, sequences, tuples, maps, sets, `Box` and `Arc`. `uuid::Uuid` and `serde_json::Value` are always available; the `chrono` and `rust_decimal` features add those leaf types, and a connector feature enables the leaf features it needs. Wrap another third-party type in a newtype when it appears inside derived data. Target handles are `Clone` but not `MemoInput`: a memoized function that takes one skips it with `memo_key(table = skip)` (see [Function](./function#customizing-data-fingerprinting)).+- **Memo keys** (function arguments, `deps` values, change-detected context values) are fingerprinted through the `MemoInput` trait. Derive it with `#[derive(cocoindex::MemoInput)]`; every field is handled recursively, so the type needs no `Serialize`. It composes through `Option`, sequences, tuples, maps, sets, `Box` and `Arc`. `uuid::Uuid` and `serde_json::Value` are always available; the `chrono` and `rust_decimal` features add those leaf types, and a connector feature enables the leaf features it needs. Wrap another third-party type in a newtype when it appears inside derived data. A type with only `Serialize` is keyed by its serialized value; a target handle that is `Serialize` is keyed that way, by its stable key. A memoized function skips any other handle with `memo_key(table = skip)` (see [Function](./function#customizing-data-fingerprinting) and [target handles](../advanced_topics/memoization_keys)).- **Connector rows** are `serde::Serialize` structs with `#[derive(SchemaFields)]`. The connector's `TableSchema::from_row::<Row>(primary_key)` derives the columns from the struct, the Rust form of Python's `TableSchema.from_class`: an `Option<T>` field is a nullable column, every other field is `NOT NULL`.{/* Rust: rust/sdk/cocoindex/tests/schema_from_row.rs (`postgres_from_row_matches_explicit_schema`), rust/sdk/SHOWCASE.md "Derive connector schemas from row types" (verified) */}diff --git a/examples/rust/docs_to_knowledge_graph/src/main.rs b/examples/rust/docs_to_knowledge_graph/src/main.rsindex 9871597f..06c2f3a3 100644--- a/examples/rust/docs_to_knowledge_graph/src/main.rs+++ b/examples/rust/docs_to_knowledge_graph/src/main.rs@@ -301,21 +301,19 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {files.len(),sourcedir.display());- let docs: Vec<DocTriples> = ctx- .use_mount_each(- files,- |(key, _)| format!("file/{key}"),- move |ctx, (_, file)| {- let document_table = document_table.clone();- async move { process_file(&ctx, file, document_table).await }- },- )- .await?;+ let docs: Vec<DocTriples> = use_mount_each!(files, |file| {+ process_file(ctx, file, document_table.clone())+ })+ .await?;// --- Phase 2: build the concept graph ---- ctx.mount(&"build_graph", move |ctx| async move {- build_graph(&ctx, docs, entity_table, relationship_rel, mention_rel).await- })+ mount!(build_graph(+ ctx,+ docs,+ entity_table,+ relationship_rel,+ mention_rel+ )).await?.ready().awaitdiff --git a/examples/rust/product_recommendation/src/main.rs b/examples/rust/product_recommendation/src/main.rsindex 48ddc316..dc8f7f23 100644--- a/examples/rust/product_recommendation/src/main.rs+++ b/examples/rust/product_recommendation/src/main.rs@@ -296,28 +296,19 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {files.len(),sourcedir.display());- let products: Vec<ProductTaxonomies> = ctx- .use_mount_each(- files,- |(key, _)| format!("file/{key}"),- move |ctx, (_, file)| {- let product_table = product_table.clone();- async move { process_file(&ctx, file, product_table).await }- },- )- .await?;+ let products: Vec<ProductTaxonomies> = use_mount_each!(files, |file| {+ process_file(ctx, file, product_table.clone())+ })+ .await?;// --- Phase 2: build the graph ---- ctx.mount(&"build_graph", move |ctx| async move {- build_graph(- &ctx,- products,- taxonomy_table,- product_taxonomy_rel,- complementary_rel,- )- .await- })+ mount!(build_graph(+ ctx,+ products,+ taxonomy_table,+ product_taxonomy_rel,+ complementary_rel+ )).await?.ready().awaitdiff --git a/rust/sdk/cocoindex/src/connectors/lancedb.rs b/rust/sdk/cocoindex/src/connectors/lancedb.rsindex ee3769e8..f0c1fc00 100644--- a/rust/sdk/cocoindex/src/connectors/lancedb.rs+++ b/rust/sdk/cocoindex/src/connectors/lancedb.rs@@ -391,11 +391,19 @@ fn lancedb_column_def(field: &crate::row_schema::SchemaField) -> Result<ColumnDe/// A declarative LanceDB table target β a handle to declare rows on. See the/// [module docs](self).-#[derive(Clone)]+///+/// As a `mount_each!` / `use_mount!` or memoized function argument it+/// fingerprints by its stable key, the database key and table name; the schema,+/// managed-by flag, and runtime provider are not part of the identity.+#[derive(Clone, Serialize)]pub struct LanceTableTarget {+ db_key: Arc<str>,table_name: Arc<str>,+ #[serde(skip)]table_schema: TableSchema,+ #[serde(skip)]managed_by: ManagedBy,+ #[serde(skip)]rows: TargetStateProvider<RowState>,}@@ -494,6 +502,7 @@ pub fn declare_table_target_with_options(RowHandler::new(db.name().to_string(), spec.clone(), BTreeSet::new()),)?;Ok(LanceTableTarget {+ db_key: Arc::from(db.name()),table_name: Arc::from(table_name),table_schema: spec.table_schema,managed_by: spec.managed_by,@@ -535,6 +544,7 @@ pub async fn mount_table_target_with_options(let spec = target_state.value().clone();let rows = mount_target::<TableSpec, RowState>(ctx, target_state).await?;Ok(LanceTableTarget {+ db_key: Arc::from(db.name()),table_name: Arc::from(table_name),table_schema: spec.table_schema,managed_by: spec.managed_by,diff --git a/rust/sdk/cocoindex/src/connectors/surrealdb.rs b/rust/sdk/cocoindex/src/connectors/surrealdb.rsindex 4c8704ce..28b6df9a 100644--- a/rust/sdk/cocoindex/src/connectors/surrealdb.rs+++ b/rust/sdk/cocoindex/src/connectors/surrealdb.rs@@ -442,11 +442,19 @@ fn json_object_keys(info: Option<&JsonValue>, field: &str) -> Vec<String> {// Target handles// ----------------------------------------------------------------------------#[derive(Clone)]+/// A SurrealDB table target β a handle to declare records on.+///+/// As a `mount_each!` / `use_mount!` or memoized function argument it+/// fingerprints by its stable key, the graph key and table name; the managed-by+/// flag and runtime provider are not part of the identity.+#[derive(Clone, Serialize)]pub struct TableTarget {+ graph_key: Arc<str>,table_name: Arc<str>,+ #[serde(skip)]managed_by: ManagedBy,/// The table's record provider; also carries its vector-index attachment.+ #[serde(skip)]records: TargetStateProvider<RecordState>,}@@ -570,13 +578,24 @@ impl Default for VectorIndexOptions {}}-#[derive(Clone)]+/// A SurrealDB relation target β a handle to declare relations on.+///+/// As a `mount_each!` / `use_mount!` or memoized function argument it+/// fingerprints by its stable key, the graph key and table name; the endpoints+/// and runtime provider are not part of the identity.+#[derive(Clone, Serialize)]pub struct RelationTarget {+ graph_key: Arc<str>,table_name: Arc<str>,+ #[serde(skip)]from_tables: Arc<[String]>,+ #[serde(skip)]to_tables: Arc<[String]>,+ #[serde(skip)]from_table: Option<Arc<str>>,+ #[serde(skip)]to_table: Option<Arc<str>>,+ #[serde(skip)]records: TargetStateProvider<RecordState>,}@@ -697,20 +716,30 @@ fn relation_key_part(value: &str) -> String {format!("{}:{value};", value.len())}-fn table_handle(spec: TableSpec, records: TargetStateProvider<RecordState>) -> TableTarget {+fn table_handle(+ graph: &ContextKey<Graph>,+ spec: TableSpec,+ records: TargetStateProvider<RecordState>,+) -> TableTarget {TableTarget {+ graph_key: Arc::from(graph.name()),table_name: Arc::from(spec.table_name),managed_by: spec.managed_by,records,}}-fn relation_handle(spec: TableSpec, records: TargetStateProvider<RecordState>) -> RelationTarget {+fn relation_handle(+ graph: &ContextKey<Graph>,+ spec: TableSpec,+ records: TargetStateProvider<RecordState>,+) -> RelationTarget {let from_names = spec.from_tables;let to_names = spec.to_tables;let from_table = (from_names.len() == 1).then(|| Arc::from(from_names[0].clone()));let to_table = (to_names.len() == 1).then(|| Arc::from(to_names[0].clone()));RelationTarget {+ graph_key: Arc::from(graph.name()),table_name: Arc::from(spec.table_name),from_table,to_table,@@ -908,7 +937,7 @@ pub fn declare_table_target_with_schema_and_options(let ts = table_target_with_schema_and_options(ctx, graph, table_name, table_schema, options)?;let spec = ts.value().clone();let records = declare_target_state_with_child::<TableSpec, RecordState>(ctx, ts)?;- Ok(table_handle(spec, records))+ Ok(table_handle(graph, spec, records))}/// Declare a SurrealDB relation target in the **current** component and return@@ -954,7 +983,7 @@ pub fn declare_relation_target_many_with_options()?;let spec = ts.value().clone();let records = declare_target_state_with_child::<TableSpec, RecordState>(ctx, ts)?;- Ok(relation_handle(spec, records))+ Ok(relation_handle(graph, spec, records))}/// Declare an unconstrained SurrealDB relation target in the current component.@@ -981,7 +1010,7 @@ pub fn declare_relation_target_unconstrained_with_options(let ts = relation_target_unconstrained_with_options(ctx, graph, table_name, options)?;let spec = ts.value().clone();let records = declare_target_state_with_child::<TableSpec, RecordState>(ctx, ts)?;- Ok(relation_handle(spec, records))+ Ok(relation_handle(graph, spec, records))}// ---------------------------------------------------------------------------@@ -1038,7 +1067,7 @@ pub async fn mount_table_target_with_schema_and_options(let ts = table_target_with_schema_and_options(ctx, graph, table_name, table_schema, options)?;let spec = ts.value().clone();let records = mount_target::<TableSpec, RecordState>(ctx, ts).await?;- Ok(table_handle(spec, records))+ Ok(table_handle(graph, spec, records))}pub async fn mount_relation_target(@@ -1120,7 +1149,7 @@ pub async fn mount_relation_target_many_with_options()?;let spec = ts.value().clone();let records = mount_target::<TableSpec, RecordState>(ctx, ts).await?;- Ok(relation_handle(spec, records))+ Ok(relation_handle(graph, spec, records))}pub async fn mount_relation_target_unconstrained(@@ -1146,7 +1175,7 @@ pub async fn mount_relation_target_unconstrained_with_options(let ts = relation_target_unconstrained_with_options(ctx, graph, table_name, options)?;let spec = ts.value().clone();let records = mount_target::<TableSpec, RecordState>(ctx, ts).await?;- Ok(relation_handle(spec, records))+ Ok(relation_handle(graph, spec, records))}// ---------------------------------------------------------------------------diff --git a/rust/sdk/cocoindex/src/cypher_graph.rs b/rust/sdk/cocoindex/src/cypher_graph.rsindex 7dbf6ea0..f8b3641d 100644--- a/rust/sdk/cocoindex/src/cypher_graph.rs+++ b/rust/sdk/cocoindex/src/cypher_graph.rs@@ -381,17 +381,24 @@ fn cypher_type(logical_type: LogicalType) -> String {name.to_string()}-#[derive(Clone)]+/// As a `mount_each!` / `use_mount!` or memoized function argument a handle+/// fingerprints by its stable key, the graph key and table name; the rest of it+/// is not part of the identity.+#[derive(Clone, Serialize)]pub(crate) struct TableTarget {/// The `ContextKey` name of the graph the table lives in.graph_key: Arc<str>,table_name: Arc<str>,+ #[serde(skip)]primary_key: Arc<str>,/// The connector's static root provider; carries the index attachments.+ #[serde(skip)]table_provider: TargetStateProvider<TableSpec>,+ #[serde(skip)]provider: TargetStateProvider<RecordState>,/// Field -> declared name of the vector indexes declared through this/// target: the database keeps one vector index per label and field.+ #[serde(skip)]vector_index_names: Arc<Mutex<BTreeMap<String, String>>>,}@@ -497,12 +504,20 @@ impl TableTarget {}}-#[derive(Clone)]+/// Fingerprints by its stable key, like [`TableTarget`].+#[derive(Clone, Serialize)]pub(crate) struct RelationTarget {+ /// The `ContextKey` name of the graph the relation lives in.+ graph_key: Arc<str>,+ relation_name: Arc<str>,/// The property that keys the relation's records.+ #[serde(skip)]primary_key: Arc<str>,+ #[serde(skip)]from_table: TableEndpoint,+ #[serde(skip)]to_table: TableEndpoint,+ #[serde(skip)]provider: TargetStateProvider<RecordState>,}@@ -778,6 +793,7 @@ fn table_handle(}fn relation_handle(+ graph_key: &str,spec: &TableSpec,child: TargetStateProvider<RecordState>,) -> Result<RelationTarget> {@@ -788,6 +804,8 @@ fn relation_handle()));};Ok(RelationTarget {+ graph_key: Arc::from(graph_key),+ relation_name: Arc::from(spec.table_name.as_str()),primary_key: Arc::from(spec.primary_key.as_str()),from_table: from_table.clone(),to_table: to_table.clone(),@@ -843,7 +861,7 @@ pub(crate) async fn mount_relation_target_with_options<C: CypherExecutor>()?;let spec = ts.value().clone();let child = mount_target(ctx, ts).await?;- relation_handle(&spec, child)+ relation_handle(graph.name(), &spec, child)}pub(crate) fn declare_relation_target_with_options<C: CypherExecutor>(@@ -866,7 +884,7 @@ pub(crate) fn declare_relation_target_with_options<C: CypherExecutor>()?;let spec = ts.value().clone();let child = declare_target_state_with_child::<TableSpec, RecordState>(ctx, ts)?;- relation_handle(&spec, child)+ relation_handle(graph.name(), &spec, child)}/// Resolve the graph provided under `graph_key` in the host context.@@ -1925,8 +1943,9 @@ pub(crate) fn validate_ident(name: &str, what: &str) -> Result<()> {/// changes are applied, including on `App::drop_state`.macro_rules! graph_target_api {($graph:ty) => {- /// A node-table target. Cheap to clone.- #[derive(Clone)]+ /// A node-table target. Cheap to clone. Serializes to its stable key, so+ /// it can be a `mount_each!` / `use_mount!` or memoized function argument.+ #[derive(Clone, ::serde::Serialize)]pub struct TableTarget($crate::cypher_graph::TableTarget);impl TableTarget {@@ -1987,8 +2006,9 @@ macro_rules! graph_target_api {}}- /// A relation target. Cheap to clone.- #[derive(Clone)]+ /// A relation target. Cheap to clone. Serializes to its stable key, so+ /// it can be a `mount_each!` / `use_mount!` or memoized function argument.+ #[derive(Clone, ::serde::Serialize)]pub struct RelationTarget($crate::cypher_graph::RelationTarget);impl RelationTarget {@@ -3500,6 +3520,48 @@ mod tests {.map(|_| ())}+ /// A handle's memo identity is its stable key: the graph key and the name,+ /// and not the schema or the runtime providers.+ #[tokio::test]+ async fn a_handle_serializes_to_its_stable_key() {+ let tmp = tempfile::tempdir().unwrap();+ let graph = RecordingGraph::new("neo4j");+ let app = recording_app(&graph, tmp.path()).await;+ app.run(|ctx| async move {+ let options = ManagedTargetOptions::default;+ let person = mount_table_target_with_options(+ &ctx,+ &RECORDING,+ "Person",+ TableSchema::schemaless("id")?,+ options(),+ )+ .await?;+ let knows = mount_relation_target_with_options(+ &ctx,+ &RECORDING,+ "KNOWS",+ &person,+ &person,+ TableSchema::schemaless("id")?,+ options(),+ )+ .await?;+ let graph_key = RECORDING.name();+ assert_eq!(+ serde_json::to_value(&person).unwrap(),+ serde_json::json!({ "graph_key": graph_key, "table_name": "Person" }),+ );+ assert_eq!(+ serde_json::to_value(&knows).unwrap(),+ serde_json::json!({ "graph_key": graph_key, "relation_name": "KNOWS" }),+ );+ Ok(())+ })+ .await+ .unwrap();+ }+fn vector_index_statements(graph: &RecordingGraph) -> Vec<String> {graph.statements()diff --git a/rust/sdk/cocoindex/tests/lancedb_target.rs b/rust/sdk/cocoindex/tests/lancedb_target.rsindex 12e861d6..92c15a33 100644--- a/rust/sdk/cocoindex/tests/lancedb_target.rs+++ b/rust/sdk/cocoindex/tests/lancedb_target.rs@@ -1408,3 +1408,67 @@ async fn lancedb_from_row_resolves_vector_from_context_provider() -> Result<()>assert_eq!(table.count_rows(None).await.unwrap(), 1);Ok(())}++static TARGET_ARG_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);++/// A LanceDB handle as a mount argument: the component is keyed by the id and+/// the table's stable key.+#[cocoindex::function]+async fn declare_row_in_component(+ ctx: &Ctx,+ id: i64,+ table: lancedb::LanceTableTarget,+) -> Result<()> {+ TARGET_ARG_CALLS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ table.declare_row(+ ctx,+ &Row {+ id,+ text: format!("doc{id}"),+ embedding: vec![1.0, 0.0, 0.0],+ },+ )+}++#[tokio::test]+async fn lancedb_table_target_is_a_mount_argument_keyed_by_its_table() -> Result<()> {+ let tempdir = tempfile::tempdir().unwrap();+ let db = LanceDatabase::connect(tempdir.path().join("data").to_str().unwrap()).await?;+ let app = Environment::builder()+ .db_path(tempdir.path().join(".cocoindex_db"))+ .provide_key(&DB, db.clone())+ .build()+ .await?+ .app("LanceTargetArgTest")+ .await?;+ let calls = || TARGET_ARG_CALLS.load(std::sync::atomic::Ordering::SeqCst);+ let run = |table_name: &'static str| {+ let app = app.clone();+ async move {+ app.run(move |ctx| async move {+ let table = lancedb::mount_table_target(&ctx, &DB, table_name, schema()).await?;+ cocoindex::use_mount_each!(vec![("1".to_string(), 1_i64)], |id| {+ declare_row_in_component(ctx, id, table.clone())+ })+ .await?;+ Ok(())+ })+ .await+ }+ };++ run(TABLE).await?;+ assert_eq!(calls(), 1);+ assert_eq!(row_count(&db).await, 1);++ // The same table: the unchanged child is skipped, and its row stays.+ run(TABLE).await?;+ assert_eq!(calls(), 1, "same table: the child is skipped");+ assert_eq!(row_count(&db).await, 1);++ // Another table is another key: the child runs again and writes there.+ run(HALF_TABLE).await?;+ assert_eq!(calls(), 2, "another table: the child runs");+ assert!(table_exists(&db, HALF_TABLE).await);+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/surrealdb_target.rs b/rust/sdk/cocoindex/tests/surrealdb_target.rsindex c03f9233..b8f9bb80 100644--- a/rust/sdk/cocoindex/tests/surrealdb_target.rs+++ b/rust/sdk/cocoindex/tests/surrealdb_target.rs@@ -980,3 +980,54 @@ async fn surrealdb_connects_with_a_database_user_when_available() {.await;assert!(denied.is_err());}++/// Both SurrealDB handles as mount arguments, keyed by their stable keys.+#[cocoindex::function]+async fn declare_edge_in_component(+ ctx: &Ctx,+ person: surrealdb::TableTarget,+ knows: surrealdb::RelationTarget,+) -> Result<()> {+ for name in ["alice", "bob"] {+ person.declare_record(ctx, name, &serde_json::json!({ "name": name }))?;+ }+ knows.declare_relation(ctx, "alice", "bob")+}++#[tokio::test]+async fn surrealdb_handles_are_mount_arguments_when_available() {+ let db_name = format!(+ "rust_sdk_surrealdb_handle_args_{}_{}",+ std::process::id(),+ chrono_like_timestamp()+ );+ let Some(graph) = try_graph(&db_name).await else {+ eprintln!("skipping SurrealDB handle argument test; no local SurrealDB connection");+ return;+ };+ let dir = tempfile::tempdir().unwrap();+ let app = Environment::builder()+ .db_path(dir.path().join("lmdb"))+ .provide_key(&GRAPH, graph.clone())+ .build()+ .await+ .unwrap()+ .app("surrealdb_handle_args")+ .await+ .unwrap();+ for _ in 0..2 {+ app.run(|ctx| async move {+ let person = surrealdb::mount_table_target(&ctx, &GRAPH, "person").await?;+ let knows =+ surrealdb::mount_relation_target(&ctx, &GRAPH, "knows", &person, &person).await?;+ cocoindex::mount!(declare_edge_in_component(ctx, person, knows))+ .await?+ .ready()+ .await+ })+ .await+ .unwrap();+ assert_eq!(graph.count("person").await.unwrap(), 2);+ assert_eq!(graph.count("knows").await.unwrap(), 1);+ }+}