Skip to content

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

perf(rust-sdk): clone-free memo calls, background streaming mount_each, typed mount keys (#2732)

LJ πŸ₯₯🌴1f351f53d3a7
diff --git a/benchmarks/file_summarization/rust/src/main.rs b/benchmarks/file_summarization/rust/src/main.rs
index c448f089..59a20d27 100644
--- a/benchmarks/file_summarization/rust/src/main.rs
+++ b/benchmarks/file_summarization/rust/src/main.rs
@@ -254,7 +254,7 @@ async fn main() -> cocoindex::Result<()> {
.run(move |ctx| async move {
let collections = discover_collections(&dataset)?;
let summaries: Vec<CollectionSummary> = ctx
- .mount_each(collections, |collection| collection.name.clone(), {
+ .use_mount_each(collections, |collection| collection.name.clone(), {
let scenario = scenario.clone();
move |project_ctx, collection| {
let scenario = scenario.clone();
@@ -323,7 +323,7 @@ async fn process_collection(
.fetch_add(files.len() as u64, Ordering::Relaxed);
let extracted: Vec<Vec<SectionInput>> = ctx
- .mount_each(
+ .use_mount_each(
files,
|file| file.key(),
|file_ctx, file| async move {
diff --git a/docs/src/content/docs/advanced_topics/concurrency_control.mdx b/docs/src/content/docs/advanced_topics/concurrency_control.mdx
index 129207ed..a4467963 100644
--- a/docs/src/content/docs/advanced_topics/concurrency_control.mdx
+++ b/docs/src/content/docs/advanced_topics/concurrency_control.mdx
@@ -52,9 +52,7 @@ You can also set the limit via the `COCOINDEX_MAX_INFLIGHT_COMPONENTS` environme
export COCOINDEX_MAX_INFLIGHT_COMPONENTS=4
```
-**Precedence:** `AppConfig` value > environment variable > default (1024).
-
-The Rust SDK reads no `COCOINDEX_MAX_INFLIGHT_COMPONENTS` variable: set the limit on the builder.
+**Precedence:** `AppConfig` value (in Rust, the builder's `max_inflight_components`) > environment variable > default (1024). Rust reads the variable when an app is created.
## Nested mounts: a parent lends its slot
diff --git a/docs/src/content/docs/advanced_topics/timeouts.mdx b/docs/src/content/docs/advanced_topics/timeouts.mdx
index 270cf093..47426bf6 100644
--- a/docs/src/content/docs/advanced_topics/timeouts.mdx
+++ b/docs/src/content/docs/advanced_topics/timeouts.mdx
@@ -113,8 +113,8 @@ The same rule holds in the Rust SDK, where the deadline is carried by the `Ctx`:
| --- | --- |
| `UpdateOptions { timeout: Some(..), .. }` on `app.update_with_options(..)` | The root processor's `Ctx` carries the timeout (see [Time-boxing a whole update](#time-boxing-a-whole-update-programmatic-callers)). |
| A `#[cocoindex::function]` called with a scoped `Ctx` | Sees the scoped deadline. A call made with the unscoped `Ctx` does not. |
-| `scoped.scope(..)` / `use_mount!` / `scoped.mount_each(..)` | The child inherits the deadline because the parent waits for the child's result. In Rust, `mount_each` is a foreground mount that returns the children's values, so its children inherit the deadline too. |
-| `scoped.mount(..)` / `mount!` / `auto_refresh` / `mount_live` | The child's `Ctx` carries no deadline. The caller's own wait on `handle.ready()` is bounded by the caller's deadline. |
+| `scoped.scope(..)` / `use_mount!` / `scoped.use_mount_each(..)` / `use_mount_each!` | The child inherits the deadline because the parent waits for the child's result. |
+| `scoped.mount(..)` / `mount!` / `scoped.mount_each(..)` / `mount_each!` / `auto_refresh` / `mount_live` | The child's `Ctx` carries no deadline. The caller's own wait on `handle.ready()` is bounded by the caller's deadline. |
| `scoped.map(items, ..)` | Item tasks see the deadline. Already-started items run to completion before the error is returned. |
| Batched function body | A physical batch does not inherit any individual caller's deadline. |
| Target writes and connector sink calls | Do not inherit the processor deadline. |
diff --git a/docs/src/content/docs/connectors/bigquery.mdx b/docs/src/content/docs/connectors/bigquery.mdx
index 26ba48ef..dc5fee53 100644
--- a/docs/src/content/docs/connectors/bigquery.mdx
+++ b/docs/src/content/docs/connectors/bigquery.mdx
@@ -410,7 +410,7 @@ let table = bigquery::mount_table_target(
schema,
)
.await?;
-let rows = mount_each!(orders, |order| process_order(ctx, order)).await?;
+let rows = use_mount_each!(orders, |order| process_order(ctx, order)).await?;
for row in &rows {
table.declare_row(&ctx, row)?;
}
diff --git a/docs/src/content/docs/connectors/google_drive.mdx b/docs/src/content/docs/connectors/google_drive.mdx
index 11478866..b1bcd560 100644
--- a/docs/src/content/docs/connectors/google_drive.mdx
+++ b/docs/src/content/docs/connectors/google_drive.mdx
@@ -170,7 +170,7 @@ async for key, file in source.items():
```rust
let files = source.list_files().await?;
-let rows_by_file = mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {
+let rows_by_file = use_mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {
process_file(ctx, file)
})
.await?;
diff --git a/docs/src/content/docs/connectors/kafka.mdx b/docs/src/content/docs/connectors/kafka.mdx
index 1b67cab1..a3712309 100644
--- a/docs/src/content/docs/connectors/kafka.mdx
+++ b/docs/src/content/docs/connectors/kafka.mdx
@@ -780,7 +780,7 @@ async fn index(producer: KafkaProducer, topic: String) -> Result<()> {
)?;
let files = cocoindex::resources::fs::walk_items("./data", &["**/*.csv"])?;
- let per_file = mount_each!(files, |file| process_csv(ctx, file)).await?;
+ let per_file = use_mount_each!(files, |file| process_csv(ctx, file)).await?;
for messages in &per_file {
for (key, value) in messages {
diff --git a/docs/src/content/docs/connectors/lancedb.mdx b/docs/src/content/docs/connectors/lancedb.mdx
index 7411a671..0c5e1c29 100644
--- a/docs/src/content/docs/connectors/lancedb.mdx
+++ b/docs/src/content/docs/connectors/lancedb.mdx
@@ -773,7 +773,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
let table = lancedb::mount_table_target(&ctx, &DB, TABLE, doc_embedding_schema()?).await?;
let files = walk_items(&sourcedir, &["**/*.md"])?;
- let rows_by_file = mount_each!(files, |file| process_file(ctx, file)).await?;
+ let rows_by_file = use_mount_each!(files, |file| process_file(ctx, file)).await?;
for rows in &rows_by_file {
for row in rows {
diff --git a/docs/src/content/docs/connectors/postgres.mdx b/docs/src/content/docs/connectors/postgres.mdx
index 8703b9fa..18e3b715 100644
--- a/docs/src/content/docs/connectors/postgres.mdx
+++ b/docs/src/content/docs/connectors/postgres.mdx
@@ -294,7 +294,7 @@ async fn app_main(ctx: Ctx) -> Result<()> {
let source_db = ctx.get_key(&SOURCE_DB)?;
let products: Vec<SourceProduct> = postgres::read_table(source_db, "source_products").await?;
- let outputs = mount_each!(
+ let outputs = use_mount_each!(
products
.into_iter()
.map(|p| (format!("{}|{}", p.product_category, p.product_name), p)),
diff --git a/docs/src/content/docs/connectors/qdrant.mdx b/docs/src/content/docs/connectors/qdrant.mdx
index acd27e05..5663c6ec 100644
--- a/docs/src/content/docs/connectors/qdrant.mdx
+++ b/docs/src/content/docs/connectors/qdrant.mdx
@@ -866,7 +866,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
.await?;
let files = walk_items(&sourcedir, &["**/*.md"])?;
- let points_by_file = mount_each!(files, |file| process_file(ctx, file)).await?;
+ let points_by_file = use_mount_each!(files, |file| process_file(ctx, file)).await?;
for points in &points_by_file {
for p in points {
diff --git a/docs/src/content/docs/connectors/snowflake.mdx b/docs/src/content/docs/connectors/snowflake.mdx
index 80c1d43f..ec0db4aa 100644
--- a/docs/src/content/docs/connectors/snowflake.mdx
+++ b/docs/src/content/docs/connectors/snowflake.mdx
@@ -427,7 +427,7 @@ let table = snowflake::mount_table_target_with_options(
},
)
.await?;
-let rows = mount_each!(orders, |order| process_order(ctx, order)).await?;
+let rows = use_mount_each!(orders, |order| process_order(ctx, order)).await?;
for row in &rows {
table.declare_row(&ctx, row)?;
}
diff --git a/docs/src/content/docs/connectors/turbopuffer.mdx b/docs/src/content/docs/connectors/turbopuffer.mdx
index 840d5914..bc2d741b 100644
--- a/docs/src/content/docs/connectors/turbopuffer.mdx
+++ b/docs/src/content/docs/connectors/turbopuffer.mdx
@@ -560,7 +560,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf, namespace: String) -> Result<()>
.await?;
let files = walk_items(&sourcedir, &["**/*.md"])?;
- let rows_by_file = mount_each!(files, |file| process_file(ctx, file)).await?;
+ let rows_by_file = use_mount_each!(files, |file| process_file(ctx, file)).await?;
for rows in &rows_by_file {
for r in rows {
diff --git a/docs/src/content/docs/programming_guide/processing_component.mdx b/docs/src/content/docs/programming_guide/processing_component.mdx
index 8cbbbe30..2ba629bd 100644
--- a/docs/src/content/docs/programming_guide/processing_component.mdx
+++ b/docs/src/content/docs/programming_guide/processing_component.mdx
@@ -79,13 +79,14 @@ And two sugar APIs that simplify common patterns:
See also [`map()`](#using-cocoindex-map-to-apply-transformations) for a utility API that operates within a component without creating new ones.
-The Rust SDK has each API in two forms. The macros `mount!`, `use_mount!` and `mount_each!` take a `#[cocoindex::function]` call, substitute the child's `&Ctx` for its first argument, and fingerprint the function's logic and arguments so an unchanged child is skipped. The methods `ctx.mount`, `ctx.scope` and `ctx.mount_each` take a key and a closure, and always run it. `ctx.mount_each_live` is `mount_each` for a live source. The table maps the names:
+The Rust SDK has each API in two forms. The macros `mount!`, `use_mount!`, `mount_each!` and `use_mount_each!` take a `#[cocoindex::function]` call, substitute the child's `&Ctx` for its first argument, and fingerprint the function's logic and arguments so an unchanged child is skipped. The methods `ctx.mount`, `ctx.scope`, `ctx.mount_each` and `ctx.use_mount_each` take a key and a closure, and always run it. A key is a string or any other `IntoStableKey`: an integer, a UUID, bytes or a `StableKey`. `ctx.mount_each_live` is `mount_each` for a live source. The table maps the names:
| Python | Rust macro | Rust method |
|--------|------------|-------------|
| `coco.mount(fn, ...)` | `mount!(fn(ctx, ...))` | `ctx.mount(&key, \|ctx\| async move { ... })` |
| `coco.use_mount(fn, ...)` | `use_mount!(fn(ctx, ...))` | `ctx.scope(&key, \|ctx\| async move { ... })` |
-| `coco.mount_each(fn, items, ...)` | `mount_each!(items, \|item\| fn(ctx, item, ...))` | `ctx.mount_each(items, key_fn, \|ctx, item\| async move { ... })`, `ctx.mount_each_live(&key, feed, ...)` |
+| `coco.mount_each(fn, items, ...)` | `mount_each!(items, \|item\| fn(ctx, item, ...))` | `ctx.mount_each(items, key_fn, \|ctx, item\| async move { ... })`, `ctx.mount_each_stream(stream, ...)`, `ctx.mount_each_live(&key, feed, ...)` |
+| β€” | `use_mount_each!(items, \|item\| fn(ctx, item, ...))` | `ctx.use_mount_each(items, key_fn, \|ctx, item\| async move { ... })` |
| `coco.mount_target(target)` | β€” | `mount_target(&ctx, target_state)`, or a connector's `mount_*_target` |
| `coco.map(fn, items, ...)` | β€” | `ctx.map(items, async \|item\| { ... })` |
@@ -291,7 +292,7 @@ handle = await coco.mount_each(process_file, files.items(), target)
await handle.ready() # waits until every per-item component is ready
```
-Rust differs here: `mount_each!` is a foreground mount. It waits for every child and returns their values as a `Vec`, so there is no handle. `ctx.mount_each` returns the values the same way. `ctx.mount_each_live` returns once the feed's first scan is mounted and ready; in live mode its children keep reacting in the background.
+Rust works the same way: `mount_each!` and `ctx.mount_each` mount the children in the background as the items are read, and return one `ComponentMountHandle` whose `ready()` waits for all of them. For per-item values, Rust also has the foreground forms `use_mount_each!` and `ctx.use_mount_each`, which wait for every child and return their values as a `Vec` in input order. `ctx.mount_each_live` returns once the feed's first scan is mounted and ready; in live mode its children keep reacting in the background.
If you want per-item results without creating components, use [`map()`](#using-cocoindex-map-to-apply-transformations).
diff --git a/examples/rust/azure_blob_embedding/src/main.rs b/examples/rust/azure_blob_embedding/src/main.rs
index f37d2ef8..1c6907f1 100644
--- a/examples/rust/azure_blob_embedding/src/main.rs
+++ b/examples/rust/azure_blob_embedding/src/main.rs
@@ -124,7 +124,7 @@ async fn app_main(ctx: Ctx, prefix: String) -> Result<()> {
client.container_name()
);
- let rows_by_file = mount_each!(
+ let rows_by_file = use_mount_each!(
files.into_iter().map(|f| (f.key(), f)),
|file| process_file(ctx, file)
)
diff --git a/examples/rust/bigquery_target/src/main.rs b/examples/rust/bigquery_target/src/main.rs
index cf5c9ce4..405c86ff 100644
--- a/examples/rust/bigquery_target/src/main.rs
+++ b/examples/rust/bigquery_target/src/main.rs
@@ -172,7 +172,7 @@ async fn index() -> Result<()> {
let orders = sample_orders()
.into_iter()
.map(|order| (order.order_id.clone(), order));
- let rows = mount_each!(orders, |order| process_order(ctx, order)).await?;
+ let rows = use_mount_each!(orders, |order| process_order(ctx, order)).await?;
for row in &rows {
table.declare_row(&ctx, row)?;
}
diff --git a/examples/rust/conversation_to_knowledge/src/main.rs b/examples/rust/conversation_to_knowledge/src/main.rs
index 7d3c1e51..b656371c 100644
--- a/examples/rust/conversation_to_knowledge/src/main.rs
+++ b/examples/rust/conversation_to_knowledge/src/main.rs
@@ -119,7 +119,7 @@ async fn app_main(ctx: Ctx, input_dir: PathBuf) -> Result<()> {
// Phase 1: per-session fetch + extract (memoized, concurrent).
let processed: Vec<ProcessedSession> =
- mount_each!(sources.into_iter().map(|s| (s.key(), s)), |source| {
+ use_mount_each!(sources.into_iter().map(|s| (s.key(), s)), |source| {
pipeline::process_session(ctx, source)
})
.await?;
diff --git a/examples/rust/csv_to_iggy/src/main.rs b/examples/rust/csv_to_iggy/src/main.rs
index aa97e09c..3c85042c 100644
--- a/examples/rust/csv_to_iggy/src/main.rs
+++ b/examples/rust/csv_to_iggy/src/main.rs
@@ -130,7 +130,7 @@ async fn index(producer: IggyProducer, stream: String, topic: String) -> Result<
let files = cocoindex::resources::fs::walk_items("./data", &["**/*.csv"])?;
println!("found {} CSV file(s)", files.len());
- let per_file = mount_each!(files, |file| process_csv(ctx, file)).await?;
+ let per_file = use_mount_each!(files, |file| process_csv(ctx, file)).await?;
let mut declared = 0;
for messages in &per_file {
diff --git a/examples/rust/docs_to_knowledge_graph/src/main.rs b/examples/rust/docs_to_knowledge_graph/src/main.rs
index 933c973a..9871597f 100644
--- a/examples/rust/docs_to_knowledge_graph/src/main.rs
+++ b/examples/rust/docs_to_knowledge_graph/src/main.rs
@@ -302,7 +302,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
sourcedir.display()
);
let docs: Vec<DocTriples> = ctx
- .mount_each(
+ .use_mount_each(
files,
|(key, _)| format!("file/{key}"),
move |ctx, (_, file)| {
diff --git a/examples/rust/image_search/src/main.rs b/examples/rust/image_search/src/main.rs
index 0d2b1ccd..138239bd 100644
--- a/examples/rust/image_search/src/main.rs
+++ b/examples/rust/image_search/src/main.rs
@@ -87,7 +87,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
sourcedir.display()
);
- let points = mount_each!(files, |file| process_image(ctx, file)).await?;
+ let points = use_mount_each!(files, |file| process_image(ctx, file)).await?;
for p in &points {
let payload = json!({ "filename": p.filename })
diff --git a/examples/rust/image_search_colpali/src/main.rs b/examples/rust/image_search_colpali/src/main.rs
index d7c7ed38..53ead886 100644
--- a/examples/rust/image_search_colpali/src/main.rs
+++ b/examples/rust/image_search_colpali/src/main.rs
@@ -149,7 +149,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
sourcedir.display()
);
- let points = mount_each!(files, |file| process_image(ctx, file)).await?;
+ let points = use_mount_each!(files, |file| process_image(ctx, file)).await?;
for p in &points {
let payload = json!({ "filename": p.filename })
diff --git a/examples/rust/multi_codebase_summarization/src/main.rs b/examples/rust/multi_codebase_summarization/src/main.rs
index e36fd90c..603d50fa 100644
--- a/examples/rust/multi_codebase_summarization/src/main.rs
+++ b/examples/rust/multi_codebase_summarization/src/main.rs
@@ -12,7 +12,7 @@
//! - `mount_each!("project", projects, |project| process_project(ctx, …))` β€” one
//! component per project, processed concurrently and skipped wholesale on the
//! component-memo fast-path when unchanged
-//! - `mount_each!(files, |file| extract_file_info(ctx, file))` β€” concurrent
+//! - `use_mount_each!(files, |file| extract_file_info(ctx, file))` β€” concurrent
//! per-file extraction, each its own component (unchanged files skip the LLM)
//! - `#[cocoindex::function(memo)]` β€” project aggregation cached by project
//! fingerprint (function-memo nested inside the project component)
@@ -326,7 +326,7 @@ async fn process_project(
let (project_name, files) = project;
// Extract per-file info β€” one child component per file (unchanged files skip).
let file_infos: Vec<CodebaseInfo> =
- mount_each!(files.into_iter().map(|f| (f.key(), f)), |file| {
+ use_mount_each!(files.into_iter().map(|f| (f.key(), f)), |file| {
extract_file_info(ctx, file)
})
.await?;
diff --git a/examples/rust/product_recommendation/src/main.rs b/examples/rust/product_recommendation/src/main.rs
index fb2528b5..48ddc316 100644
--- a/examples/rust/product_recommendation/src/main.rs
+++ b/examples/rust/product_recommendation/src/main.rs
@@ -297,7 +297,7 @@ async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
sourcedir.display()
);
let products: Vec<ProductTaxonomies> = ctx
- .mount_each(
+ .use_mount_each(
files,
|(key, _)| format!("file/{key}"),
move |ctx, (_, file)| {
diff --git a/examples/rust/snowflake_target/src/main.rs b/examples/rust/snowflake_target/src/main.rs
index f77e6de4..4e386bec 100644
--- a/examples/rust/snowflake_target/src/main.rs
+++ b/examples/rust/snowflake_target/src/main.rs
@@ -190,7 +190,7 @@ async fn index() -> Result<()> {
let orders = sample_orders()
.into_iter()
.map(|order| (order.order_id.clone(), order));
- let rows = mount_each!(orders, |order| process_order(ctx, order)).await?;
+ let rows = use_mount_each!(orders, |order| process_order(ctx, order)).await?;
for row in &rows {
table.declare_row(&ctx, row)?;
}
diff --git a/rust/cli/templates/main.rs.tmpl b/rust/cli/templates/main.rs.tmpl
index d54fc20e..932adeb0 100644
--- a/rust/cli/templates/main.rs.tmpl
+++ b/rust/cli/templates/main.rs.tmpl
@@ -39,7 +39,7 @@ async fn app_main(ctx: Ctx) -> Result<()> {
let files = walk_items(project_dir().join("data"), &["**/*.md"])?;
// 3) Process each input under a stable path, then declare its output.
- let outputs = mount_each!(files, |file| process_file(ctx, file)).await?;
+ let outputs = use_mount_each!(files, |file| process_file(ctx, file)).await?;
for (name, content) in &outputs {
target.declare_file(&ctx, name, content.as_bytes())?;
}
diff --git a/rust/cli/tests/e2e.rs b/rust/cli/tests/e2e.rs
index 33ed4130..76a6fd27 100644
--- a/rust/cli/tests/e2e.rs
+++ b/rust/cli/tests/e2e.rs
@@ -207,7 +207,7 @@ fn update_preview_ls_show_drop() {
assert_ok(&show);
assert_eq!(
stdout(&show),
- "Stable paths:\n /\n /\"upper/a.txt\"\n /\"upper/b.txt\"\n"
+ "Stable paths:\n /\n /\"upper\"\n /\"upper\"/\"a.txt\"\n /\"upper\"/\"b.txt\"\n"
);
let tree = sb.cli(&[
"show",
@@ -218,7 +218,7 @@ fn update_preview_ls_show_drop() {
"--tree",
]);
assert!(
- stdout(&tree).contains("- upper/a.txt [component]"),
+ stdout(&tree).contains("- upper\n - a.txt [component]"),
"{}",
stdout(&tree)
);
@@ -252,9 +252,11 @@ fn update_preview_ls_show_drop() {
states:1:Existing schema_version:0 generation:None\n \
- path:/@cocoindex/localfs/file/[\"{out_dir}\",\"{second}\"]\n \
states:1:Existing schema_version:0 generation:None\n\n \
- /\"upper/a.txt\"\n type:component version:1 processor:mount:upper\n \
+ /\"upper\"\n type:directory version:0 processor:-\n \
+ has_memoization:false target_state_count:0\n\n \
+ /\"upper\"/\"a.txt\"\n type:component version:1 processor:mount:upper\n \
has_memoization:true target_state_count:0\n\n \
- /\"upper/b.txt\"\n type:component version:1 processor:mount:upper\n \
+ /\"upper\"/\"b.txt\"\n type:component version:1 processor:mount:upper\n \
has_memoization:true target_state_count:0\n\n"
)
});
@@ -265,7 +267,7 @@ fn update_preview_ls_show_drop() {
"--app-name",
"FixtureApp",
"-p",
- "/upper%2Fa.txt",
+ "/upper/a.txt",
]);
assert_ok(&one);
let states = sb.cli(&[
diff --git a/rust/cli/tests/fixture_app/src/main.rs b/rust/cli/tests/fixture_app/src/main.rs
index 62a29487..7e8602c3 100644
--- a/rust/cli/tests/fixture_app/src/main.rs
+++ b/rust/cli/tests/fixture_app/src/main.rs
@@ -34,7 +34,7 @@ async fn fixture_app(ctx: Ctx) -> Result<()> {
let target = mount_dir_target(&ctx, env_path("FIXTURE_OUT")?)?;
let files = walk_items(env_path("FIXTURE_SRC")?, &["*.txt"])?;
let count = files.len();
- let outputs = mount_each!(files, |file| upper(ctx, file)).await?;
+ let outputs = use_mount_each!(files, |file| upper(ctx, file)).await?;
for (name, text) in &outputs {
target.declare_file(&ctx, name, text.as_bytes())?;
}
diff --git a/rust/sdk/SHOWCASE.md b/rust/sdk/SHOWCASE.md
index 8649bd2a..bd59afc2 100644
--- a/rust/sdk/SHOWCASE.md
+++ b/rust/sdk/SHOWCASE.md
@@ -450,15 +450,23 @@ arguments in a component-memo fingerprint:
```rust
let summary = use_mount!(summarize(ctx, document)).await?;
-let outputs = mount_each!(files, |file| process_file(ctx, file, target)).await?;
+mount_each!(files, |file| process_file(ctx, file, target)).await?;
+
+let outputs = use_mount_each!(files, |file| summarize_file(ctx, file)).await?;
```
-`mount_each!` accepts `(key, value)` items, creates one child component per
-key, and runs them concurrently. Without an explicit prefix, the entry
-function's name is used; the prefixed form is
+`mount_each!` accepts `(key, value)` items and mounts one background child
+component per key at `prefix/key`, like `coco.mount_each` in Python: children
+are mounted as the items are read, run on their own tasks under the app's
+`max_inflight_components` limit (1024 by default, or
+`COCOINDEX_MAX_INFLIGHT_COMPONENTS`), and the macro returns one handle whose
+`ready()` waits for all of them. `use_mount_each!` is the foreground form that
+returns each child's value in input order. Without an explicit prefix, the
+entry function's name is used; the prefixed form is
`mount_each!("documents", files, |file| process_file(ctx, file))`.
-Use `ctx.scope(key, body)` or `ctx.mount_each(items, key_fn, body)` only when
+Use `ctx.scope(key, body)`, `ctx.mount_each(items, key_fn, body)` or
+`ctx.use_mount_each(items, key_fn, body)` only when
the component key and closure are deliberately dynamic and no automatic
function/argument fingerprint is wanted. These methods always execute their
closures; they still provide stable child ownership and reconciliation.
@@ -480,11 +488,14 @@ exception handlers in scope.
### Nested component paths
-`ctx.with_subpath(&"process")` returns a context whose child mounts go under
+`ctx.with_subpath("process")` returns a context whose child mounts go under
`process`, the Rust spelling of a `with coco.component_subpath("process"):`
block. Chain calls for a multi-part prefix. `use_state` is not available on a
subpath context, as in Python.
+A mount key is a string or any other `IntoStableKey`: an integer, a UUID,
+bytes, or a `StableKey` such as a symbol, as Python's component keys are.
+
```rust
let process = ctx.with_subpath(&"process");
for file in files {
diff --git a/rust/sdk/cocoindex/benches/sdk_engine.rs b/rust/sdk/cocoindex/benches/sdk_engine.rs
index fcb9bdf0..d69a54ca 100644
--- a/rust/sdk/cocoindex/benches/sdk_engine.rs
+++ b/rust/sdk/cocoindex/benches/sdk_engine.rs
@@ -25,8 +25,7 @@
//! 5. `batched_fn` β€” N concurrent calls of a `#[function(batching)]` with a
//! trivial body. Reported per call.
//! 6. `startup` β€” open an environment on a fresh directory, create an app and
-//! run an empty update: the async API and the `*_blocking` API, which
-//! builds a tokio runtime per call.
+//! run an empty update: the async API and the `*_blocking` API.
use std::hint::black_box;
use std::sync::Arc;
@@ -217,7 +216,9 @@ fn bench_memo_call(c: &mut Criterion) {
async fn mount_each_run(app: &App, n: usize) -> Duration {
app.update(move |ctx| async move {
let start = Instant::now();
- ctx.mount_each(0..n, |i| *i, |_child, _i| async { Ok(()) })
+ ctx.mount_each(0..n, |i| *i as i64, |_child, _i| async { Ok(()) })
+ .await?
+ .ready()
.await?;
Ok(start.elapsed())
})
@@ -229,7 +230,7 @@ async fn scope_run(app: &App, n: usize) -> Duration {
app.update(move |ctx| async move {
let start = Instant::now();
for i in 0..n {
- ctx.scope(&i, |_child| async { Ok(()) }).await?;
+ ctx.scope(i as i64, |_child| async { Ok(()) }).await?;
}
Ok(start.elapsed())
})
diff --git a/rust/sdk/cocoindex/src/app.rs b/rust/sdk/cocoindex/src/app.rs
index cea60c96..df8f0cc7 100644
--- a/rust/sdk/cocoindex/src/app.rs
+++ b/rust/sdk/cocoindex/src/app.rs
@@ -81,8 +81,14 @@ pub const LMDB_MAX_DBS_ENV: &str = "COCOINDEX_LMDB_MAX_DBS";
/// none (read by [`Environment::from_registered`]).
pub const LMDB_MAP_SIZE_ENV: &str = "COCOINDEX_LMDB_MAP_SIZE";
+/// Environment variable for the number of components an app runs at once
+/// when the builder sets none, read when the app is created, as in Python.
+pub const MAX_INFLIGHT_COMPONENTS_ENV: &str = "COCOINDEX_MAX_INFLIGHT_COMPONENTS";
+
/// LMDB maximum number of named databases when nothing sets it.
pub const DEFAULT_LMDB_MAX_DBS: u32 = 1024;
+/// Components an app runs at once when nothing sets it (Python's default).
+pub const DEFAULT_MAX_INFLIGHT_COMPONENTS: usize = 1024;
/// LMDB map size in bytes (4 GiB) when nothing sets it.
pub const DEFAULT_LMDB_MAP_SIZE: usize = 0x1_0000_0000;
@@ -189,10 +195,18 @@ impl Environment {
/// # Errors
/// Returns an error if the app's state store cannot be created.
pub async fn app(&self, name: &str) -> Result<App> {
+ // Resolved per app, as Python's `App.__init__` does: the builder's
+ // value, else the environment variable, else the default.
+ let max_inflight_components = match self.inner.max_inflight_components {
+ Some(limit) => limit,
+ None => {
+ env_setting(MAX_INFLIGHT_COMPONENTS_ENV)?.unwrap_or(DEFAULT_MAX_INFLIGHT_COMPONENTS)
+ }
+ };
let core_app = CoreApp::new(
name,
self.inner.core_env.clone(),
- self.inner.max_inflight_components,
+ Some(max_inflight_components),
)
.await
.map_err(|e| Error::engine(format!("failed to create app: {e}")))?;
@@ -210,14 +224,12 @@ impl Environment {
}
/// Create an app in this environment (blocking). Convenience for sync
- /// callers β€” creates a tokio runtime internally and awaits [`Self::app`].
+ /// callers β€” awaits [`Self::app`] on the engine's runtime.
///
/// # Panics
/// Panics if called from within an async runtime; use the async form there.
pub fn app_blocking(&self, name: &str) -> Result<App> {
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.app(name))
+ block_on(self.app(name))
}
}
@@ -302,6 +314,8 @@ impl EnvironmentBuilder {
}
/// Limit the number of concurrently processing components (per app).
+ /// Default: the `COCOINDEX_MAX_INFLIGHT_COMPONENTS` environment variable
+ /// when the app is created, else 1024, as in Python.
pub fn max_inflight_components(mut self, value: usize) -> Self {
self.max_inflight_components = Some(value);
self
@@ -394,12 +408,20 @@ impl EnvironmentBuilder {
/// # Panics
/// Panics if called from within an async runtime; use the async form there.
pub fn build_blocking(self) -> Result<Environment> {
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.build())
+ block_on(self.build())
}
}
+/// Run `fut` to completion on the engine's runtime, for the `*_blocking`
+/// wrappers. The runtime is shared by every app in the process (the engine
+/// spawns component tasks on it), so no wrapper builds a runtime of its own.
+///
+/// # Panics
+/// Panics if called from within an async runtime; use the async form there.
+fn block_on<F: Future>(fut: F) -> F::Output {
+ cocoindex_core::engine::runtime::get_runtime().block_on(fut)
+}
+
/// Read an integer setting from the environment; `Ok(None)` when unset.
fn env_setting<T: std::str::FromStr>(name: &str) -> Result<Option<T>> {
match std::env::var(name) {
@@ -464,9 +486,7 @@ impl AppBuilder {
/// # Panics
/// Panics if called from within an async runtime; use the async form there.
pub fn build_blocking(self) -> Result<App> {
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.build())
+ block_on(self.build())
}
}
@@ -524,7 +544,7 @@ impl App {
}
/// Convenience: synchronously open an app with a specific DB path. Same
- /// as [`Self::open`] but blocks on a tokio runtime internally.
+ /// as [`Self::open`] but blocks on the engine's runtime.
///
/// # Panics
/// Panics if called from within an async runtime; use the async form there.
@@ -685,9 +705,7 @@ impl App {
Fut: Future<Output = Result<T>> + Send + 'static,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.preview(f))
+ block_on(self.preview(f))
}
/// Start an update and return a handle for progress/stat polling.
@@ -806,8 +824,8 @@ impl App {
}
}
- /// Run the pipeline (blocking). Convenience for sync callers β€” creates a
- /// tokio runtime internally.
+ /// Run the pipeline (blocking). Convenience for sync callers β€” runs on
+ /// the engine's runtime.
///
/// # Panics
/// Panics if called from within an active tokio runtime (use `update`
@@ -818,9 +836,7 @@ impl App {
Fut: Future<Output = Result<T>> + Send + 'static,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.update(f))
+ block_on(self.update(f))
}
/// Run the pipeline once with explicit update options (blocking).
@@ -833,9 +849,7 @@ impl App {
Fut: Future<Output = Result<T>> + Send + 'static,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.update_with_options(options, f))
+ block_on(self.update_with_options(options, f))
}
/// Start dropping all persisted app state and return a handle.
@@ -858,9 +872,7 @@ impl App {
/// # Panics
/// Panics if called from within an async runtime; use the async form there.
pub fn drop_state_blocking(&self) -> Result<()> {
- let rt = tokio::runtime::Runtime::new()
- .map_err(|e| Error::engine(format!("failed to create tokio runtime: {e}")))?;
- rt.block_on(self.drop_state())
+ block_on(self.drop_state())
}
/// Get the app name.
diff --git a/rust/sdk/cocoindex/src/ctx.rs b/rust/sdk/cocoindex/src/ctx.rs
index 2cefe4c7..b69b20b1 100644
--- a/rust/sdk/cocoindex/src/ctx.rs
+++ b/rust/sdk/cocoindex/src/ctx.rs
@@ -2,7 +2,6 @@
use std::any::Any;
use std::collections::{HashMap, HashSet};
-use std::fmt::Display;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
@@ -18,6 +17,8 @@ use cocoindex_core::engine::live_component::mount_live_prepare;
use cocoindex_core::engine::target_state::TargetStateProvider;
use cocoindex_core::state::stable_path::{StableKey, StablePath, StablePathRef};
use cocoindex_utils::fingerprint::Fingerprint;
+use futures::stream::{Stream, StreamExt};
+use rustc_hash::FxHashSet;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@@ -28,8 +29,10 @@ use crate::live_component::{
ExceptionContext, ExceptionHandler, ExceptionSource, LiveComponent, LiveMapView,
MountEachLiveComponent, MountKind, build_chained_on_error, new_operator, start_process_live,
};
+use crate::logic::FnLogicEntry;
use crate::memo::{MemoInput, MemoStateDecision, MemoStateValue};
use crate::profile::{BoxedHandler, BoxedProcessor, RustProfile, Value};
+use crate::target_state::IntoStableKey;
use crate::user_state::{IntoStateKey, StateHandle};
type ContextFingerprinter<T> = Arc<dyn Fn(&str, &T) -> Result<Fingerprint> + Send + Sync>;
@@ -423,32 +426,32 @@ impl Ctx {
fn child_path(
&self,
comp_ctx: &ComponentProcessorContext<RustProfile>,
- key: &str,
+ key: StableKey,
) -> StablePath {
- self.mount_base_path(comp_ctx)
- .concat_part(StableKey::Str(Arc::from(key)))
+ self.mount_base_path(comp_ctx).concat_part(key)
}
/// Return a clone of this `Ctx` whose child mounts go under `key`, below
- /// the current path: `ctx.with_subpath(&"process")` followed by
+ /// the current path: `ctx.with_subpath("process")` followed by
/// `use_mount!("a.md", ...)` mounts at `process/a.md`. The Rust analogue of
/// a `with coco.component_subpath("process"):` block in Python. Chain calls
/// for a multi-part subpath.
///
+ /// `key` is any [`IntoStableKey`]: a string, an integer, a UUID, bytes, a
+ /// [`StableKey`] (for a symbol or an array), or a reference to one.
+ ///
/// The scoped context still belongs to the same component: target states
/// declared through it are the component's own, and
/// [`Ctx::use_state`] is an error inside a subpath, as in Python, because
/// the state would be owned by the component but keyed as if by a child.
#[must_use = "returns a new scoped Ctx; the original is unchanged"]
- pub fn with_subpath<K: Display>(&self, key: &K) -> Self {
+ pub fn with_subpath<K: IntoStableKey>(&self, key: K) -> Self {
let mut scoped = self.clone();
scoped.subpath = self
.subpath
.iter()
.cloned()
- .chain(std::iter::once(StableKey::Str(Arc::from(
- key.to_string().as_str(),
- ))))
+ .chain(std::iter::once(key.into_stable_key()))
.collect();
scoped
}
@@ -481,10 +484,7 @@ impl Ctx {
#[doc(hidden)]
pub async fn __coco_tracked_fn<T, F, Fut>(
&self,
- module_path: &'static str,
- fn_name: &'static str,
- code_hash: u64,
- deps_fp: Option<Fingerprint>,
+ logic: &'static FnLogicEntry,
propagate_children_fn_logic: bool,
f: F,
) -> Result<T>
@@ -492,7 +492,7 @@ impl Ctx {
F: FnOnce(Ctx) -> Fut,
Fut: Future<Output = Result<T>>,
{
- let fp = fn_logic_fingerprint(module_path, fn_name, code_hash, deps_fp)?;
+ let fp = logic.fingerprint()?;
// `propagate_children_fn_logic` is the `logic_tracking` mode lowered by
// the `#[function]` macro: `true` for `"full"` (default β€” a transitively
// called function's logic change also invalidates this one), `false` for
@@ -688,8 +688,8 @@ impl Ctx {
}
}
-/// The logic fingerprint of one `#[cocoindex::function]`. Must match the one
-/// registered at startup (see `crate::logic`). `deps_fp` is the fingerprint of
+/// The logic fingerprint of one `#[cocoindex::function]`, computed once per
+/// function by [`FnLogicEntry::fingerprint`]. `deps_fp` is the fingerprint of
/// the function's `deps = ...` value, folded in so a change to it moves the
/// function's logic exactly as a body edit does.
pub(crate) fn fn_logic_fingerprint(
@@ -1041,9 +1041,9 @@ impl Ctx {
/// In catch-up mode this runs `f` once and returns. In live mode it runs
/// once, marks the component ready, then repeats after `interval` until the
/// app/live component is cancelled.
- pub async fn auto_refresh<K, F, Fut>(&self, key: &K, interval: Duration, f: F) -> Result<()>
+ pub async fn auto_refresh<K, F, Fut>(&self, key: K, interval: Duration, f: F) -> Result<()>
where
- K: Display,
+ K: IntoStableKey,
F: Fn(Ctx) -> Fut + Clone + Send + Sync + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
@@ -1051,8 +1051,9 @@ impl Ctx {
return f(self.clone()).await;
};
- let key_str = key.to_string();
- let child_path = self.child_path(comp_ctx, &key_str);
+ let key = key.into_stable_key();
+ let key_str = key_label(&key);
+ let child_path = self.child_path(comp_ctx, key);
let stable_path = child_path.to_string();
let fn_ctx = Arc::new(FnCallContext::default());
let pending = mount_live_prepare(comp_ctx, &fn_ctx, child_path, comp_ctx.live())
@@ -1122,12 +1123,12 @@ impl Ctx {
///
/// A failure in the component's processing is logged, not returned; use
/// [`Ctx::mount_live_with_handler`] to observe or propagate it.
- pub async fn mount_live<K, C>(&self, key: &K, component: C) -> Result<()>
+ pub async fn mount_live<K, C>(&self, key: K, component: C) -> Result<()>
where
- K: Display,
+ K: IntoStableKey,
C: LiveComponent,
{
- self.mount_live_impl(key.to_string(), Arc::new(component), None)
+ self.mount_live_impl(key.into_stable_key(), Arc::new(component), None)
.await
}
@@ -1136,17 +1137,17 @@ impl Ctx {
/// `Ok(())` to swallow a failure or `Err(_)` to propagate it.
pub async fn mount_live_with_handler<K, C, H>(
&self,
- key: &K,
+ key: K,
component: C,
handler: H,
) -> Result<()>
where
- K: Display,
+ K: IntoStableKey,
C: LiveComponent,
H: Fn(&Error, &ExceptionContext) -> Result<()> + Send + Sync + 'static,
{
let handler: ExceptionHandler = Arc::new(handler);
- self.mount_live_impl(key.to_string(), Arc::new(component), Some(handler))
+ self.mount_live_impl(key.into_stable_key(), Arc::new(component), Some(handler))
.await
}
@@ -1156,13 +1157,13 @@ impl Ctx {
/// individually. The analogue of [`Ctx::mount_each`] for live sources.
pub async fn mount_each_live<Key, K, V, Feed, F, Fut>(
&self,
- key: &Key,
+ key: Key,
feed: Feed,
process_fn: F,
) -> Result<()>
where
- Key: Display,
- K: Display + Send + Sync + 'static,
+ Key: IntoStableKey,
+ K: std::fmt::Display + Send + Sync + 'static,
V: Send + Sync + 'static,
Feed: LiveMapView<K, V>,
F: Fn(Ctx, V) -> Fut + Send + Sync + 'static,
@@ -1191,24 +1192,25 @@ impl Ctx {
) -> Result<()>
where
I: IntoIterator,
- K: Display,
+ K: IntoStableKey,
F: Fn(I::Item) -> C,
C: LiveComponent,
{
- let mut keys = rustc_hash::FxHashSet::default();
+ let mut keys = FxHashSet::default();
let mut components = Vec::new();
for item in items {
- let key = key_fn(&item).to_string();
+ let key = key_fn(&item).into_stable_key();
if !keys.insert(key.clone()) {
return Err(Error::engine(format!(
- "duplicate key `{key}` in mount_each_live_component batch"
+ "duplicate key `{}` in mount_each_live_component batch",
+ key_label(&key)
)));
}
components.push((key, make_component(item)));
}
let futs: Vec<_> = components
.into_iter()
- .map(|(key, component)| async move { self.mount_live(&key, component).await })
+ .map(|(key, component)| async move { self.mount_live(key, component).await })
.collect();
futures::future::try_join_all(futs).await?;
Ok(())
@@ -1216,7 +1218,7 @@ impl Ctx {
async fn mount_live_impl(
&self,
- key_str: String,
+ key: StableKey,
instance: Arc<dyn LiveComponent>,
handler: Option<ExceptionHandler>,
) -> Result<()> {
@@ -1226,7 +1228,8 @@ impl Ctx {
return instance.process(self.clone()).await;
};
- let child_path = self.child_path(comp_ctx, &key_str);
+ let key_str = key_label(&key);
+ let child_path = self.child_path(comp_ctx, key);
let fn_ctx = Arc::new(FnCallContext::default());
let pending = mount_live_prepare(comp_ctx, &fn_ctx, child_path.clone(), comp_ctx.live())
.map_err(|e| Error::engine(format!("{e}")))?;
@@ -1279,6 +1282,9 @@ impl Ctx {
/// handler returns `Err`. The parent's own completion still waits for every
/// child it mounted.
///
+ /// `key` is any [`IntoStableKey`]: a string, an integer, a UUID, bytes, a
+ /// [`StableKey`], or a reference to one.
+ ///
/// Prefer the `mount!` macro for a `#[cocoindex::function]` call: it adds
/// the function's logic and arguments as the component-memo fingerprint, so
/// an unchanged child is skipped. This method always runs `f`.
@@ -1288,7 +1294,7 @@ impl Ctx {
/// ```no_run
/// # use cocoindex::ctx::Ctx;
/// # async fn doc(ctx: &Ctx) -> cocoindex::error::Result<()> {
- /// let handle = ctx.mount(&"child", |child_ctx| async move {
+ /// let handle = ctx.mount("child", |child_ctx| async move {
/// // declare target states ...
/// Ok(())
/// }).await?;
@@ -1296,13 +1302,13 @@ impl Ctx {
/// # Ok(())
/// # }
/// ```
- pub async fn mount<K, F, Fut>(&self, key: &K, f: F) -> Result<ComponentMountHandle>
+ pub async fn mount<K, F, Fut>(&self, key: K, f: F) -> Result<ComponentMountHandle>
where
- K: Display,
+ K: IntoStableKey,
F: FnOnce(Ctx) -> Fut + Send + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
- self.__mount_fp(key.to_string(), None, f).await
+ self.__mount_fp(key.into_stable_key(), None, f).await
}
/// Background mount with an explicit component-memo fingerprint. The
@@ -1311,7 +1317,7 @@ impl Ctx {
#[doc(hidden)]
pub async fn __mount_fp<F, Fut>(
&self,
- key: String,
+ key: StableKey,
memo: Option<crate::mount::ComponentMemo>,
f: F,
) -> Result<ComponentMountHandle>
@@ -1329,8 +1335,38 @@ impl Ctx {
deadline: self.deadline,
});
};
+ let processor_name = format!("mount:{}", key_label(&key));
+ let handle = self
+ .mount_background(comp_ctx, key, processor_name, memo, f)
+ .await?;
+ Ok(ComponentMountHandle {
+ inner: MountHandleInner::Core(vec![handle]),
+ deadline: self.deadline,
+ })
+ }
- let child_path = self.child_path(comp_ctx, &key);
+ /// Mount `f` under `key` on its own task, reported as `processor_name`,
+ /// and return the engine handle to wait for it. The one background mount
+ /// path: [`Ctx::mount`] / `mount!` and every item of [`Ctx::mount_each`]
+ /// / `mount_each!` go through it.
+ ///
+ /// Admission is bounded by the app's `max_inflight_components`: when the
+ /// pool is full this waits before spawning, so a parent streaming items
+ /// into `mount_each` runs ahead of its children only as far as the pool
+ /// allows, as in Python.
+ async fn mount_background<F, Fut>(
+ &self,
+ comp_ctx: &ComponentProcessorContext<RustProfile>,
+ key: StableKey,
+ processor_name: String,
+ memo: Option<crate::mount::ComponentMemo>,
+ f: F,
+ ) -> Result<ComponentExecutionHandle>
+ where
+ F: FnOnce(Ctx) -> Fut + Send + 'static,
+ Fut: Future<Output = Result<()>> + Send + 'static,
+ {
+ let child_path = self.child_path(comp_ctx, key);
let fn_ctx = Arc::new(FnCallContext::default());
let child_component = comp_ctx
.component()
@@ -1343,7 +1379,6 @@ impl Ctx {
let state = self.state.clone();
let has_context_memo_state = state.context.has_memo_state_fns();
let handler_chain = self.handler_chain.clone();
- let processor_name = format!("mount:{key}");
let processor = BoxedProcessor::new(
{
let handler_chain = handler_chain.clone();
@@ -1357,6 +1392,7 @@ impl Ctx {
handler_chain.clone(),
DeadlineContext::NONE,
);
+ // The body returns `()`: no value is serialized or stored.
Box::pin(async move {
f(ctx).await?;
Ok(Value::unit())
@@ -1381,27 +1417,23 @@ impl Ctx {
source: ExceptionSource::Component,
},
);
- let handle = child_component
+ child_component
.mount(comp_ctx, processor, on_error)
.await
- .map_err(Error::from)?;
- Ok(ComponentMountHandle {
- inner: MountHandleInner::Core(handle),
- deadline: self.deadline,
- })
+ .map_err(Error::from)
}
/// Named sub-component. Creates a child scope in the pipeline tree.
///
/// The key determines the child's stable path for memoization and
- /// target state tracking.
+ /// target state tracking; it is any [`IntoStableKey`].
///
/// # Examples
///
/// ```no_run
/// # use cocoindex::ctx::Ctx;
/// # async fn doc(ctx: &Ctx) -> cocoindex::error::Result<()> {
- /// let val = ctx.scope(&"child", |child_ctx| async move {
+ /// let val = ctx.scope("child", |child_ctx| async move {
/// Ok(42)
/// }).await?;
/// # Ok(())
@@ -1412,19 +1444,19 @@ impl Ctx {
///
/// Returns an error if the closure returns an error, or if stable
/// path/component tracking fails internally.
- pub async fn scope<K, T, F, Fut>(&self, key: &K, f: F) -> Result<T>
+ pub async fn scope<K, T, F, Fut>(&self, key: K, f: F) -> Result<T>
where
- K: Display,
+ K: IntoStableKey,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
F: FnOnce(Ctx) -> Fut + Send + 'static,
Fut: Future<Output = Result<T>> + Send + 'static,
{
- self.__use_mount_fp(key.to_string(), None, f).await
+ self.__use_mount_fp(key.into_stable_key(), None, f).await
}
/// Foreground mount with an explicit component-memo fingerprint. The
- /// `mount!` / `use_mount!` / `mount_each!` macros call this; `scope` is the
- /// `memo = None` (always-run) case kept for direct use and tests.
+ /// `use_mount!` macro calls this; `scope` is the `memo = None`
+ /// (always-run) case kept for direct use and tests.
///
/// When `memo` is `Some`, the engine checks its fingerprint and argument states before running the child
/// and skips the whole component on an unchanged hit (see
@@ -1432,7 +1464,7 @@ impl Ctx {
#[doc(hidden)]
pub async fn __use_mount_fp<T, F, Fut>(
&self,
- key: String,
+ key: StableKey,
memo: Option<crate::mount::ComponentMemo>,
f: F,
) -> Result<T>
@@ -1441,17 +1473,17 @@ impl Ctx {
F: FnOnce(Ctx) -> Fut + Send + 'static,
Fut: Future<Output = Result<T>> + Send + 'static,
{
- let processor_name = format!("mount:{key}");
+ let processor_name = format!("mount:{}", key_label(&key));
self.use_mount_named(key, processor_name, memo, f).await
}
/// Foreground mount under `key`, reported (stats, `show -l`) as
- /// `processor_name`. Items of one `mount_each` share a name, the way
+ /// `processor_name`. Items of one `use_mount_each` share a name, the way
/// Python names a processor after its function, so per-item mounts do not
/// produce one stats line per item.
async fn use_mount_named<T, F, Fut>(
&self,
- key: String,
+ key: StableKey,
processor_name: String,
memo: Option<crate::mount::ComponentMemo>,
f: F,
@@ -1467,7 +1499,7 @@ impl Ctx {
return f(child_ctx).await;
};
- let child_path = self.child_path(comp_ctx, &key);
+ let child_path = self.child_path(comp_ctx, key);
let fn_ctx = Arc::new(FnCallContext::default());
let child_component = comp_ctx
@@ -1512,38 +1544,256 @@ impl Ctx {
.with_context_memo_state(has_context_memo_state)
.with_state_inputs(memo.map(|memo| memo.state_inputs).unwrap_or_default());
- let handle = match child_component
+ let handle = child_component
.use_mount(comp_ctx, processor, self.deadline)
.await
- {
- Ok(handle) => handle,
- Err(err) => {
- return Err(Error::from(err));
- }
- };
- let value = handle.result(Some(comp_ctx)).await;
- let value = match value {
- Ok(value) => value,
- Err(err) => {
- return Err(Error::from(err));
- }
+ .map_err(Error::from)?;
+ let value = handle.result(Some(comp_ctx)).await.map_err(Error::from)?;
+ value
+ .deserialize()
+ .map_err(|err| Error::engine(format!("{err}")))
+ }
+
+ /// Mount one background child component per item, keyed by `key_fn`, and
+ /// return one handle for all of them. The Rust analogue of Python's
+ /// `coco.mount_each` for a plain iterable: `items` is consumed as the
+ /// children are mounted, each child runs on its own task under the app's
+ /// `max_inflight_components` limit, and the parent neither waits for them
+ /// nor takes a value from them (see [`Ctx::mount`] for how a child's
+ /// failure is reported). For items whose values the caller needs, use
+ /// [`Ctx::use_mount_each`]; for an async source, [`Ctx::mount_each_stream`].
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use cocoindex::ctx::Ctx;
+ /// # async fn doc(ctx: &Ctx, tasks: Vec<String>) -> cocoindex::error::Result<()> {
+ /// let handle = ctx.mount_each(
+ /// tasks,
+ /// |task| task.clone(), // use the task string as the child key
+ /// |child_ctx, task| async move {
+ /// // declare target states ...
+ /// Ok(())
+ /// }
+ /// ).await?;
+ /// handle.ready().await?;
+ /// # Ok(())
+ /// # }
+ /// ```
+ ///
+ /// All items are reported under one processor name, `mount_each`, in
+ /// update stats and `cocoindex show -l`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error when `key_fn` yields the same key twice, or when a
+ /// child cannot be mounted. A child's own failure is not an error here.
+ pub async fn mount_each<I, K, F, Fut>(
+ &self,
+ items: I,
+ key_fn: impl Fn(&I::Item) -> K,
+ f: F,
+ ) -> Result<ComponentMountHandle>
+ where
+ I: IntoIterator,
+ I::Item: Send + 'static,
+ K: IntoStableKey,
+ F: Fn(Ctx, I::Item) -> Fut + Send + Clone + 'static,
+ Fut: Future<Output = Result<()>> + Send + 'static,
+ {
+ let keyed = items
+ .into_iter()
+ .map(|item| (key_fn(&item).into_stable_key(), item));
+ self.mount_each_keyed(
+ futures::stream::iter(keyed),
+ None,
+ "mount_each".to_string(),
+ |_| Ok(None),
+ f,
+ )
+ .await
+ }
+
+ /// Like [`Ctx::mount_each`] for an async source of `(key, item)` pairs: a
+ /// child is mounted as each pair arrives, so the source is read at the
+ /// pace the children are admitted. The analogue of passing an async
+ /// iterable to Python's `coco.mount_each`.
+ pub async fn mount_each_stream<S, K, V, F, Fut>(
+ &self,
+ items: S,
+ f: F,
+ ) -> Result<ComponentMountHandle>
+ where
+ S: Stream<Item = (K, V)>,
+ K: IntoStableKey,
+ V: Send + 'static,
+ F: Fn(Ctx, V) -> Fut + Send + Clone + 'static,
+ Fut: Future<Output = Result<()>> + Send + 'static,
+ {
+ self.mount_each_keyed(
+ items.map(|(key, value)| (key.into_stable_key(), value)),
+ None,
+ "mount_each".to_string(),
+ |_| Ok(None),
+ f,
+ )
+ .await
+ }
+
+ /// Per-item background mounts with component-memo fingerprints, the
+ /// runtime behind `mount_each!`. Each `(key, value)` pair becomes a child
+ /// component at `prefix/key` (or `key` when `prefix` is `None`); `memo_of`
+ /// computes the value's component-memo fingerprint and `body` runs the
+ /// entry function under the child scope.
+ #[doc(hidden)]
+ pub async fn __mount_each_fp<K, V, M, B, Fut>(
+ &self,
+ items: impl IntoIterator<Item = (K, V)>,
+ prefix: Option<&str>,
+ memo_of: M,
+ body: B,
+ ) -> Result<ComponentMountHandle>
+ where
+ K: IntoStableKey,
+ V: Send + 'static,
+ M: Fn(&V) -> Result<Option<crate::mount::ComponentMemo>>,
+ B: Fn(Ctx, V) -> Fut + Clone + Send + 'static,
+ Fut: Future<Output = Result<()>> + Send + 'static,
+ {
+ let processor_name = format!("mount:{}", prefix.unwrap_or("mount_each"));
+ let keyed = items
+ .into_iter()
+ .map(|(key, value)| (key.into_stable_key(), value));
+ self.mount_each_keyed(
+ futures::stream::iter(keyed),
+ prefix,
+ processor_name,
+ memo_of,
+ body,
+ )
+ .await
+ }
+
+ /// The one `mount_each` path: stream `(key, value)` pairs, mount each in
+ /// the background under `prefix` (a child path part, as Python's
+ /// `mount_each` subpath) and gather the handles. Duplicate keys are an
+ /// error, as in Python.
+ async fn mount_each_keyed<S, V, M, B, Fut>(
+ &self,
+ items: S,
+ prefix: Option<&str>,
+ processor_name: String,
+ memo_of: M,
+ body: B,
+ ) -> Result<ComponentMountHandle>
+ where
+ S: Stream<Item = (StableKey, V)>,
+ V: Send + 'static,
+ M: Fn(&V) -> Result<Option<crate::mount::ComponentMemo>>,
+ B: Fn(Ctx, V) -> Fut + Clone + Send + 'static,
+ Fut: Future<Output = Result<()>> + Send + 'static,
+ {
+ self.check_cancellation()?;
+ let parent = match prefix {
+ Some(prefix) => self.with_subpath(prefix),
+ None => self.clone(),
};
- let result: T = match value.deserialize() {
- Ok(result) => result,
- Err(err) => {
- return Err(Error::engine(format!("{err}")));
+ let mut keys = FxHashSet::default();
+ let mut items = std::pin::pin!(items);
+ let Some(comp_ctx) = &parent.comp_ctx else {
+ // No pipeline context β€” run the bodies one by one; the handle
+ // reports the first failure.
+ let mut outcome = Ok(());
+ while let Some((key, value)) = items.next().await {
+ check_unique_key(&mut keys, key)?;
+ if let Err(err) = body(parent.child(None), value).await
+ && outcome.is_ok()
+ {
+ outcome = Err(err);
+ }
}
+ return Ok(ComponentMountHandle {
+ inner: MountHandleInner::Immediate(outcome),
+ deadline: self.deadline,
+ });
};
- Ok(result)
+ let mut handles = Vec::new();
+ while let Some((key, value)) = items.next().await {
+ parent.check_cancellation()?;
+ check_unique_key(&mut keys, key.clone())?;
+ let memo = memo_of(&value)?;
+ let body = body.clone();
+ let handle = parent
+ .mount_background(comp_ctx, key, processor_name.clone(), memo, move |child| {
+ body(child, value)
+ })
+ .await?;
+ handles.push(handle);
+ }
+ Ok(ComponentMountHandle {
+ inner: MountHandleInner::Core(handles),
+ deadline: self.deadline,
+ })
}
- /// Per-item foreground mounts with component-memo fingerprints, the runtime
- /// behind `mount_each!`. Each `(key, value)` pair becomes a child component
- /// at `prefix/key` (or `key` when `prefix` is `None`); `memo_of` computes
- /// the value's component-memo fingerprint and `body` runs the entry
- /// function under the child scope. All children run concurrently.
+ /// Run a closure for each item in its own child scope, in the foreground,
+ /// and return the values in input order: the per-item form of
+ /// [`Ctx::scope`] / `use_mount!`, where [`Ctx::mount_each`] is the
+ /// per-item form of [`Ctx::mount`].
+ ///
+ /// Each item gets its own `Ctx` child scope keyed by `key_fn(item)`. All
+ /// closures run concurrently; every started item runs to completion, then
+ /// the first error in input order is returned.
+ ///
+ /// # Examples
+ ///
+ /// ```no_run
+ /// # use cocoindex::ctx::Ctx;
+ /// # async fn doc(ctx: &Ctx, tasks: Vec<String>) -> cocoindex::error::Result<()> {
+ /// let results = ctx.use_mount_each(
+ /// tasks,
+ /// |task| task.clone(), // use the task string as scope key
+ /// |child_ctx, task| async move {
+ /// Ok(format!("processed {task}"))
+ /// }
+ /// ).await?;
+ /// # Ok(())
+ /// # }
+ /// ```
+ ///
+ /// All items are reported under one processor name, `use_mount_each`, in
+ /// update stats and `cocoindex show -l`.
+ ///
+ /// # Errors
+ ///
+ /// Returns an error if any of the closures fail. The first encountered error
+ /// is returned.
+ pub async fn use_mount_each<I, K, F, Fut, T>(
+ &self,
+ items: I,
+ key_fn: impl Fn(&I::Item) -> K,
+ f: F,
+ ) -> Result<Vec<T>>
+ where
+ I: IntoIterator,
+ I::Item: Send + 'static,
+ K: IntoStableKey,
+ T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
+ F: Fn(Ctx, I::Item) -> Fut + Send + Clone + 'static,
+ Fut: Future<Output = Result<T>> + Send + 'static,
+ {
+ let keyed = items
+ .into_iter()
+ .map(|item| (key_fn(&item).into_stable_key(), item));
+ self.use_mount_each_keyed(keyed, None, "use_mount_each".to_string(), |_| Ok(None), f)
+ .await
+ }
+
+ /// Per-item foreground mounts with component-memo fingerprints, the
+ /// runtime behind `use_mount_each!`: [`Ctx::__mount_each_fp`] with the
+ /// values returned in input order.
#[doc(hidden)]
- pub async fn __mount_each_fp<K, V, M, B, Fut, T>(
+ pub async fn __use_mount_each_fp<K, V, M, B, Fut, T>(
&self,
items: impl IntoIterator<Item = (K, V)>,
prefix: Option<&str>,
@@ -1551,49 +1801,56 @@ impl Ctx {
body: B,
) -> Result<Vec<T>>
where
- K: Display,
+ K: IntoStableKey,
V: Send + 'static,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
M: Fn(&V) -> Result<Option<crate::mount::ComponentMemo>>,
B: Fn(Ctx, V) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Result<T>> + Send + 'static,
{
- let mut keys = rustc_hash::FxHashSet::default();
- let mut keyed = Vec::new();
+ let processor_name = format!("mount:{}", prefix.unwrap_or("use_mount_each"));
+ let keyed = items
+ .into_iter()
+ .map(|(key, value)| (key.into_stable_key(), value));
+ self.use_mount_each_keyed(keyed, prefix, processor_name, memo_of, body)
+ .await
+ }
+
+ async fn use_mount_each_keyed<V, M, B, Fut, T>(
+ &self,
+ items: impl IntoIterator<Item = (StableKey, V)>,
+ prefix: Option<&str>,
+ processor_name: String,
+ memo_of: M,
+ body: B,
+ ) -> Result<Vec<T>>
+ where
+ V: Send + 'static,
+ T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
+ M: Fn(&V) -> Result<Option<crate::mount::ComponentMemo>>,
+ B: Fn(Ctx, V) -> Fut + Clone + Send + 'static,
+ Fut: Future<Output = Result<T>> + Send + 'static,
+ {
+ let parent = match prefix {
+ Some(prefix) => self.with_subpath(prefix),
+ None => self.clone(),
+ };
+ let mut keys = FxHashSet::default();
+ let mut futs = Vec::new();
for (key, value) in items {
- let key = key.to_string();
- if !keys.insert(key.clone()) {
- return Err(Error::engine(format!(
- "duplicate key `{key}` in mount_each batch"
- )));
- }
+ check_unique_key(&mut keys, key.clone())?;
let memo = memo_of(&value)?;
- let (subpath, processor_name) = match prefix {
- Some(prefix) => (format!("{prefix}/{key}"), format!("mount:{prefix}")),
- None => (key.clone(), format!("mount:{key}")),
- };
- keyed.push((subpath, processor_name, memo, value));
- }
-
- let futs: Vec<_> = keyed
- .into_iter()
- .map(|(subpath, processor_name, memo, value)| {
- let body = body.clone();
- async move {
- self.use_mount_named(subpath, processor_name, memo, move |child| {
- body(child, value)
- })
+ let body = body.clone();
+ let parent = &parent;
+ let processor_name = processor_name.clone();
+ futs.push(async move {
+ parent
+ .use_mount_named(key, processor_name, memo, move |child| body(child, value))
.await
- }
- })
- .collect();
-
- let outcomes = futures::future::join_all(futs).await;
- let mut values = Vec::with_capacity(outcomes.len());
- for outcome in outcomes {
- values.push(outcome?);
+ });
}
- Ok(values)
+ let outcomes = futures::future::join_all(futs).await;
+ outcomes.into_iter().collect()
}
/// Cached computation. If `key` hasn't changed since the last run,
@@ -1633,95 +1890,21 @@ impl Ctx {
pub async fn memo<K, T, F, Fut>(&self, key: &K, f: F) -> Result<T>
where
K: Serialize,
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: FnOnce(Ctx) -> Fut + Send + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
+ T: Serialize + for<'de> Deserialize<'de>,
+ F: FnOnce(Ctx) -> Fut,
+ Fut: Future<Output = Result<T>>,
{
crate::memo::cached(self, key, f).await
}
- /// Run a closure concurrently for each item, creating a child scope per item.
- ///
- /// Each item gets its own `Ctx` child scope keyed by `key_fn(item)`.
- /// All closures run concurrently; every started item runs to
- /// completion, then the first error in input order is returned.
- ///
- /// # Examples
- ///
- /// ```no_run
- /// # use cocoindex::ctx::Ctx;
- /// # async fn doc(ctx: &Ctx, tasks: Vec<String>) -> cocoindex::error::Result<()> {
- /// let results = ctx.mount_each(
- /// tasks,
- /// |task| task.clone(), // use the task string as scope key
- /// |child_ctx, task| async move {
- /// Ok(format!("processed {task}"))
- /// }
- /// ).await?;
- /// # Ok(())
- /// # }
- /// ```
- ///
- /// All items are reported under one processor name, `mount_each`, in
- /// update stats and `cocoindex show -l`.
- ///
- /// # Errors
- ///
- /// Returns an error if any of the closures fail. The first encountered error
- /// is returned.
- pub async fn mount_each<I, K, F, Fut, T>(
- &self,
- items: I,
- key_fn: impl Fn(&I::Item) -> K,
- f: F,
- ) -> Result<Vec<T>>
- where
- I: IntoIterator,
- I::Item: Send + 'static,
- K: Display,
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: Fn(Ctx, I::Item) -> Fut + Send + Clone + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
- {
- let mut keys = rustc_hash::FxHashSet::default();
- let mut keyed = Vec::new();
-
- for item in items {
- let key = key_fn(&item).to_string();
- if !keys.insert(key.clone()) {
- return Err(Error::engine(format!(
- "duplicate key `{}` in mount_each batch",
- key
- )));
- }
- keyed.push((key, item));
- }
-
- let futs: Vec<_> = keyed
- .into_iter()
- .map(|(key, item)| {
- let f = f.clone();
- async move {
- self.use_mount_named(key, "mount_each".to_string(), None, move |child| {
- f(child, item)
- })
- .await
- }
- })
- .collect();
-
- let outcomes = futures::future::join_all(futs).await;
- let mut values = Vec::with_capacity(outcomes.len());
- for outcome in outcomes {
- values.push(outcome?);
- }
- Ok(values)
- }
-
- /// Run a closure concurrently for each item within the current scope (no child scopes).
+ /// Run a closure concurrently for each item within the current scope (no
+ /// child scopes). The analogue of Python's `coco.map`: the items run on
+ /// the caller's task and start in input order, as tasks of one asyncio
+ /// loop do. For CPU-bound work, spawn it from the closure
+ /// (`tokio::task::spawn_blocking`).
///
- /// Like `futures::future::join_all` plus result collection: every started
- /// item runs to completion, then the first error in input order is returned.
+ /// Every started item runs to completion, then the first error in input
+ /// order is returned.
///
/// # Examples
///
@@ -1752,20 +1935,40 @@ impl Ctx {
let futs: Vec<_> = items
.into_iter()
.map(|item| async {
+ // A task may start after the caller's deadline moved forward
+ // while earlier tasks were being scheduled.
deadline.check().map_err(Error::from)?;
let result = f(item).await;
+ // Do not let a value returned after the deadline look
+ // successful to the caller.
if result.is_ok() {
deadline.check().map_err(Error::from)?;
}
result
})
.collect();
- let outcomes = futures::future::join_all(futs).await;
- let mut values = Vec::with_capacity(outcomes.len());
- for outcome in outcomes {
- values.push(outcome?);
- }
- Ok(values)
+ futures::future::join_all(futs).await.into_iter().collect()
+ }
+}
+
+/// `key` as it reads in a processor name: the bare text of a string or
+/// symbol key, the [`StableKey`] display form otherwise.
+fn key_label(key: &StableKey) -> String {
+ match key {
+ StableKey::Str(text) | StableKey::Symbol(text) => text.to_string(),
+ other => other.to_string(),
+ }
+}
+
+/// Record `key` in `keys`, or fail: a `mount_each` batch mounts each key once.
+fn check_unique_key(keys: &mut FxHashSet<StableKey>, key: StableKey) -> Result<()> {
+ if keys.insert(key.clone()) {
+ Ok(())
+ } else {
+ Err(Error::engine(format!(
+ "duplicate key `{}` in mount_each batch",
+ key_label(&key)
+ )))
}
}
@@ -1779,24 +1982,34 @@ pub struct ComponentMountHandle {
}
enum MountHandleInner {
- Core(ComponentExecutionHandle),
- /// Standalone use (no pipeline): the body already ran.
+ /// One handle per child: a `mount` has one, a `mount_each` one per item.
+ Core(Vec<ComponentExecutionHandle>),
+ /// Standalone use (no pipeline): the bodies already ran.
Immediate(Result<()>),
}
impl ComponentMountHandle {
- /// Wait until the component is ready: its body has run and its target
+ /// Wait until every component is ready: its body has run and its target
/// states are synced. Returns `Err` only when the caller's deadline expires
- /// or an exception handler in scope propagated the child's failure (see
+ /// or an exception handler in scope propagated a child's failure (see
/// [`Ctx::with_exception_handler`]); an unhandled failure is logged and
/// resolves `Ok`, as in Python.
pub async fn ready(self) -> Result<()> {
self.deadline.check()?;
match self.inner {
- MountHandleInner::Core(handle) => handle.ready().await?,
- MountHandleInner::Immediate(outcome) => outcome?,
+ MountHandleInner::Core(handles) => {
+ for handle in handles {
+ handle.ready().await?;
+ // The child is ready; check the caller's own deadline
+ // before it continues or waits on the next child.
+ self.deadline.check()?;
+ }
+ }
+ MountHandleInner::Immediate(outcome) => {
+ outcome?;
+ self.deadline.check()?;
+ }
}
- self.deadline.check()?;
Ok(())
}
}
diff --git a/rust/sdk/cocoindex/src/lib.rs b/rust/sdk/cocoindex/src/lib.rs
index 2f3ac27c..2f9fc426 100644
--- a/rust/sdk/cocoindex/src/lib.rs
+++ b/rust/sdk/cocoindex/src/lib.rs
@@ -137,6 +137,7 @@ pub use user_state::{IntoStateKey, StateHandle};
// Re-export proc macros
pub use cocoindex_macros::{
MemoInput, SchemaFields, app, function, lifespan, main, mount, mount_each, use_mount,
+ use_mount_each,
};
pub use row_schema::{LogicalType, SchemaField, SchemaFields};
diff --git a/rust/sdk/cocoindex/src/logic.rs b/rust/sdk/cocoindex/src/logic.rs
index c3ce9978..a0532cd1 100644
--- a/rust/sdk/cocoindex/src/logic.rs
+++ b/rust/sdk/cocoindex/src/logic.rs
@@ -23,15 +23,51 @@ use crate::error::{Error, Result};
/// One `#[coco::function]`'s logic identity, collected at link time.
///
-/// The fingerprint computed from these fields must match the one
-/// `#[cocoindex::function]` records at call time (see `Ctx::__coco_tracked_fn`):
-/// `crate::ctx::fn_logic_fingerprint(module, name, code_hash, deps_fp)`.
+/// The fingerprint is computed once per process ([`fingerprint`](Self::fingerprint)):
+/// registration and every call of the function read the same cached value,
+/// so a call hashes nothing.
pub struct FnLogicEntry {
pub module: &'static str,
pub name: &'static str,
pub code_hash: u64,
/// The function's `deps = ...` value, if any. See [`FnDeps`].
pub deps: Option<&'static FnDeps>,
+ fingerprint: OnceLock<std::result::Result<Fingerprint, String>>,
+}
+
+impl FnLogicEntry {
+ #[doc(hidden)]
+ pub const fn new(
+ module: &'static str,
+ name: &'static str,
+ code_hash: u64,
+ deps: Option<&'static FnDeps>,
+ ) -> Self {
+ Self {
+ module,
+ name,
+ code_hash,
+ deps,
+ fingerprint: OnceLock::new(),
+ }
+ }
+
+ /// The function's logic fingerprint, computed on first use:
+ /// `crate::ctx::fn_logic_fingerprint(module, name, code_hash, deps_fp)`.
+ pub fn fingerprint(&self) -> Result<Fingerprint> {
+ self.fingerprint
+ .get_or_init(|| {
+ let deps_fp = self
+ .deps
+ .map(FnDeps::get)
+ .transpose()
+ .map_err(|err| err.to_string())?;
+ crate::ctx::fn_logic_fingerprint(self.module, self.name, self.code_hash, deps_fp)
+ .map_err(|err| err.to_string())
+ })
+ .clone()
+ .map_err(|err| Error::engine(format!("logic fingerprint error: {err}")))
+ }
}
/// The fingerprint of a `#[cocoindex::function(deps = ...)]` value, computed
@@ -64,13 +100,6 @@ impl FnDeps {
#[linkme::distributed_slice]
pub static COCO_FN_LOGIC: [FnLogicEntry] = [..];
-/// The logic fingerprint for one registered function β€” kept in sync with
-/// `Ctx::__coco_tracked_fn`.
-fn entry_fingerprint(e: &FnLogicEntry) -> Result<Fingerprint> {
- let deps_fp = e.deps.map(FnDeps::get).transpose()?;
- crate::ctx::fn_logic_fingerprint(e.module, e.name, e.code_hash, deps_fp)
-}
-
/// Register every `#[coco::function]`'s logic fingerprint into the engine's
/// logic set. The slice is fixed at link time and these registrations are held
/// for the life of the process, so only the first call registers; later calls
@@ -79,7 +108,7 @@ pub(crate) fn register_all_fn_logic() {
static REGISTERED: Once = Once::new();
REGISTERED.call_once(|| {
for entry in COCO_FN_LOGIC {
- match entry_fingerprint(entry) {
+ match entry.fingerprint() {
Ok(fp) => logic_registry::register(fp),
Err(err) => tracing::warn!(
"{}::{} is not registered in the logic set, so memo entries that recorded it never hit: {err}",
diff --git a/rust/sdk/cocoindex/src/memo.rs b/rust/sdk/cocoindex/src/memo.rs
index 95b91a6f..0d061638 100644
--- a/rust/sdk/cocoindex/src/memo.rs
+++ b/rust/sdk/cocoindex/src/memo.rs
@@ -41,15 +41,17 @@ use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
-use cocoindex_core::engine::context::{FnCallContext, MemoStatesPayload};
-use cocoindex_core::engine::function::reserve_memoization;
+use cocoindex_core::engine::context::{
+ ComponentProcessorContext, FnCallContext, MemoStatesPayload,
+};
+use cocoindex_core::engine::function::{FnCallMemoGuard, reserve_memoization};
use cocoindex_utils::fingerprint::{Fingerprint, Fingerprinter};
use serde::{Deserialize, Serialize};
-use crate::ctx::Ctx;
+use crate::ctx::{Ctx, FnFrameGuard};
use crate::deps::validate_data_deps;
use crate::error::{Error, Result};
-use crate::profile::Value;
+use crate::profile::{RustProfile, Value};
use crate::resources::file::FileLike;
/// Type-owned memoization behavior for function arguments and tracked context
@@ -70,9 +72,22 @@ pub trait MemoInput: Send + Sync {
/// Add this value's semantic identity to a function memo key.
fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()>;
+ /// Whether [`memo_state`](Self::memo_state) may return `Some` for this
+ /// value. `true` by default, so a type that implements `memo_state` need
+ /// not implement this; a type whose `memo_state` is always `None` (every
+ /// plain data type) returns `false` here, and the SDK then skips the
+ /// `memo_state` call and its boxed future on every memoized call.
+ ///
+ /// A container returns whether any of its elements does: see the
+ /// [`crate::MemoInput`] derive.
+ fn has_memo_state(&self) -> bool {
+ true
+ }
+
/// Validate external state before a matching memo is reused.
///
- /// `None` means that this value needs no state validation.
+ /// `None` means that this value needs no state validation. Called only
+ /// when [`has_memo_state`](Self::has_memo_state) is `true`.
async fn memo_state(
&self,
_previous: Option<&MemoStateValue>,
@@ -89,6 +104,10 @@ macro_rules! impl_serde_memo_input {
fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()> {
writer.write(self)
}
+
+ fn has_memo_state(&self) -> bool {
+ false
+ }
}
)+
};
@@ -127,6 +146,10 @@ impl MemoInput for bytes::Bytes {
fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()> {
writer.write(self)
}
+
+ fn has_memo_state(&self) -> bool {
+ false
+ }
}
impl_serde_memo_input!(serde_json::Value);
@@ -145,6 +168,10 @@ where
fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()> {
writer.write(self)
}
+
+ fn has_memo_state(&self) -> bool {
+ false
+ }
}
#[cfg(feature = "rust_decimal")]
@@ -156,6 +183,10 @@ impl<T: MemoInput + ?Sized> MemoInput for &T {
(*self).write_memo_key(writer)
}
+ fn has_memo_state(&self) -> bool {
+ (*self).has_memo_state()
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -170,6 +201,10 @@ impl<T: MemoInput + ?Sized> MemoInput for Box<T> {
self.as_ref().write_memo_key(writer)
}
+ fn has_memo_state(&self) -> bool {
+ self.as_ref().has_memo_state()
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -184,6 +219,10 @@ impl<T: MemoInput + ?Sized> MemoInput for Arc<T> {
self.as_ref().write_memo_key(writer)
}
+ fn has_memo_state(&self) -> bool {
+ self.as_ref().has_memo_state()
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -204,6 +243,10 @@ impl<T: MemoInput> MemoInput for Option<T> {
}
}
+ fn has_memo_state(&self) -> bool {
+ self.as_ref().is_some_and(MemoInput::has_memo_state)
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -225,6 +268,10 @@ impl<T: MemoInput> MemoInput for [T] {
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ self.iter().any(MemoInput::has_memo_state)
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -243,6 +290,10 @@ impl<T: MemoInput> MemoInput for Vec<T> {
self.as_slice().write_memo_key(writer)
}
+ fn has_memo_state(&self) -> bool {
+ self.as_slice().has_memo_state()
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -257,6 +308,10 @@ impl<T: MemoInput, const N: usize> MemoInput for [T; N] {
self.as_slice().write_memo_key(writer)
}
+ fn has_memo_state(&self) -> bool {
+ self.as_slice().has_memo_state()
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -316,6 +371,11 @@ macro_rules! impl_map_memo_input {
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ self.iter()
+ .any(|(key, value)| key.has_memo_state() || value.has_memo_state())
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -347,6 +407,11 @@ impl<K: MemoInput + Ord, V: MemoInput> MemoInput for BTreeMap<K, V> {
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ self.iter()
+ .any(|(key, value)| key.has_memo_state() || value.has_memo_state())
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -386,6 +451,10 @@ where
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ self.iter().any(MemoInput::has_memo_state)
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -410,6 +479,10 @@ impl<T: MemoInput + Ord> MemoInput for BTreeSet<T> {
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ self.iter().any(MemoInput::has_memo_state)
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -433,6 +506,10 @@ macro_rules! impl_tuple_memo_input {
Ok(())
}
+ fn has_memo_state(&self) -> bool {
+ $(self.$index.has_memo_state())||+
+ }
+
async fn memo_state(
&self,
previous: Option<&MemoStateValue>,
@@ -541,12 +618,15 @@ pub async fn memo_state_group(
})
.collect::<Vec<_>>();
- let decisions = futures::future::try_join_all(
- children
- .iter()
- .zip(&previous_values)
- .map(|(child, previous)| child.memo_state(previous.as_ref())),
- )
+ let decisions = futures::future::try_join_all(children.iter().zip(&previous_values).map(
+ |(child, previous)| async move {
+ if child.has_memo_state() {
+ child.memo_state(previous.as_ref()).await
+ } else {
+ Ok(None)
+ }
+ },
+ ))
.await?;
let mut memo_valid = previous.is_some() && shape_matches && !force_miss;
@@ -596,6 +676,9 @@ pub(crate) async fn collect_component_states(
let mut states = Vec::new();
let mut memo_valid = true;
for input in inputs {
+ if !input.has_memo_state() {
+ continue;
+ }
let previous = stored
.and_then(|stored| stored.get(states.len()))
.cloned()
@@ -635,9 +718,9 @@ struct FileMemoState {
pub async fn cached<K, T, F, Fut>(ctx: &Ctx, key: &K, f: F) -> Result<T>
where
K: Serialize,
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: FnOnce(Ctx) -> Fut + Send + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
+ T: Serialize + for<'de> Deserialize<'de>,
+ F: FnOnce(Ctx) -> Fut,
+ Fut: Future<Output = Result<T>>,
{
let fp = key_fingerprint_result(key)?;
cached_by_fingerprint(ctx, fp, None, true, f).await
@@ -665,165 +748,269 @@ pub async fn cached_by_fingerprint<T, F, Fut>(
f: F,
) -> Result<T>
where
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: FnOnce(Ctx) -> Fut + Send + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
-{
- memoized_call(
- ctx,
- fp,
- logic_fp,
- propagate_children_fn_logic,
- |_| async { Ok(Vec::new()) },
- f,
- )
- .await
-}
-
-/// Like [`cached_by_fingerprint`], with positional argument state validation
-/// (`MemoInput::memo_state`) supplied by the generated `#[function(memo)]`
-/// wrapper.
-#[doc(hidden)]
-pub async fn cached_by_fingerprint_with_state<T, F, Fut, S, SFut>(
- ctx: &Ctx,
- fp: Fingerprint,
- logic_fp: Option<Fingerprint>,
- propagate_children_fn_logic: bool,
- state_fn: S,
- f: F,
-) -> Result<T>
-where
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: FnOnce(Ctx) -> Fut + Send + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
- S: FnOnce(Option<Vec<MemoStateValue>>) -> SFut,
- SFut: Future<Output = Result<Vec<MemoStateDecision>>> + Send,
+ T: Serialize + for<'de> Deserialize<'de>,
+ F: FnOnce(Ctx) -> Fut,
+ Fut: Future<Output = Result<T>>,
{
- memoized_call(ctx, fp, logic_fp, propagate_children_fn_logic, state_fn, f).await
+ let probe = MemoProbe::begin(ctx, fp, logic_fp, propagate_children_fn_logic).await?;
+ match probe.lookup(Vec::new()).await? {
+ MemoLookup::Hit(value) => Ok(value),
+ MemoLookup::Miss(miss) => miss.run(f).await,
+ }
}
-/// One memoized call, mirroring the Python SDK's `Function.__call__`.
+/// One memoized call in progress, mirroring the Python SDK's
+/// `Function.__call__`: the entry under `fp` is reserved, then the caller
+/// collects the arguments' states against the stored ones
+/// ([`cached_states`](Self::cached_states)), then [`lookup`](Self::lookup)
+/// decides between a hit and a miss, and a miss [`runs`](MemoMiss::run) the
+/// body.
+///
+/// The `#[cocoindex::function(memo)]` wrapper drives these steps itself so
+/// the arguments are only borrowed until the body runs: on a hit nothing is
+/// cloned, and on a miss the function's own arguments move into the body.
///
/// The call's frame is created (and seeded with the function's own logic
/// fingerprint) before the memo probe and joined into the caller's frame on
/// every exit path β€” hit, miss or error β€” so a memoized caller records this
/// call's logic, context dependencies, target-provider generations and memo
/// entry whether or not this call ran its body.
-async fn memoized_call<T, F, Fut, S, SFut>(
- ctx: &Ctx,
+#[doc(hidden)]
+pub struct MemoProbe<'a> {
+ ctx: &'a Ctx,
+ /// `None` outside a pipeline (standalone mode): the body always runs.
+ pipeline: Option<PipelineProbe<'a>>,
+}
+
+struct PipelineProbe<'a> {
+ comp_ctx: &'a ComponentProcessorContext<RustProfile>,
fp: Fingerprint,
- logic_fp: Option<Fingerprint>,
- propagate_children_fn_logic: bool,
- state_fn: S,
- f: F,
-) -> Result<T>
-where
- T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
- F: FnOnce(Ctx) -> Fut + Send + 'static,
- Fut: Future<Output = Result<T>> + Send + 'static,
- S: FnOnce(Option<Vec<MemoStateValue>>) -> SFut,
- SFut: Future<Output = Result<Vec<MemoStateDecision>>> + Send,
-{
- ctx.check_cancellation()?;
- let Some(comp_ctx) = &ctx.comp_ctx else {
- // No pipeline context β€” execute directly (standalone mode).
- let result = f(ctx.clone()).await?;
+ fn_ctx: Arc<FnCallContext>,
+ // Field order is drop order: the frame joins the caller once this entry's
+ // write lock is released.
+ guard: FnCallMemoGuard<RustProfile>,
+ _frame: FnFrameGuard,
+}
+
+/// The outcome of [`MemoProbe::lookup`].
+#[doc(hidden)]
+pub enum MemoLookup<'a, T> {
+ /// The stored value, still valid.
+ Hit(T),
+ /// No reusable entry: run the body with [`MemoMiss::run`].
+ Miss(MemoMiss<'a>),
+}
+
+/// A memo miss: the body must run, and its result is stored under the
+/// reserved entry.
+#[doc(hidden)]
+pub struct MemoMiss<'a> {
+ /// The `Ctx` the body receives: scoped to the call's frame in a pipeline.
+ ctx: Ctx,
+ /// Boxed: a hit, the common case, does not carry a miss's state.
+ pipeline: Option<Box<PipelineMiss<'a>>>,
+}
+
+struct PipelineMiss<'a> {
+ comp_ctx: &'a ComponentProcessorContext<RustProfile>,
+ fp: Fingerprint,
+ fn_ctx: Arc<FnCallContext>,
+ /// The argument states to store with the entry.
+ memo_states: Vec<Value>,
+ guard: FnCallMemoGuard<RustProfile>,
+ _frame: FnFrameGuard,
+}
+
+impl<'a> MemoProbe<'a> {
+ /// Reserve the memo entry under `fp`. See [`cached_by_fingerprint`] for
+ /// `logic_fp` and `propagate_children_fn_logic`.
+ pub async fn begin(
+ ctx: &'a Ctx,
+ fp: Fingerprint,
+ logic_fp: Option<Fingerprint>,
+ propagate_children_fn_logic: bool,
+ ) -> Result<Self> {
ctx.check_cancellation()?;
- return Ok(result);
- };
+ let Some(comp_ctx) = &ctx.comp_ctx else {
+ return Ok(Self {
+ ctx,
+ pipeline: None,
+ });
+ };
+ let fn_ctx = Arc::new(FnCallContext::new(propagate_children_fn_logic));
+ if let Some(logic_fp) = logic_fp {
+ fn_ctx.add_fn_logic_dep(logic_fp);
+ }
+ let frame = ctx.frame_guard(fn_ctx.clone());
+ let guard = reserve_memoization(comp_ctx, fp).await?;
+ Ok(Self {
+ ctx,
+ pipeline: Some(PipelineProbe {
+ comp_ctx,
+ fp,
+ fn_ctx,
+ guard,
+ _frame: frame,
+ }),
+ })
+ }
+
+ /// Whether the arguments' states must be collected: `false` outside a
+ /// pipeline, where the body always runs.
+ pub fn validates_states(&self) -> bool {
+ self.pipeline.is_some()
+ }
- let fn_ctx = Arc::new(FnCallContext::new(propagate_children_fn_logic));
- if let Some(logic_fp) = logic_fp {
- fn_ctx.add_fn_logic_dep(logic_fp);
+ /// The positional argument states stored with the entry, to validate the
+ /// current arguments against; `None` when there is no entry.
+ pub fn cached_states(&self) -> Option<Vec<MemoStateValue>> {
+ let cached = self.pipeline.as_ref()?.guard.cached()?;
+ Some(
+ cached
+ .memo_states
+ .iter()
+ .cloned()
+ .map(MemoStateValue)
+ .collect(),
+ )
}
- // Declared before the memo guard so it drops after it: the frame joins
- // the caller once this entry's write lock is released.
- let _frame = ctx.frame_guard(fn_ctx.clone());
- let mut guard = reserve_memoization(comp_ctx, fp).await?;
+ /// Decide between a hit and a miss from the arguments' state decisions
+ /// (positional, one per argument with state), the context values' states
+ /// and the entry's data dependencies.
+ pub async fn lookup<T>(
+ self,
+ state_decisions: Vec<MemoStateDecision>,
+ ) -> Result<MemoLookup<'a, T>>
+ where
+ T: for<'de> Deserialize<'de>,
+ {
+ let Self { ctx, pipeline } = self;
+ let Some(PipelineProbe {
+ comp_ctx,
+ fp,
+ fn_ctx,
+ mut guard,
+ _frame,
+ }) = pipeline
+ else {
+ return Ok(MemoLookup::Miss(MemoMiss {
+ ctx: ctx.clone(),
+ pipeline: None,
+ }));
+ };
- let cached_states = guard.cached().map(|cached| {
- cached
- .memo_states
+ let memo_states_for_resolve = state_decisions
.iter()
- .cloned()
- .map(MemoStateValue)
- .collect::<Vec<_>>()
- });
- let state_decisions = state_fn(cached_states).await?;
- let memo_states_for_resolve = state_decisions
- .iter()
- .map(|decision| decision.state.0.clone())
- .collect::<Vec<_>>();
- let cached_context_states = guard
- .cached()
- .map(|cached| cached.context_memo_states.to_vec())
- .unwrap_or_default();
- let context_validation = ctx
- .state
- .context
- .validate_memo_states(&cached_context_states)
- .await?;
- let states_valid =
- state_decisions.iter().all(|decision| decision.memo_valid) && context_validation.memo_valid;
- // Data dependencies the entry recorded (`use_data_dep`): validated only
- // when the states still allow a reuse.
- let data_deps = match guard.cached() {
- Some(cached) if states_valid && !cached.data_deps.is_empty() => {
- Some(validate_data_deps(cached.data_deps.to_vec(), "memoized function").await?)
+ .map(|decision| decision.state.0.clone())
+ .collect::<Vec<_>>();
+ let cached_context_states = guard
+ .cached()
+ .map(|cached| cached.context_memo_states.to_vec())
+ .unwrap_or_default();
+ let context_validation = ctx
+ .state
+ .context
+ .validate_memo_states(&cached_context_states)
+ .await?;
+ let states_valid = state_decisions.iter().all(|decision| decision.memo_valid)
+ && context_validation.memo_valid;
+ // Data dependencies the entry recorded (`use_data_dep`): validated only
+ // when the states still allow a reuse.
+ let data_deps = match guard.cached() {
+ Some(cached) if states_valid && !cached.data_deps.is_empty() => {
+ Some(validate_data_deps(cached.data_deps.to_vec(), "memoized function").await?)
+ }
+ _ => None,
+ };
+
+ if let Some(cached) = guard.cached()
+ && states_valid
+ && data_deps.as_ref().is_none_or(|dd| dd.can_reuse)
+ {
+ let states_changed = state_decisions
+ .iter()
+ .map(|decision| &decision.state.0.0)
+ .ne(cached.memo_states.iter().map(|value| &value.0));
+ let value: T = cached.ret.deserialize()?;
+ ctx.check_cancellation()?;
+ // The hit skips the body, so carry what it would have declared: this
+ // entry (which owns its target states) and its provider generations.
+ record_dependency_memo_entry(&fn_ctx, fp);
+ guard.join_cached_target_provider_deps(&fn_ctx);
+ // ... and the logic deps the entry recorded beneath this fn's own fp,
+ // through this frame so the caller's `logic_tracking` applies as on a
+ // miss.
+ guard.join_cached_logic_deps(&fn_ctx);
+ if states_changed
+ || context_validation.states_changed
+ || data_deps.as_ref().is_some_and(|dd| dd.states_changed)
+ {
+ guard.update_memo_states(MemoStatesPayload {
+ positional: memo_states_for_resolve,
+ by_context_fp: context_validation.states,
+ data_deps: data_deps.map(|dd| dd.records).unwrap_or_default(),
+ });
+ }
+ // After the refresh, so the records re-offered to a caller stored
+ // later are the refreshed ones.
+ guard.join_cached_data_deps(&fn_ctx);
+ return Ok(MemoLookup::Hit(value));
}
- _ => None,
- };
- if let Some(cached) = guard.cached()
- && states_valid
- && data_deps.as_ref().is_none_or(|dd| dd.can_reuse)
+ Ok(MemoLookup::Miss(MemoMiss {
+ ctx: ctx.with_fn_ctx(fn_ctx.clone()),
+ pipeline: Some(Box::new(PipelineMiss {
+ comp_ctx,
+ fp,
+ fn_ctx,
+ memo_states: memo_states_for_resolve,
+ guard,
+ _frame,
+ })),
+ }))
+ }
+}
+
+impl MemoMiss<'_> {
+ /// Run the body and store its result under the reserved entry.
+ pub async fn run<T, F, Fut>(self, f: F) -> Result<T>
+ where
+ T: Serialize,
+ F: FnOnce(Ctx) -> Fut,
+ Fut: Future<Output = Result<T>>,
{
- let states_changed = state_decisions
- .iter()
- .map(|decision| &decision.state.0.0)
- .ne(cached.memo_states.iter().map(|value| &value.0));
- let value: T = cached.ret.deserialize()?;
+ let Self { ctx, pipeline } = self;
+ let Some(miss) = pipeline else {
+ // No pipeline context β€” execute directly (standalone mode).
+ let result = f(ctx.clone()).await?;
+ ctx.check_cancellation()?;
+ return Ok(result);
+ };
+ let PipelineMiss {
+ comp_ctx,
+ fp,
+ fn_ctx,
+ memo_states,
+ guard,
+ _frame,
+ } = *miss;
+ let result = f(ctx.clone()).await?;
ctx.check_cancellation()?;
- // The hit skips the body, so carry what it would have declared: this
- // entry (which owns its target states) and its provider generations.
- record_dependency_memo_entry(&fn_ctx, fp);
- guard.join_cached_target_provider_deps(&fn_ctx);
- // ... and the logic deps the entry recorded beneath this fn's own fp,
- // through this frame so the caller's `logic_tracking` applies as on a
- // miss.
- guard.join_cached_logic_deps(&fn_ctx);
- if states_changed
- || context_validation.states_changed
- || data_deps.as_ref().is_some_and(|dd| dd.states_changed)
- {
- guard.update_memo_states(MemoStatesPayload {
- positional: memo_states_for_resolve,
- by_context_fp: context_validation.states,
- data_deps: data_deps.map(|dd| dd.records).unwrap_or_default(),
- });
+ let value = Value::from_serializable(&result)?;
+ let memo_states = MemoStatesPayload {
+ positional: memo_states,
+ by_context_fp: fn_ctx.collect_context_initial_states(comp_ctx.app_ctx().env()),
+ // The entry's records come from the frame (`build_fn_call_memo`).
+ data_deps: Vec::new(),
+ };
+ // Recorded after `resolve`, which snapshots the frame's dependency
+ // entries: an entry must not list itself.
+ if guard.resolve(&fn_ctx, || value, memo_states)? {
+ record_dependency_memo_entry(&fn_ctx, fp);
}
- // After the refresh, so the records re-offered to a caller stored
- // later are the refreshed ones.
- guard.join_cached_data_deps(&fn_ctx);
- return Ok(value);
- }
-
- let result = f(ctx.with_fn_ctx(fn_ctx.clone())).await?;
- ctx.check_cancellation()?;
- let value = Value::from_serializable(&result)?;
- let memo_states = MemoStatesPayload {
- positional: memo_states_for_resolve,
- by_context_fp: fn_ctx.collect_context_initial_states(comp_ctx.app_ctx().env()),
- // The entry's records come from the frame (`build_fn_call_memo`).
- data_deps: Vec::new(),
- };
- // Recorded after `resolve`, which snapshots the frame's dependency
- // entries: an entry must not list itself.
- if guard.resolve(&fn_ctx, || value, memo_states)? {
- record_dependency_memo_entry(&fn_ctx, fp);
+ Ok(result)
}
- Ok(result)
}
fn record_dependency_memo_entry(fn_ctx: &FnCallContext, fp: Fingerprint) {
@@ -917,9 +1104,72 @@ pub async fn collect_memo_arg_state<T: MemoInput + ?Sized>(
value: &T,
prev: Option<&MemoStateValue>,
) -> Result<Option<MemoStateDecision>> {
+ if !value.has_memo_state() {
+ return Ok(None);
+ }
value.memo_state(prev).await
}
+/// Wraps a `#[cocoindex::function(memo)]` argument so the generated code can
+/// pick its memo identity by method resolution (autoref specialization): an
+/// argument whose type implements [`MemoInput`] uses its identity and state
+/// (`MemoArgKeyViaMemoInput`, `MemoArgStateViaMemoInput`); any other
+/// `Serialize` argument, such as a target handle, uses its serialized value
+/// and has no state (`MemoArgKeyViaSerialize`, `MemoArgStateViaSerialize`).
+#[doc(hidden)]
+pub struct MemoArg<'a, T: ?Sized>(pub &'a T);
+
+#[doc(hidden)]
+pub trait MemoArgKeyViaMemoInput {
+ fn __coco_write_memo_key(&self, fingerprinter: &mut Fingerprinter) -> Result<()>;
+}
+
+impl<T: MemoInput + ?Sized> MemoArgKeyViaMemoInput for &MemoArg<'_, T> {
+ fn __coco_write_memo_key(&self, fingerprinter: &mut Fingerprinter) -> Result<()> {
+ write_key_fingerprint_part_for_arg(fingerprinter, self.0)
+ }
+}
+
+#[doc(hidden)]
+pub trait MemoArgKeyViaSerialize {
+ fn __coco_write_memo_key(&self, fingerprinter: &mut Fingerprinter) -> Result<()>;
+}
+
+impl<T: Serialize + ?Sized> MemoArgKeyViaSerialize for MemoArg<'_, T> {
+ fn __coco_write_memo_key(&self, fingerprinter: &mut Fingerprinter) -> Result<()> {
+ write_key_fingerprint_part(fingerprinter, self.0)
+ }
+}
+
+#[doc(hidden)]
+pub trait MemoArgStateViaMemoInput {
+ fn __coco_memo_state_input(&self) -> Option<&dyn MemoInput>;
+}
+
+impl<T: MemoInput> MemoArgStateViaMemoInput for &MemoArg<'_, T> {
+ fn __coco_memo_state_input(&self) -> Option<&dyn MemoInput> {
+ Some(self.0)
+ }
+}
+
+#[doc(hidden)]
+pub trait MemoArgStateViaSerialize {
+ fn __coco_memo_state_input(&self) -> Option<&dyn MemoInput>;
+}
+
+impl<T: Serialize + ?Sized> MemoArgStateViaSerialize for MemoArg<'_, T> {
+ fn __coco_memo_state_input(&self) -> Option<&dyn MemoInput> {
+ None
+ }
+}
+
+/// Whether any of `children` has memo state, for the [`crate::MemoInput`]
+/// derive.
+#[doc(hidden)]
+pub fn any_has_memo_state(children: &[&dyn MemoInput]) -> bool {
+ children.iter().any(|child| child.has_memo_state())
+}
+
pub(crate) async fn file_memo_state(
file: &dyn FileLike,
prev: Option<&MemoStateValue>,
@@ -979,6 +1229,10 @@ fn system_time_nanos(time: SystemTime) -> u128 {
#[cfg(test)]
mod tests {
use super::*;
+ #[allow(unused_imports)]
+ use super::{
+ MemoArgKeyViaMemoInput as _, MemoArgKeyViaSerialize as _, MemoArgStateViaMemoInput as _,
+ };
#[derive(Clone)]
struct Tracked {
@@ -1037,6 +1291,28 @@ mod tests {
decision.state.clone()
}
+ /// The `#[function(memo)]` argument key picks the `MemoInput` identity
+ /// whenever the type has one, unsized slices included, so the key of a
+ /// `MemoInput` argument is what it was before the `Serialize` fallback.
+ #[test]
+ fn memo_arg_key_prefers_memo_input_identity() {
+ fn via_arg_path<T: MemoInput + ?Sized>(value: &T) -> Fingerprint {
+ let mut fp = Fingerprinter::default();
+ write_key_fingerprint_part_for_arg(&mut fp, value).unwrap();
+ fp.into_fingerprint()
+ }
+ let slice: &[u32] = &[1, 2, 3];
+ let mut fp = Fingerprinter::default();
+ (&&MemoArg(slice)).__coco_write_memo_key(&mut fp).unwrap();
+ assert_eq!(fp.into_fingerprint(), via_arg_path(slice));
+
+ let mut serde_fp = Fingerprinter::default();
+ write_key_fingerprint_part(&mut serde_fp, slice).unwrap();
+ assert_ne!(via_arg_path(slice), serde_fp.into_fingerprint());
+
+ assert!((&&MemoArg(&vec![1u32])).__coco_memo_state_input().is_some());
+ }
+
#[test]
fn recursive_sequence_fingerprints_are_framed_and_ordered() {
assert_ne!(
diff --git a/rust/sdk/cocoindex/src/ops/api.rs b/rust/sdk/cocoindex/src/ops/api.rs
index acf6646b..e19130c3 100644
--- a/rust/sdk/cocoindex/src/ops/api.rs
+++ b/rust/sdk/cocoindex/src/ops/api.rs
@@ -695,7 +695,7 @@ async fn chat_json_memoized(
client: &ApiChatClient,
messages: &[ChatMessage],
) -> Result<String> {
- client.request_chat_json(Some(ctx), &messages).await
+ client.request_chat_json(Some(ctx), messages).await
}
#[derive(Deserialize)]
@@ -753,7 +753,7 @@ async fn resolve_pair_memoized(
candidates: &[String],
resolver: &LlmPairResolver,
) -> Result<PairDecision> {
- resolver.request_decision(ctx, &entity, &candidates).await
+ resolver.request_decision(ctx, entity, candidates).await
}
impl LlmPairResolver {
diff --git a/rust/sdk/cocoindex/src/prelude.rs b/rust/sdk/cocoindex/src/prelude.rs
index 7ce03c3d..762ce2eb 100644
--- a/rust/sdk/cocoindex/src/prelude.rs
+++ b/rust/sdk/cocoindex/src/prelude.rs
@@ -56,6 +56,6 @@ pub use crate::{
UpdateOptions,
};
-pub use crate::{app, function, lifespan, main, mount, mount_each, use_mount};
+pub use crate::{app, function, lifespan, main, mount, mount_each, use_mount, use_mount_each};
pub use serde::{Deserialize, Serialize};
diff --git a/rust/sdk/cocoindex/src/target_state.rs b/rust/sdk/cocoindex/src/target_state.rs
index 601d2b70..0f72cab4 100644
--- a/rust/sdk/cocoindex/src/target_state.rs
+++ b/rust/sdk/cocoindex/src/target_state.rs
@@ -16,6 +16,14 @@ use crate::profile::{
Action, BoxedHandler, BoxedSink, ChildHandlerFn, RustProfile, SinkChildren, SinkFuture, Value,
};
+/// A value usable as a [`StableKey`]: a target-state key, a mount key
+/// (`ctx.mount`, `mount_each`, `with_subpath`, …) or a user-state key. The
+/// Rust analogue of Python's `StableKey` union: a string stores as
+/// [`StableKey::Str`], an integer as [`StableKey::Int`], a UUID as
+/// [`StableKey::Uuid`], bytes as [`StableKey::Bytes`], a `bool` as
+/// [`StableKey::Bool`] and `()` as [`StableKey::Null`]; pass a [`StableKey`]
+/// for a symbol or an array. A reference to any of these converts like the
+/// value.
pub trait IntoStableKey {
fn into_stable_key(self) -> StableKey;
}
@@ -26,6 +34,12 @@ impl IntoStableKey for StableKey {
}
}
+impl<T: IntoStableKey + Clone> IntoStableKey for &T {
+ fn into_stable_key(self) -> StableKey {
+ self.clone().into_stable_key()
+ }
+}
+
impl IntoStableKey for &str {
fn into_stable_key(self) -> StableKey {
StableKey::Str(Arc::from(self))
@@ -38,9 +52,53 @@ impl IntoStableKey for String {
}
}
-impl IntoStableKey for i64 {
+impl IntoStableKey for () {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Null
+ }
+}
+
+impl IntoStableKey for bool {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Bool(self)
+ }
+}
+
+macro_rules! impl_int_stable_key {
+ ($($ty:ty),+ $(,)?) => {
+ $(
+ impl IntoStableKey for $ty {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Int(i64::from(self))
+ }
+ }
+ )+
+ };
+}
+
+impl_int_stable_key!(i8, i16, i32, i64, u8, u16, u32);
+
+impl IntoStableKey for uuid::Uuid {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Uuid(self)
+ }
+}
+
+impl IntoStableKey for Vec<u8> {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Bytes(Arc::from(self))
+ }
+}
+
+impl IntoStableKey for &[u8] {
+ fn into_stable_key(self) -> StableKey {
+ StableKey::Bytes(Arc::from(self))
+ }
+}
+
+impl IntoStableKey for bytes::Bytes {
fn into_stable_key(self) -> StableKey {
- StableKey::Int(self)
+ StableKey::Bytes(Arc::from(self.as_ref()))
}
}
diff --git a/rust/sdk/cocoindex/tests/admission.rs b/rust/sdk/cocoindex/tests/admission.rs
new file mode 100644
index 00000000..1f07165f
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/admission.rs
@@ -0,0 +1,39 @@
+//! The number of components an app runs at once: 1024 by default, as in
+//! Python, or the builder's `max_inflight_components`. The environment
+//! variable is covered by `admission_env.rs`, which owns its process.
+//!
+//! cargo test -p cocoindex --test admission
+
+mod admission_common;
+
+use admission_common::count_admitted;
+use cocoindex::Environment;
+
+#[tokio::test]
+async fn default_limit_is_1024_components() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap()
+ .app("admission_default")
+ .await
+ .unwrap();
+ assert_eq!(count_admitted(&app, 1030).await, 1024);
+}
+
+#[tokio::test]
+async fn builder_limit_bounds_components() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .max_inflight_components(3)
+ .build()
+ .await
+ .unwrap()
+ .app("admission_builder")
+ .await
+ .unwrap();
+ assert_eq!(count_admitted(&app, 10).await, 3);
+}
diff --git a/rust/sdk/cocoindex/tests/admission_common/mod.rs b/rust/sdk/cocoindex/tests/admission_common/mod.rs
new file mode 100644
index 00000000..57281bad
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/admission_common/mod.rs
@@ -0,0 +1,60 @@
+//! Shared by `admission.rs` and `admission_env.rs`.
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::{Duration, Instant};
+
+use cocoindex::App;
+use tokio::sync::Semaphore;
+
+/// Mount `children` background components that block until released and
+/// return how many of them were running once the count stopped growing:
+/// the app's limit, when `children` exceeds it.
+pub async fn count_admitted(app: &App, children: usize) -> usize {
+ let started = Arc::new(AtomicUsize::new(0));
+ let gate = Arc::new(Semaphore::new(0));
+ let admitted = Arc::new(AtomicUsize::new(0));
+
+ let observer = tokio::spawn({
+ let (started, gate, admitted) = (started.clone(), gate.clone(), admitted.clone());
+ async move {
+ let mut last = usize::MAX;
+ let mut stable_since = Instant::now();
+ loop {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ let now = started.load(Ordering::SeqCst);
+ if now != last {
+ last = now;
+ stable_since = Instant::now();
+ } else if now > 0 && stable_since.elapsed() > Duration::from_millis(500) {
+ break;
+ }
+ }
+ admitted.store(started.load(Ordering::SeqCst), Ordering::SeqCst);
+ gate.add_permits(children);
+ }
+ });
+
+ let (started_outer, gate_outer) = (started.clone(), gate.clone());
+ app.update(move |ctx| async move {
+ let handle = ctx
+ .mount_each(0..children, |i| *i as i64, {
+ move |_child, _i| {
+ let (started, gate) = (started_outer.clone(), gate_outer.clone());
+ async move {
+ started.fetch_add(1, Ordering::SeqCst);
+ let _permit = gate.acquire().await.unwrap();
+ Ok(())
+ }
+ }
+ })
+ .await?;
+ handle.ready().await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ observer.await.unwrap();
+ assert_eq!(started.load(Ordering::SeqCst), children);
+ admitted.load(Ordering::SeqCst)
+}
diff --git a/rust/sdk/cocoindex/tests/admission_env.rs b/rust/sdk/cocoindex/tests/admission_env.rs
new file mode 100644
index 00000000..fd4dbe1f
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/admission_env.rs
@@ -0,0 +1,48 @@
+//! `COCOINDEX_MAX_INFLIGHT_COMPONENTS` sets the number of components an app
+//! runs at once when the builder sets none, read when the app is created, as
+//! in Python. One test, alone in its process: it sets the variable.
+//!
+//! cargo test -p cocoindex --test admission_env
+
+mod admission_common;
+
+use admission_common::count_admitted;
+use cocoindex::Environment;
+
+#[tokio::test]
+async fn environment_variable_sets_the_limit() {
+ // SAFETY: this is the only test in this binary, so no other thread reads
+ // the environment while it is written.
+ unsafe { std::env::set_var("COCOINDEX_MAX_INFLIGHT_COMPONENTS", "lots") };
+ let dir = tempfile::tempdir().unwrap();
+ let env = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap();
+ let Err(err) = env.app("admission_env_bad").await else {
+ panic!("an unparsable limit must be an error");
+ };
+ assert!(
+ err.to_string()
+ .contains("COCOINDEX_MAX_INFLIGHT_COMPONENTS"),
+ "{err}"
+ );
+
+ unsafe { std::env::set_var("COCOINDEX_MAX_INFLIGHT_COMPONENTS", "5") };
+ let app = env.app("admission_env").await.unwrap();
+ assert_eq!(count_admitted(&app, 12).await, 5);
+
+ // The builder's value wins over the variable.
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .max_inflight_components(2)
+ .build()
+ .await
+ .unwrap()
+ .app("admission_env_builder")
+ .await
+ .unwrap();
+ assert_eq!(count_admitted(&app, 12).await, 2);
+}
diff --git a/rust/sdk/cocoindex/tests/amazon_s3_source.rs b/rust/sdk/cocoindex/tests/amazon_s3_source.rs
index e31dc32e..d5c154aa 100644
--- a/rust/sdk/cocoindex/tests/amazon_s3_source.rs
+++ b/rust/sdk/cocoindex/tests/amazon_s3_source.rs
@@ -232,7 +232,7 @@ async fn s3_source_mount_each_pipeline_when_available() -> Result<()> {
#[cocoindex::function(memo)]
async fn process(ctx: &cocoindex::Ctx, file: &S3File) -> Result<usize> {
- let bytes = ctx.get_key(&S3)?.read(&file).await?;
+ let bytes = ctx.get_key(&S3)?.read(file).await?;
Ok(bytes.len())
}
@@ -255,7 +255,7 @@ async fn s3_source_mount_each_pipeline_when_available() -> Result<()> {
.list()
.await?;
let sizes = ctx
- .mount_each(
+ .use_mount_each(
files,
|f| f.key(),
|child, file| async move { process(&child, &file).await },
diff --git a/rust/sdk/cocoindex/tests/azure_blob_source.rs b/rust/sdk/cocoindex/tests/azure_blob_source.rs
index 4fafacb7..87d119a4 100644
--- a/rust/sdk/cocoindex/tests/azure_blob_source.rs
+++ b/rust/sdk/cocoindex/tests/azure_blob_source.rs
@@ -623,7 +623,7 @@ async fn mount_each_pipeline_reprocesses_only_changed_blobs() -> Result<()> {
.list()
.await?;
let sizes = ctx
- .mount_each(
+ .use_mount_each(
files,
|f| f.key(),
|child, file| async move { process(&child, &file).await },
diff --git a/rust/sdk/cocoindex/tests/deadline.rs b/rust/sdk/cocoindex/tests/deadline.rs
index 412780a5..3ba22eba 100644
--- a/rust/sdk/cocoindex/tests/deadline.rs
+++ b/rust/sdk/cocoindex/tests/deadline.rs
@@ -385,12 +385,12 @@ async fn rust_sdk_deadline_conformance_subset() {
}
#[tokio::test]
-async fn mount_each_drains_started_siblings_on_deadline_error() {
+async fn use_mount_each_drains_started_siblings_on_deadline_error() {
// One child failing with DeadlineExceeded must not drop its started
// siblings: every started item runs to completion (including its
// commit), then the first error is returned. Child B only begins its
// work after A has already failed, so B's committed row below is only
- // possible if mount_each drained instead of cancelling.
+ // possible if use_mount_each drained instead of cancelling.
let _clock = TestClockGuard::new();
let (app, _dir) = temp_app("mount_each_drain").await;
let applied: Arc<Mutex<Vec<WriteAction>>> = Arc::new(Mutex::new(Vec::new()));
@@ -403,7 +403,7 @@ async fn mount_each_drains_started_siblings_on_deadline_error() {
let gate = gate.clone();
async move {
let out = ctx
- .mount_each(
+ .use_mount_each(
["a", "b"],
|item| item.to_string(),
move |child, item| {
@@ -429,7 +429,7 @@ async fn mount_each_drains_started_siblings_on_deadline_error() {
.await;
assert!(
matches!(out, Err(ref e) if e.is_deadline_exceeded()),
- "mount_each must surface A's deadline error"
+ "use_mount_each must surface A's deadline error"
);
Ok(())
}
@@ -444,6 +444,6 @@ async fn mount_each_drains_started_siblings_on_deadline_error() {
key: "\"row-1\"".to_string(),
value: "b-done".to_string(),
}],
- "B's started work must drain to commit before mount_each returns"
+ "B's started work must drain to commit before use_mount_each returns"
);
}
diff --git a/rust/sdk/cocoindex/tests/inspect.rs b/rust/sdk/cocoindex/tests/inspect.rs
index c0270600..5c60b952 100644
--- a/rust/sdk/cocoindex/tests/inspect.rs
+++ b/rust/sdk/cocoindex/tests/inspect.rs
@@ -34,7 +34,7 @@ async fn run_app(root: &Path) -> (Environment, App) {
app.update(move |ctx| async move {
let target = mount_dir_target(&ctx, out)?;
let files = walk_items(src, &["*.txt"])?;
- let outputs = mount_each!(files, |file| upper(ctx, file)).await?;
+ let outputs = use_mount_each!(files, |file| upper(ctx, file)).await?;
for (name, text) in &outputs {
target.declare_file(&ctx, name, text.as_bytes())?;
}
@@ -49,6 +49,12 @@ fn child(key: &str) -> StablePath {
StablePath::root().concat_part(key.into_stable_key())
}
+/// The path of the `use_mount_each!(files, |file| upper(ctx, file))` child
+/// for `name`: `upper/<name>`, the function name being the prefix.
+fn upper_child(name: &str) -> StablePath {
+ child("upper").concat_part(name.into_stable_key())
+}
+
fn paths_of(details: &[StablePathDetail]) -> Vec<String> {
details.iter().map(|d| d.path.to_string()).collect()
}
@@ -69,18 +75,32 @@ async fn stable_paths_of_a_run() {
.iter()
.map(ToString::to_string)
.collect();
- assert_eq!(paths, ["/", "/\"upper/a.txt\"", "/\"upper/b.txt\""]);
+ assert_eq!(
+ paths,
+ [
+ "/",
+ "/\"upper\"",
+ "/\"upper\"/\"a.txt\"",
+ "/\"upper\"/\"b.txt\""
+ ]
+ );
let infos: Vec<_> = inspect::iter_stable_paths(&app)
.await
.try_collect()
.await
.unwrap();
- assert_eq!(infos.len(), 3);
- assert!(
- infos
- .iter()
- .all(|info| info.node_type == StablePathNodeType::Component)
+ assert_eq!(infos.len(), 4);
+ // `upper` is the directory between the root and the per-file components.
+ let node_types: Vec<_> = infos.iter().map(|info| info.node_type).collect();
+ assert_eq!(
+ node_types,
+ [
+ StablePathNodeType::Component,
+ StablePathNodeType::Directory,
+ StablePathNodeType::Component,
+ StablePathNodeType::Component,
+ ]
);
let by_name: Vec<_> = inspect::iter_stable_paths_by_name(&env, APP_NAME)
@@ -104,7 +124,12 @@ async fn details_of_stable_paths() {
.unwrap();
assert_eq!(
paths_of(&details),
- ["/", "/\"upper/a.txt\"", "/\"upper/b.txt\""]
+ [
+ "/",
+ "/\"upper\"",
+ "/\"upper\"/\"a.txt\"",
+ "/\"upper\"/\"b.txt\""
+ ]
);
// The root component owns both files of the directory target.
@@ -139,14 +164,14 @@ async fn details_of_stable_paths() {
assert_eq!(files, ["a.txt", "b.txt"]);
// A mounted component: memoized, no target states of its own.
- let a = &details[1];
+ let a = &details[2];
assert_eq!(a.processor_name, "mount:upper");
assert!(a.has_memoization);
assert_eq!(a.target_state_count, 0);
assert!(a.target_state_items.is_empty());
// One path at a time reads the same records as the stream.
- let a_path = child("upper/a.txt");
+ let a_path = upper_child("a.txt");
let one = inspect::get_stable_path_detail(&app, &a_path)
.await
.unwrap()
@@ -182,7 +207,7 @@ async fn query_adds_children_and_parents() {
let dir = tempfile::tempdir().unwrap();
let (env, app) = run_app(dir.path()).await;
let root = StablePath::root();
- let a_path = child("upper/a.txt");
+ let a_path = upper_child("a.txt");
let alone = inspect::query_stable_path_details(&app, &root, StablePathQuery::default())
.await
@@ -196,15 +221,13 @@ async fn query_adds_children_and_parents() {
let children = inspect::query_stable_path_details(&app, &root, with_children)
.await
.unwrap();
- assert_eq!(
- paths_of(&children),
- ["/", "/\"upper/a.txt\"", "/\"upper/b.txt\""]
- );
+ // Direct children only: the per-file components sit below `upper`.
+ assert_eq!(paths_of(&children), ["/", "/\"upper\""]);
// A leaf has no children to add.
let leaf = inspect::query_stable_path_details(&app, &a_path, with_children)
.await
.unwrap();
- assert_eq!(paths_of(&leaf), ["/\"upper/a.txt\""]);
+ assert_eq!(paths_of(&leaf), ["/\"upper\"/\"a.txt\""]);
let with_parents = StablePathQuery {
include_parents: true,
@@ -213,7 +236,10 @@ async fn query_adds_children_and_parents() {
let parents = inspect::query_stable_path_details(&app, &a_path, with_parents)
.await
.unwrap();
- assert_eq!(paths_of(&parents), ["/", "/\"upper/a.txt\""]);
+ assert_eq!(
+ paths_of(&parents),
+ ["/", "/\"upper\"", "/\"upper\"/\"a.txt\""]
+ );
assert_eq!(parents[0].target_state_count, 2);
let by_name = inspect::query_stable_path_details_by_name(&env, APP_NAME, &a_path, with_parents)
@@ -264,7 +290,8 @@ async fn target_states_with_their_owner() {
let out_dir = out.clone();
app.update(move |ctx| async move {
let target = mount_dir_target(&ctx, out_dir)?;
- let outputs = mount_each!(walk_items(src, &["*.txt"])?, |file| upper(ctx, file)).await?;
+ let outputs =
+ use_mount_each!(walk_items(src, &["*.txt"])?, |file| upper(ctx, file)).await?;
for (name, text) in &outputs {
target.declare_file(&ctx, name, text.as_bytes())?;
}
@@ -281,7 +308,7 @@ async fn target_states_with_their_owner() {
assert_eq!(readable, [expected("a.txt")]);
assert_eq!(
inspect::list_stable_paths(&app).await.unwrap().len(),
- 2,
+ 3,
"the component of the removed file is gone too"
);
}
diff --git a/rust/sdk/cocoindex/tests/memo_clone.rs b/rust/sdk/cocoindex/tests/memo_clone.rs
new file mode 100644
index 00000000..077002c2
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/memo_clone.rs
@@ -0,0 +1,220 @@
+//! `#[cocoindex::function(memo)]` borrows its arguments for the memo probe
+//! and moves them into the body only on a miss, and `MemoInput::has_memo_state`
+//! lets a plain-data argument skip the state call.
+//!
+//! cargo test -p cocoindex --test memo_clone
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use cocoindex::memo::{MemoInput, MemoKeyWriter, MemoStateDecision, MemoStateValue};
+use cocoindex::prelude::*;
+use cocoindex::resources::fs::FileEntry;
+
+async fn temp_app(name: &str) -> (App, tempfile::TempDir) {
+ let dir = tempfile::tempdir().unwrap();
+ let app = App::builder(name)
+ .db_path(dir.path().join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap();
+ (app, dir)
+}
+
+static PAYLOAD_CLONES: AtomicUsize = AtomicUsize::new(0);
+static BY_VALUE_CALLS: AtomicUsize = AtomicUsize::new(0);
+static BY_REF_CALLS: AtomicUsize = AtomicUsize::new(0);
+
+/// A memo input whose clones are counted.
+#[derive(cocoindex::MemoInput)]
+struct Payload {
+ text: String,
+}
+
+impl Clone for Payload {
+ fn clone(&self) -> Self {
+ PAYLOAD_CLONES.fetch_add(1, Ordering::SeqCst);
+ Self {
+ text: self.text.clone(),
+ }
+ }
+}
+
+/// A memo input that cannot be cloned at all.
+#[derive(cocoindex::MemoInput)]
+struct NotClone {
+ n: u32,
+}
+
+#[cocoindex::function(memo)]
+async fn by_value(_ctx: &Ctx, payload: Payload, extra: NotClone) -> Result<usize> {
+ BY_VALUE_CALLS.fetch_add(1, Ordering::SeqCst);
+ Ok(payload.text.len() + extra.n as usize)
+}
+
+#[cocoindex::function(memo)]
+async fn by_ref(_ctx: &Ctx, payload: &Payload, name: &str, items: &[u32]) -> Result<usize> {
+ BY_REF_CALLS.fetch_add(1, Ordering::SeqCst);
+ Ok(payload.text.len() + name.len() + items.len())
+}
+
+/// Neither a miss nor a hit clones an argument: the key and the state probe
+/// borrow it, and on a miss the function's own argument moves into the body.
+#[tokio::test]
+async fn memo_function_never_clones_its_arguments() {
+ let (app, _dir) = temp_app("memo_no_clone").await;
+ for expected_calls in [1, 1] {
+ let (value, by_ref_value) = app
+ .update(|ctx| async move {
+ let value = by_value(
+ &ctx,
+ Payload {
+ text: "hello".to_string(),
+ },
+ NotClone { n: 2 },
+ )
+ .await?;
+ let payload = Payload {
+ text: "hi".to_string(),
+ };
+ let by_ref_value = by_ref(&ctx, &payload, "name", &[1, 2, 3]).await?;
+ Ok((value, by_ref_value))
+ })
+ .await
+ .unwrap();
+ assert_eq!(value, 7);
+ assert_eq!(by_ref_value, 9);
+ assert_eq!(BY_VALUE_CALLS.load(Ordering::SeqCst), expected_calls);
+ assert_eq!(BY_REF_CALLS.load(Ordering::SeqCst), expected_calls);
+ assert_eq!(PAYLOAD_CLONES.load(Ordering::SeqCst), 0);
+ }
+}
+
+static STATE_CALLS: AtomicUsize = AtomicUsize::new(0);
+
+/// A manual `MemoInput` that declares it has no state: its `memo_state` must
+/// never be called.
+struct Stateless;
+
+#[cocoindex::async_trait]
+impl MemoInput for Stateless {
+ fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()> {
+ writer.write(&"stateless")
+ }
+
+ fn has_memo_state(&self) -> bool {
+ false
+ }
+
+ async fn memo_state(
+ &self,
+ _previous: Option<&MemoStateValue>,
+ ) -> Result<Option<MemoStateDecision>> {
+ STATE_CALLS.fetch_add(1, Ordering::SeqCst);
+ Ok(None)
+ }
+}
+
+#[cocoindex::function(memo)]
+async fn with_stateless(_ctx: &Ctx, _arg: Stateless, _plain: Vec<Payload>) -> Result<u32> {
+ Ok(1)
+}
+
+#[derive(cocoindex::MemoInput)]
+struct WithFile {
+ label: String,
+ file: FileEntry,
+}
+
+#[derive(cocoindex::MemoInput)]
+enum Source {
+ Plain(u32),
+ File(WithFile),
+}
+
+#[tokio::test]
+async fn stateless_inputs_skip_the_state_probe() {
+ let (app, _dir) = temp_app("memo_stateless").await;
+ for _ in 0..2 {
+ app.update(|ctx| async move {
+ with_stateless(
+ &ctx,
+ Stateless,
+ vec![Payload {
+ text: "x".to_string(),
+ }],
+ )
+ .await
+ })
+ .await
+ .unwrap();
+ }
+ assert_eq!(STATE_CALLS.load(Ordering::SeqCst), 0);
+}
+
+/// Derived and composite inputs have state exactly when an element does:
+/// plain data does not, a file (validated by mtime and content) does.
+#[test]
+fn has_memo_state_follows_the_elements() {
+ assert!(!Payload { text: "a".into() }.has_memo_state());
+ assert!(!(1u32, "s".to_string()).has_memo_state());
+ assert!(!vec![NotClone { n: 1 }].has_memo_state());
+ assert!(!Source::Plain(1).has_memo_state());
+ assert!(!Option::<Payload>::None.has_memo_state());
+
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(dir.path().join("a.txt"), "a").unwrap();
+ let file = walk(dir.path(), &["*.txt"])
+ .unwrap()
+ .into_iter()
+ .next()
+ .unwrap();
+ assert!(file.has_memo_state());
+ assert!(
+ Source::File(WithFile {
+ label: "l".into(),
+ file: file.clone(),
+ })
+ .has_memo_state()
+ );
+ assert!(vec![file].has_memo_state());
+}
+
+// ---------------------------------------------------------------------------
+// A target handle as a memoized argument
+// ---------------------------------------------------------------------------
+
+static RENDER_CALLS: AtomicUsize = AtomicUsize::new(0);
+
+/// A target handle is `Serialize` (its stable identity) but not `MemoInput`:
+/// a memoized function keys it by its serialized value, as Python memoizes a
+/// target on its key.
+#[cocoindex::function(memo)]
+async fn render(ctx: &Ctx, name: &str, target: &DirTarget) -> Result<()> {
+ RENDER_CALLS.fetch_add(1, Ordering::SeqCst);
+ target.declare_file(ctx, &format!("{name}.txt"), name.as_bytes())
+}
+
+#[tokio::test]
+async fn memo_function_takes_a_target_handle() {
+ let (app, dir) = temp_app("memo_target_arg").await;
+ let run = |out: std::path::PathBuf| {
+ let app = app.clone();
+ async move {
+ app.update(move |ctx| async move {
+ let target = DirTarget::mount(&ctx, &out)?;
+ render(&ctx, "a", &target).await
+ })
+ .await
+ .unwrap()
+ }
+ };
+ let out = dir.path().join("out");
+ run(out.clone()).await;
+ run(out.clone()).await;
+ assert_eq!(RENDER_CALLS.load(Ordering::SeqCst), 1, "same target: a hit");
+ assert_eq!(std::fs::read(out.join("a.txt")).unwrap(), b"a");
+
+ // A different target is a different key.
+ run(dir.path().join("other")).await;
+ assert_eq!(RENDER_CALLS.load(Ordering::SeqCst), 2);
+}
diff --git a/rust/sdk/cocoindex/tests/memo_deps.rs b/rust/sdk/cocoindex/tests/memo_deps.rs
index 2f04bb50..2ac35a96 100644
--- a/rust/sdk/cocoindex/tests/memo_deps.rs
+++ b/rust/sdk/cocoindex/tests/memo_deps.rs
@@ -138,13 +138,13 @@ async fn records(ctx: &Ctx, test: &str, name: &str, value: &str) -> Result<Strin
#[cocoindex::function(memo)]
async fn caller_full(ctx: &Ctx, test: &str, value: &str) -> Result<String> {
increment(&format!("{test}/caller_full"));
- records(ctx, &test, "rust", &value).await
+ records(ctx, test, "rust", value).await
}
#[cocoindex::function(memo, logic_tracking = "self", version = 1)]
async fn caller_self(ctx: &Ctx, test: &str, value: &str) -> Result<String> {
increment(&format!("{test}/caller_self"));
- records(ctx, &test, "rust", &value).await
+ records(ctx, test, "rust", value).await
}
#[test]
@@ -482,7 +482,7 @@ fn session_body(ctx: &Ctx, test: &str, name: &str) -> Result<String> {
#[cocoindex::function(memo)]
async fn session(ctx: &Ctx, test: &str, name: &str) -> Result<String> {
- session_body(ctx, &test, &name)
+ session_body(ctx, test, name)
}
#[test]
@@ -533,7 +533,7 @@ fn a_memoized_function_is_reused_while_its_reads_are_unchanged() {
#[cocoindex::function(memo, logic_tracking = "self", version = 1)]
async fn outer_self(ctx: &Ctx, test: &str, name: &str) -> Result<String> {
increment(&format!("{test}/run.outer"));
- Ok(format!("outer:{}", session(ctx, &test, &name).await?))
+ Ok(format!("outer:{}", session(ctx, test, name).await?))
}
#[test]
@@ -633,7 +633,7 @@ fn an_open_component_is_reused_while_its_reads_are_unchanged() {
#[cocoindex::function(memo)]
async fn conflicting(ctx: &Ctx, test: &str) -> Result<()> {
increment(&format!("{test}/run"));
- let kind = kind(&test);
+ let kind = kind(test);
ctx.use_data_dep(&kind, &"k".to_string(), &(1, Fingerprint::from_bytes(b"x")))?;
ctx.use_data_dep(&kind, &"k".to_string(), &(2, Fingerprint::from_bytes(b"x")))?;
Ok(())
diff --git a/rust/sdk/cocoindex/tests/mount.rs b/rust/sdk/cocoindex/tests/mount.rs
index 63d51e78..acec7f29 100644
--- a/rust/sdk/cocoindex/tests/mount.rs
+++ b/rust/sdk/cocoindex/tests/mount.rs
@@ -501,13 +501,13 @@ async fn with_subpath_nests_child_paths() {
.await;
app.update(|ctx| async move {
- let process = ctx.with_subpath(&"process");
+ let process = ctx.with_subpath("process");
process
.mount(&"a.md", |_child| async move { Err(Error::engine("boom")) })
.await?
.ready()
.await?;
- let ctx = &process.with_subpath(&"nested");
+ let ctx = &process.with_subpath("nested");
cocoindex::mount!("b.md", fail_under_subpath(ctx, "b".to_string()))
.await?
.ready()
@@ -543,7 +543,7 @@ async fn with_subpath_is_the_same_component_as_the_direct_path() {
let sink = recording_sink(log.clone());
app.update(move |ctx| async move {
let provider = root_provider(&ctx, sink)?;
- ctx.with_subpath(&"process")
+ ctx.with_subpath("process")
.mount(&"x", move |child| async move {
declare_target_state(&child, provider.target_state("x", "v1".to_string()))
})
@@ -558,7 +558,7 @@ async fn with_subpath_is_the_same_component_as_the_direct_path() {
let sink = recording_sink(log.clone());
app.update(move |ctx| async move {
let provider = root_provider(&ctx, sink)?;
- ctx.with_subpath(&"process")
+ ctx.with_subpath("process")
.mount(&"x", move |child| async move {
declare_target_state(&child, provider.target_state("x", "v1".to_string()))
})
@@ -598,7 +598,7 @@ async fn use_state_is_rejected_on_a_subpath_ctx() {
let message = app
.update(|ctx| async move {
let err = ctx
- .with_subpath(&"process")
+ .with_subpath("process")
.use_state("counter", 0u32)
.err()
.expect("use_state on a subpath ctx must fail");
diff --git a/rust/sdk/cocoindex/tests/mount_each.rs b/rust/sdk/cocoindex/tests/mount_each.rs
new file mode 100644
index 00000000..3c1a1449
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/mount_each.rs
@@ -0,0 +1,336 @@
+//! `Ctx::mount_each` / `mount_each!` as background, streaming mounts (the
+//! Python `coco.mount_each` shape), `use_mount_each` as their value-returning
+//! form, and typed mount keys.
+//!
+//! cargo test -p cocoindex --test mount_each
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cocoindex::prelude::*;
+use cocoindex::{Environment, inspect};
+use tokio::sync::Semaphore;
+
+async fn temp_app(name: &str) -> (App, tempfile::TempDir) {
+ let dir = tempfile::tempdir().unwrap();
+ let app = App::builder(name)
+ .db_path(dir.path().join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap();
+ (app, dir)
+}
+
+/// The failing paths and their parents, as the environment's exception
+/// handler saw them.
+type SeenPaths = Arc<Mutex<Vec<(String, Option<String>)>>>;
+
+async fn temp_app_recording_failures(name: &str) -> (App, tempfile::TempDir, SeenPaths) {
+ let seen: SeenPaths = Arc::new(Mutex::new(Vec::new()));
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .exception_handler({
+ let seen = seen.clone();
+ move |_err, exc| {
+ seen.lock()
+ .unwrap()
+ .push((exc.stable_path.clone(), exc.parent_stable_path.clone()));
+ Ok(())
+ }
+ })
+ .build()
+ .await
+ .unwrap()
+ .app(name)
+ .await
+ .unwrap();
+ (app, dir, seen)
+}
+
+fn sorted(seen: &SeenPaths) -> Vec<(String, Option<String>)> {
+ let mut v = seen.lock().unwrap().clone();
+ v.sort();
+ v
+}
+
+// ---------------------------------------------------------------------------
+// Background semantics
+// ---------------------------------------------------------------------------
+
+/// The parent returns from `mount_each` while the children are still
+/// running: the gate the children wait on is only opened afterwards, so a
+/// foreground `mount_each` would never return. `ready()` then waits for all.
+#[tokio::test]
+async fn mount_each_mounts_children_in_the_background() {
+ let (app, _dir) = temp_app("mount_each_background").await;
+ let gate = Arc::new(Semaphore::new(0));
+ let finished = Arc::new(AtomicUsize::new(0));
+
+ let (gate_outer, finished_outer) = (gate.clone(), finished.clone());
+ app.update(move |ctx| async move {
+ let handle = ctx
+ .mount_each(vec!["a", "b", "c"], |k| k.to_string(), {
+ let gate = gate_outer.clone();
+ let finished = finished_outer.clone();
+ move |_child, _k| {
+ let gate = gate.clone();
+ let finished = finished.clone();
+ async move {
+ let _permit = gate.acquire().await.unwrap();
+ finished.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+ }
+ })
+ .await?;
+ assert_eq!(finished_outer.load(Ordering::SeqCst), 0);
+ gate_outer.add_permits(3);
+ handle.ready().await?;
+ assert_eq!(finished_outer.load(Ordering::SeqCst), 3);
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+/// A lazy iterator that counts how many items were pulled.
+struct Counted {
+ next: usize,
+ len: usize,
+ pulled: Arc<AtomicUsize>,
+}
+
+impl Iterator for Counted {
+ type Item = usize;
+
+ fn next(&mut self) -> Option<usize> {
+ if self.next == self.len {
+ return None;
+ }
+ self.next += 1;
+ self.pulled.fetch_add(1, Ordering::SeqCst);
+ Some(self.next - 1)
+ }
+}
+
+/// `mount_each` consumes its items as children are admitted: with
+/// `max_inflight_components = 2` and children that block, the iterator is
+/// pulled at most three times (two running children, one waiting for a slot)
+/// however many items it holds.
+#[tokio::test]
+async fn mount_each_streams_items_as_children_are_admitted() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .max_inflight_components(2)
+ .build()
+ .await
+ .unwrap()
+ .app("mount_each_streams")
+ .await
+ .unwrap();
+ let pulled = Arc::new(AtomicUsize::new(0));
+ let started = Arc::new(AtomicUsize::new(0));
+ let gate = Arc::new(Semaphore::new(0));
+ let pulled_when_blocked = Arc::new(AtomicUsize::new(usize::MAX));
+
+ // Opens the gate once the admitted children stop increasing, recording
+ // how far the parent had read into its items by then.
+ let observer = tokio::spawn({
+ let (pulled, started, gate, pulled_when_blocked) = (
+ pulled.clone(),
+ started.clone(),
+ gate.clone(),
+ pulled_when_blocked.clone(),
+ );
+ async move {
+ let mut last = usize::MAX;
+ let mut stable_since = Instant::now();
+ loop {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ let now = started.load(Ordering::SeqCst);
+ if now != last {
+ last = now;
+ stable_since = Instant::now();
+ } else if now >= 2 && stable_since.elapsed() > Duration::from_millis(300) {
+ break;
+ }
+ }
+ pulled_when_blocked.store(pulled.load(Ordering::SeqCst), Ordering::SeqCst);
+ gate.add_permits(20);
+ }
+ });
+
+ let (pulled_outer, started_outer, gate_outer) = (pulled.clone(), started.clone(), gate.clone());
+ app.update(move |ctx| async move {
+ let items = Counted {
+ next: 0,
+ len: 20,
+ pulled: pulled_outer,
+ };
+ let handle = ctx
+ .mount_each(items, |i| *i as i64, {
+ let (started, gate) = (started_outer, gate_outer);
+ move |_child, _i| {
+ let (started, gate) = (started.clone(), gate.clone());
+ async move {
+ started.fetch_add(1, Ordering::SeqCst);
+ let _permit = gate.acquire().await.unwrap();
+ Ok(())
+ }
+ }
+ })
+ .await?;
+ handle.ready().await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ observer.await.unwrap();
+
+ let when_blocked = pulled_when_blocked.load(Ordering::SeqCst);
+ assert!(
+ (2..=3).contains(&when_blocked),
+ "the parent must read only as far as admission allows, read {when_blocked} of 20"
+ );
+ assert_eq!(pulled.load(Ordering::SeqCst), 20);
+ assert_eq!(started.load(Ordering::SeqCst), 20);
+}
+
+#[tokio::test]
+async fn mount_each_rejects_duplicate_keys() {
+ let (app, _dir) = temp_app("mount_each_dup").await;
+ let err = app
+ .update(|ctx| async move {
+ ctx.mount_each(
+ vec![("alpha", 1), ("beta", 2), ("alpha", 3)],
+ |&(name, _)| name.to_string(),
+ |_child, _item| async move { Ok(()) },
+ )
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap_err();
+ assert!(
+ err.to_string().contains("duplicate key"),
+ "unexpected error: {err}"
+ );
+}
+
+/// An async source of items: a child is mounted per pair as it arrives.
+#[tokio::test]
+async fn mount_each_stream_mounts_each_pair() {
+ let (app, _dir) = temp_app("mount_each_stream").await;
+ let seen = Arc::new(Mutex::new(Vec::new()));
+ let seen_outer = seen.clone();
+ app.update(move |ctx| async move {
+ let items = futures::stream::iter(vec![("x", 1u32), ("y", 2)]);
+ ctx.mount_each_stream(items, {
+ let seen = seen_outer.clone();
+ move |_child, value| {
+ let seen = seen.clone();
+ async move {
+ seen.lock().unwrap().push(value);
+ Ok(())
+ }
+ }
+ })
+ .await?
+ .ready()
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ let mut values = seen.lock().unwrap().clone();
+ values.sort();
+ assert_eq!(values, vec![1, 2]);
+}
+
+// ---------------------------------------------------------------------------
+// Paths: `mount_each!` prefix and typed keys
+// ---------------------------------------------------------------------------
+
+#[cocoindex::function]
+async fn fail_item(_ctx: &Ctx, _n: u32) -> Result<()> {
+ Err(Error::engine("boom"))
+}
+
+/// `mount_each!(prefix, items, ...)` mounts each item at `prefix/key`: two
+/// path parts, the prefix being the parent, as Python's `mount_each` subpath.
+/// The prefix defaults to the function's name.
+#[tokio::test]
+async fn mount_each_macro_mounts_under_the_prefix() {
+ let (app, _dir, seen) = temp_app_recording_failures("mount_each_prefix").await;
+ app.update(|ctx| async move {
+ let ctx = &ctx;
+ let items = vec![("k".to_string(), 1u32)];
+ cocoindex::mount_each!("items", items, |n| fail_item(ctx, n))
+ .await?
+ .ready()
+ .await?;
+ let items = vec![(7i64, 2u32)];
+ cocoindex::mount_each!(items, |n| fail_item(ctx, n))
+ .await?
+ .ready()
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+ assert_eq!(
+ sorted(&seen),
+ vec![
+ (
+ "/\"fail_item\"/7".to_string(),
+ Some("/\"fail_item\"".to_string())
+ ),
+ (
+ "/\"items\"/\"k\"".to_string(),
+ Some("/\"items\"".to_string())
+ ),
+ ]
+ );
+}
+
+/// Mount keys are any `IntoStableKey`: an integer stores as `StableKey::Int`,
+/// a UUID as `StableKey::Uuid`, bytes as `StableKey::Bytes`, a `StableKey`
+/// as itself; a string still stores as `StableKey::Str`.
+#[tokio::test]
+async fn typed_mount_keys_store_as_typed_stable_keys() {
+ let (app, _dir) = temp_app("typed_keys").await;
+ let id = uuid::Uuid::from_u128(0x1234);
+ app.update(move |ctx| async move {
+ ctx.mount(7i64, |_child| async move { Ok(()) }).await?;
+ ctx.mount(id, |_child| async move { Ok(()) }).await?;
+ ctx.mount(&"name", |_child| async move { Ok(()) }).await?;
+ ctx.with_subpath(StableKey::Symbol("sym".into()))
+ .mount(b"xy".as_slice(), |_child| async move { Ok(()) })
+ .await?;
+ ctx.scope(3u32, |_child| async move { Ok(1u8) }).await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+
+ let paths = inspect::list_stable_paths(&app).await.unwrap();
+ let parts: Vec<Vec<StableKey>> = paths.iter().map(|p| p.to_vec()).collect();
+ for expected in [
+ vec![StableKey::Int(7)],
+ vec![StableKey::Uuid(id)],
+ vec![StableKey::Str("name".into())],
+ vec![
+ StableKey::Symbol("sym".into()),
+ StableKey::Bytes(Arc::from(&b"xy"[..])),
+ ],
+ vec![StableKey::Int(3)],
+ ] {
+ assert!(
+ parts.contains(&expected),
+ "missing {expected:?} in {parts:?}"
+ );
+ }
+}
diff --git a/rust/sdk/cocoindex/tests/pipeline.rs b/rust/sdk/cocoindex/tests/pipeline.rs
index d2e22570..d90dde40 100644
--- a/rust/sdk/cocoindex/tests/pipeline.rs
+++ b/rust/sdk/cocoindex/tests/pipeline.rs
@@ -754,7 +754,7 @@ async fn type_owned_context_memo_state_invalidates_cached_function() {
Vec::new(),
)?;
ctx.__use_mount_fp(
- "stateful_child".to_string(),
+ cocoindex::IntoStableKey::into_stable_key("stateful_child"),
Some(memo),
move |child_ctx| async move {
component_calls.fetch_add(1, Ordering::SeqCst);
@@ -2046,7 +2046,7 @@ mod memo_test_borrowed_slice {
#[cocoindex::function(memo)]
async fn memo_total(ctx: &cocoindex::Ctx, values: &[i64]) -> cocoindex::Result<i64> {
CALLS.fetch_add(1, Ordering::SeqCst);
- total(ctx, &values).await
+ total(ctx, values).await
}
#[tokio::test]
@@ -2556,7 +2556,7 @@ async fn ctx_mount_each() {
app.update(|ctx| async move {
let items = vec![("alpha", 1), ("beta", 2), ("gamma", 3)];
let results: Vec<Output> = ctx
- .mount_each(
+ .use_mount_each(
items,
|&(name, _)| name.to_string(),
|_child_ctx, (name, value)| async move {
@@ -2594,7 +2594,7 @@ async fn ctx_mount_each_independent_memo() {
app.update(|ctx| async move {
let items = vec!["child_a", "child_b"];
let results: Vec<i32> = ctx
- .mount_each(items, |name| name.to_string(), {
+ .use_mount_each(items, |name| name.to_string(), {
let count = count.clone();
move |child_ctx, name| {
let count = count.clone();
@@ -2625,7 +2625,7 @@ async fn ctx_mount_each_independent_memo() {
app.update(|ctx| async move {
let items = vec!["child_a", "child_b"];
let results: Vec<i32> = ctx
- .mount_each(items, |name| name.to_string(), {
+ .use_mount_each(items, |name| name.to_string(), {
let count = count.clone();
move |child_ctx, name| {
let count = count.clone();
@@ -2658,7 +2658,7 @@ async fn ctx_mount_each_preserves_input_order_under_concurrency() {
app.update(|ctx| async move {
let items = vec![("slow", 30_u64), ("fast", 0_u64), ("mid", 10_u64)];
let results: Vec<String> = ctx
- .mount_each(
+ .use_mount_each(
items.clone(),
|&(name, _)| name.to_string(),
|_child_ctx, (name, delay)| async move {
@@ -2882,7 +2882,7 @@ async fn ctx_stats_group_reports_scoped_child_stats() {
let (sum, handle) = ctx
.stats_group("Indexing docs", |group_ctx, _handle| async move {
let values = group_ctx
- .mount_each(
+ .use_mount_each(
vec![1, 2],
|item| *item,
|child, item| async move {
@@ -2935,7 +2935,7 @@ async fn ctx_stats_group_with_options_reports_scoped_child_stats() {
options,
|group_ctx, _h| async move {
let values = group_ctx
- .mount_each(
+ .use_mount_each(
vec![1, 2, 3],
|item| *item,
|child, item| async move {
@@ -3305,7 +3305,7 @@ async fn ctx_mount_each_rejects_duplicate_keys() {
// "alpha" is duplicated
let items = vec![("alpha", 1), ("beta", 2), ("alpha", 3)];
let _: Vec<i32> = ctx
- .mount_each(
+ .use_mount_each(
items,
|&(name, _)| name.to_string(), // duplicate 'alpha' keys
|_child_ctx, (_, value)| async move { Ok(value) },
@@ -3481,7 +3481,7 @@ mod mount_macros {
async fn run_each(app: &cocoindex::App, items: Vec<(String, u32)>) -> Vec<u32> {
app.update(move |ctx| async move {
- let out = cocoindex::mount_each!(items, |n| each_double(ctx, n)).await?;
+ let out = cocoindex::use_mount_each!(items, |n| each_double(ctx, n)).await?;
Ok(out)
})
.await
@@ -3518,7 +3518,7 @@ mod mount_macros {
async fn run(app: &cocoindex::App, items: Vec<(String, u32)>) {
app.update(move |ctx| async move {
- cocoindex::mount_each!(items, |n| sel_double(ctx, n)).await?;
+ cocoindex::use_mount_each!(items, |n| sel_double(ctx, n)).await?;
Ok(())
})
.await
@@ -3578,7 +3578,7 @@ mod mount_macros {
// `#[rustfmt::skip]` keeps the block braces so this test keeps
// exercising the block-form closure body the macro must accept.
#[rustfmt::skip]
- let out = cocoindex::mount_each!(items, |n| { block_id(ctx, n) }).await?;
+ let out = cocoindex::use_mount_each!(items, |n| { block_id(ctx, n) }).await?;
Ok(out)
})
.await
diff --git a/rust/sdk/cocoindex/tests/postgres_source.rs b/rust/sdk/cocoindex/tests/postgres_source.rs
index 1cca7069..e6de0089 100644
--- a/rust/sdk/cocoindex/tests/postgres_source.rs
+++ b/rust/sdk/cocoindex/tests/postgres_source.rs
@@ -255,7 +255,7 @@ async fn postgres_source_reads_processes_and_reconciles_when_available() -> Resu
.try_collect()
.await?;
let outs = ctx
- .mount_each(
+ .use_mount_each(
rows,
|r| format!("{}|{}", r.category, r.name),
|child, r| async move { process(&child, &r).await },
diff --git a/rust/sdk/cocoindex_macros/src/lib.rs b/rust/sdk/cocoindex_macros/src/lib.rs
index 78ac8d96..df35aaa4 100644
--- a/rust/sdk/cocoindex_macros/src/lib.rs
+++ b/rust/sdk/cocoindex_macros/src/lib.rs
@@ -1,5 +1,5 @@
//! Proc macros for cocoindex: `#[function]`, `#[app]`, `#[lifespan]`, `#[main]`,
-//! `use_mount!`, `mount!`, `mount_each!`.
+//! `use_mount!`, `mount!`, `mount_each!`, `use_mount_each!`.
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
@@ -39,7 +39,11 @@ fn derive_memo_input_impl(input: DeriveInput) -> syn::Result<TokenStream2> {
.push(syn::parse_quote!(#ty: ::cocoindex::memo::MemoInput));
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
- let (write_body, state_body) = memo_input_derive_bodies(&name, &input.data)?;
+ let MemoInputBodies {
+ write_body,
+ has_state_body,
+ state_body,
+ } = memo_input_derive_bodies(&name, &input.data)?;
Ok(quote! {
#[::cocoindex::async_trait]
@@ -51,6 +55,10 @@ fn derive_memo_input_impl(input: DeriveInput) -> syn::Result<TokenStream2> {
#write_body
}
+ fn has_memo_state(&self) -> bool {
+ #has_state_body
+ }
+
async fn memo_state(
&self,
previous: ::core::option::Option<&::cocoindex::memo::MemoStateValue>,
@@ -63,6 +71,13 @@ fn derive_memo_input_impl(input: DeriveInput) -> syn::Result<TokenStream2> {
})
}
+/// The three method bodies of a derived `MemoInput` impl.
+struct MemoInputBodies {
+ write_body: TokenStream2,
+ has_state_body: TokenStream2,
+ state_body: TokenStream2,
+}
+
fn memo_input_field_types(data: &syn::Data) -> Vec<&Type> {
match data {
syn::Data::Struct(data) => data.fields.iter().map(|field| &field.ty).collect(),
@@ -75,10 +90,7 @@ fn memo_input_field_types(data: &syn::Data) -> Vec<&Type> {
}
}
-fn memo_input_derive_bodies(
- name: &Ident,
- data: &syn::Data,
-) -> syn::Result<(TokenStream2, TokenStream2)> {
+fn memo_input_derive_bodies(name: &Ident, data: &syn::Data) -> syn::Result<MemoInputBodies> {
match data {
syn::Data::Struct(data) => Ok(memo_input_struct_bodies(name, &data.fields)),
syn::Data::Enum(data) => Ok(memo_input_enum_bodies(name, data)),
@@ -89,7 +101,7 @@ fn memo_input_derive_bodies(
}
}
-fn memo_input_struct_bodies(name: &Ident, fields: &syn::Fields) -> (TokenStream2, TokenStream2) {
+fn memo_input_struct_bodies(name: &Ident, fields: &syn::Fields) -> MemoInputBodies {
let len = fields.len();
let (key_writes, children): (Vec<_>, Vec<_>) = match fields {
syn::Fields::Named(fields) => fields
@@ -126,15 +138,24 @@ fn memo_input_struct_bodies(name: &Ident, fields: &syn::Fields) -> (TokenStream2
#(#key_writes)*
Ok(())
};
+ let has_state_body = quote! {
+ let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] = &[#(#children),*];
+ ::cocoindex::memo::any_has_memo_state(__coco_children)
+ };
let state_body = quote! {
let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] = &[#(#children),*];
::cocoindex::memo::memo_state_group(__coco_children, previous, false).await
};
- (write_body, state_body)
+ MemoInputBodies {
+ write_body,
+ has_state_body,
+ state_body,
+ }
}
-fn memo_input_enum_bodies(name: &Ident, data: &syn::DataEnum) -> (TokenStream2, TokenStream2) {
+fn memo_input_enum_bodies(name: &Ident, data: &syn::DataEnum) -> MemoInputBodies {
let mut write_arms = Vec::with_capacity(data.variants.len());
+ let mut has_state_arms = Vec::with_capacity(data.variants.len());
let mut state_arms = Vec::with_capacity(data.variants.len());
for variant in &data.variants {
@@ -178,9 +199,18 @@ fn memo_input_enum_bodies(name: &Ident, data: &syn::DataEnum) -> (TokenStream2,
Ok(())
}
});
+ let children = children.collect::<Vec<_>>();
let patterns = fields_and_bindings
.iter()
- .map(|(field, binding)| quote! { #field: #binding });
+ .map(|(field, binding)| quote! { #field: #binding })
+ .collect::<Vec<_>>();
+ has_state_arms.push(quote! {
+ Self::#variant_ident { #(#patterns),* } => {
+ let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] =
+ &[#(#children),*];
+ ::cocoindex::memo::any_has_memo_state(__coco_children)
+ }
+ });
state_arms.push(quote! {
Self::#variant_ident { #(#patterns),* } => {
let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] =
@@ -216,6 +246,14 @@ fn memo_input_enum_bodies(name: &Ident, data: &syn::DataEnum) -> (TokenStream2,
Ok(())
}
});
+ let children = children.collect::<Vec<_>>();
+ has_state_arms.push(quote! {
+ Self::#variant_ident(#(#bindings),*) => {
+ let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] =
+ &[#(#children),*];
+ ::cocoindex::memo::any_has_memo_state(__coco_children)
+ }
+ });
state_arms.push(quote! {
Self::#variant_ident(#(#bindings),*) => {
let __coco_children: &[&dyn ::cocoindex::memo::MemoInput] =
@@ -241,15 +279,17 @@ fn memo_input_enum_bodies(name: &Ident, data: &syn::DataEnum) -> (TokenStream2,
Ok(())
}
});
+ has_state_arms.push(quote! { Self::#variant_ident => false });
state_arms.push(quote! { Self::#variant_ident => Ok(None) });
}
}
}
- (
- quote! { match self { #(#write_arms),* } },
- quote! { match self { #(#state_arms),* } },
- )
+ MemoInputBodies {
+ write_body: quote! { match self { #(#write_arms),* } },
+ has_state_body: quote! { match self { #(#has_state_arms),* } },
+ state_body: quote! { match self { #(#state_arms),* } },
+ }
}
/// Information about a non-ctx parameter.
@@ -631,8 +671,11 @@ fn gen_key_write_for_param(
None if param.is_str_ref => Some(quote! {
::cocoindex::memo::write_key_fingerprint_part(&mut #fingerprinter, #default_arg)?;
}),
+ // `MemoInput` identity when the type has one, else its serialized
+ // value (a target handle), picked by autoref specialization.
None => Some(quote! {
- ::cocoindex::memo::write_key_fingerprint_part_for_arg(&mut #fingerprinter, #default_arg)?;
+ (&&::cocoindex::memo::MemoArg(#default_arg))
+ .__coco_write_memo_key(&mut #fingerprinter)?;
}),
}
}
@@ -647,15 +690,20 @@ fn gen_state_collect_for_param(
return quote! {};
}
let ident = &param.ident;
- let default_arg = quote! { &#ident };
+ // Only a `MemoInput` argument can carry state; a `Serialize`-only one
+ // takes no state slot, like a `MemoInput` whose state is `None`.
quote! {
- let __coco_prev_state = #prev_states_ident
- .as_ref()
- .and_then(|__coco_previous_states| __coco_previous_states.get(#states_ident.len()));
- if let Some(__coco_state) =
- ::cocoindex::memo::collect_memo_arg_state(#default_arg, __coco_prev_state).await?
+ if let ::core::option::Option::Some(__coco_input) =
+ (&&::cocoindex::memo::MemoArg(&#ident)).__coco_memo_state_input()
{
- #states_ident.push(__coco_state);
+ let __coco_prev_state = #prev_states_ident
+ .as_ref()
+ .and_then(|__coco_previous_states| __coco_previous_states.get(#states_ident.len()));
+ if let ::core::option::Option::Some(__coco_state) =
+ ::cocoindex::memo::collect_memo_arg_state(__coco_input, __coco_prev_state).await?
+ {
+ #states_ident.push(__coco_state);
+ }
}
}
}
@@ -685,9 +733,20 @@ struct FnLogicTokens {
hash_const_value: TokenStream2,
/// The link-time logic registration (and the `deps` static), if tracked.
logic_registration: TokenStream2,
- /// An expression for the `deps` fingerprint: `Option<Fingerprint>`, may
- /// use `?`.
- deps_fp: TokenStream2,
+ /// `__COCO_FN_LOGIC_<NAME>`: the registered `FnLogicEntry` static, whose
+ /// cached fingerprint every call records. `None` for
+ /// `logic_tracking = "none"`.
+ logic_entry: Option<Ident>,
+}
+
+impl FnLogicTokens {
+ /// `Option<Fingerprint>` of the function's logic, for a memo frame.
+ fn logic_fp_tokens(&self) -> TokenStream2 {
+ match &self.logic_entry {
+ Some(entry) => quote! { ::core::option::Option::Some(#entry.fingerprint()?) },
+ None => quote! { ::core::option::Option::None },
+ }
+ }
}
fn gen_memo_wrapper_block(
@@ -700,7 +759,6 @@ fn gen_memo_wrapper_block(
body_closure: TokenStream2,
) -> syn::Result<TokenStream2> {
let hash_const_name = &logic.hash_const_name;
- let deps_fp = &logic.deps_fp;
let propagate_children_fn_logic = logic_tracking == LogicTracking::Full;
validate_memo_key_overrides(
overrides,
@@ -719,52 +777,41 @@ fn gen_memo_wrapper_block(
gen_state_collect_for_param(&states_ident, &prev_states_ident, param, overrides)
})
.collect::<Vec<_>>();
- let state_params = params
- .iter()
- .filter(|param| !param.is_str_ref && memo_key_override(overrides, &param.ident).is_none())
- .cloned()
- .collect::<Vec<_>>();
- let state_clone_stmts = gen_clones(&state_params);
- let body_clone_stmts = gen_clones(params);
let memo_key = gen_function_memo_key(fn_name, hash_const_name, &key_writes);
// `logic_tracking = "none"` is never registered in the logic set, so its
// fingerprint must not reach a caller's memo entry.
- let logic_fp = if logic_tracking != LogicTracking::None {
- quote! {
- ::core::option::Option::Some(::cocoindex::memo::fn_logic_fingerprint(
- ::core::module_path!(),
- ::core::stringify!(#fn_name),
- #hash_const_name,
- #deps_fp,
- )?)
- }
- } else {
- quote! { ::core::option::Option::None }
- };
+ let logic_fp = logic.logic_fp_tokens();
+ // The key and the argument states only borrow the parameters, so a hit
+ // clones nothing; on a miss the parameters move into the body closure,
+ // which is created only then.
Ok(quote! {{
- let __coco_key = #memo_key;
- let __coco_logic_fp = #logic_fp;
-
- ::cocoindex::memo::cached_by_fingerprint_with_state(
+ #[allow(unused_imports)]
+ use ::cocoindex::memo::{
+ MemoArgKeyViaMemoInput as _, MemoArgKeyViaSerialize as _,
+ MemoArgStateViaMemoInput as _, MemoArgStateViaSerialize as _,
+ };
+ let #key_ident = #memo_key;
+ let __coco_probe = ::cocoindex::memo::MemoProbe::begin(
#ctx_ident,
- __coco_key,
- __coco_logic_fp,
+ #key_ident,
+ #logic_fp,
#propagate_children_fn_logic,
- {
- #(#state_clone_stmts)*
- move |__coco_prev_states| async move {
- let mut __coco_states = Vec::new();
- #(#state_collects)*
- Ok(__coco_states)
- }
- },
- {
- #(#body_clone_stmts)*
- #body_closure
- },
)
- .await
+ .await?;
+ let mut #states_ident = ::std::vec::Vec::new();
+ if __coco_probe.validates_states() {
+ let #prev_states_ident = __coco_probe.cached_states();
+ #(#state_collects)*
+ }
+ match __coco_probe.lookup(#states_ident).await? {
+ ::cocoindex::memo::MemoLookup::Hit(__coco_value) => {
+ ::core::result::Result::Ok(__coco_value)
+ }
+ ::cocoindex::memo::MemoLookup::Miss(__coco_miss) => {
+ __coco_miss.run(#body_closure).await
+ }
+ }
}})
}
@@ -978,14 +1025,13 @@ fn expand_batching_function(
func: &ItemFn,
args: &FunctionArgs,
logic: &FnLogicTokens,
- track_logic: bool,
propagate_children_fn_logic: bool,
) -> syn::Result<TokenStream2> {
let FnLogicTokens {
hash_const_name,
hash_const_value,
logic_registration,
- deps_fp,
+ logic_entry: _,
} = logic;
let batching = parse_batching_signature(func)?;
let fn_name = &func.sig.ident;
@@ -1058,6 +1104,10 @@ fn expand_batching_function(
.await
};
+ // The batch closure handed to the scheduler is `'static`, so the extra
+ // parameters are cloned into it; a memoized call clones them only on a
+ // miss, inside the body.
+ let initial_extra_clones = gen_clones(extra_params);
let wrapper_body = if args.memo {
let mut key_params = vec![batching.item_param.clone()];
key_params.extend(extra_params.iter().cloned());
@@ -1070,21 +1120,18 @@ fn expand_batching_function(
args.logic_tracking,
quote! {
move |__coco_scoped_ctx| async move {
+ #(#initial_extra_clones)*
#schedule_call
}
},
)?
} else {
- let initial_extra_clones = gen_clones(extra_params);
- if track_logic {
+ if let Some(logic_entry) = &logic.logic_entry {
quote! {{
#(#initial_extra_clones)*
#ctx_ident
.__coco_tracked_fn(
- ::core::module_path!(),
- ::core::stringify!(#fn_name),
- #hash_const_name,
- #deps_fp,
+ &#logic_entry,
#propagate_children_fn_logic,
move |__coco_scoped_ctx| async move {
#schedule_call
@@ -1143,6 +1190,12 @@ fn expand_batching_function(
/// whole function because it includes the function's logic hash and arguments
/// in the key automatically.
///
+/// Each argument is keyed by its `cocoindex::MemoInput` identity, with that
+/// type's state validation (a file's mtime and content). An argument whose type
+/// is not `MemoInput` but is `Serialize`, such as a target handle, is keyed by
+/// its serialized value and has no state validation, as Python memoizes a
+/// target on its key.
+///
/// Customize individual argument keys with `memo_key(...)`. A transform
/// function replaces the argument's default `cocoindex::MemoInput` identity
/// and suppresses its type-owned external-state validation. `skip` (or `None`)
@@ -1169,9 +1222,9 @@ fn expand_batching_function(
/// let embedding: Vec<f32> = embed(ctx, text).await?;
/// ```
/// Additional parameters must implement `Serialize` because their serialized
-/// values group compatible calls into a physical batch. With `memo`, they must
-/// also implement `MemoInput` because they form part of each item's memo key,
-/// unless `memo_key(...)` transforms or skips their memo identity.
+/// values group compatible calls into a physical batch. With `memo`, they are
+/// also part of each item's memo key, by their `MemoInput` identity when they
+/// have one, unless `memo_key(...)` transforms or skips it.
///
/// A batching body may return `Error::retry_with_smaller_batch(cause)`: the
/// batch is halved and each half re-run, down to single items, where `cause`
@@ -1235,8 +1288,8 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
// set, so a memoized caller's stored `logic_deps` (which include the
// fingerprints of transitively-called `#[coco::function]`s) validate via
// `all_contained` instead of being perpetually treated as stale. The
- // (module, name, code_hash) tuple must match `Ctx::__coco_tracked_fn`'s
- // fingerprint computation. `linkme` is reached through the re-export so the
+ // (module, name, code_hash) tuple is what `FnLogicEntry::fingerprint`
+ // hashes, once per process. `linkme` is reached through the re-export so the
// user crate needs no direct dependency. Omitted entirely for
// `logic_tracking = "none"`.
// `deps = <expr>`: the value's fingerprint is computed once per process
@@ -1245,7 +1298,7 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
// exactly as a body edit does. The static initializer cannot see the
// function's parameters, so a per-call value cannot slip in here.
let deps_static_name = format_ident!("__COCO_FN_DEPS_{}", fn_name.to_string().to_uppercase());
- let (deps_static, deps_entry, deps_fp) = match &args.deps {
+ let (deps_static, deps_entry) = match &args.deps {
Some(deps) => (
quote! {
#[doc(hidden)]
@@ -1254,14 +1307,11 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
);
},
quote! { ::core::option::Option::Some(&#deps_static_name) },
- quote! { ::core::option::Option::Some(#deps_static_name.get()?) },
- ),
- None => (
- quote! {},
- quote! { ::core::option::Option::None },
- quote! { ::core::option::Option::None },
),
+ None => (quote! {}, quote! { ::core::option::Option::None }),
};
+ // The entry's fingerprint is cached in the static (`FnLogicEntry::fingerprint`),
+ // so a call reads it instead of hashing its identity again.
let logic_slice_name = format_ident!("__COCO_FN_LOGIC_{}", fn_name.to_string().to_uppercase());
let logic_registration = if track_logic {
quote! {
@@ -1269,16 +1319,17 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
#[::cocoindex::linkme::distributed_slice(::cocoindex::COCO_FN_LOGIC)]
#[linkme(crate = ::cocoindex::linkme)]
#[doc(hidden)]
- static #logic_slice_name: ::cocoindex::FnLogicEntry = ::cocoindex::FnLogicEntry {
- module: ::core::module_path!(),
- name: ::core::stringify!(#fn_name),
- code_hash: #code_hash,
- deps: #deps_entry,
- };
+ static #logic_slice_name: ::cocoindex::FnLogicEntry = ::cocoindex::FnLogicEntry::new(
+ ::core::module_path!(),
+ ::core::stringify!(#fn_name),
+ #code_hash,
+ #deps_entry,
+ );
}
} else {
quote! {}
};
+ let logic_entry = track_logic.then(|| logic_slice_name.clone());
if !args.memo && !args.memo_key.is_empty() {
return TokenStream::from(
@@ -1302,16 +1353,10 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
hash_const_name,
hash_const_value,
logic_registration,
- deps_fp,
+ logic_entry,
};
if args.batching {
- return match expand_batching_function(
- &func,
- &args,
- &logic,
- track_logic,
- propagate_children_fn_logic,
- ) {
+ return match expand_batching_function(&func, &args, &logic, propagate_children_fn_logic) {
Ok(expanded) => expanded.into(),
Err(err) => err.to_compile_error().into(),
};
@@ -1321,7 +1366,7 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
hash_const_name,
hash_const_value,
logic_registration,
- deps_fp,
+ logic_entry,
} = &logic;
if args.memo {
// memo: wrap body in ctx.memo()
@@ -1387,7 +1432,7 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
let body = &func.block;
let expanded = if let Some(ctx_ident) = ctx_opt {
- if track_logic {
+ if let Some(logic_entry) = logic_entry {
let run_body = gen_runner_wrap(
fn_name,
&args,
@@ -1405,10 +1450,7 @@ pub fn function(attr: TokenStream, item: TokenStream) -> TokenStream {
#(#attrs)*
#vis #sig {
#ctx_ident.__coco_tracked_fn(
- ::core::module_path!(),
- ::core::stringify!(#fn_name),
- #hash_const_name,
- #deps_fp,
+ &#logic_entry,
#propagate_children_fn_logic,
move |__coco_scoped_ctx| async move { #run_body },
).await
@@ -1510,7 +1552,7 @@ fn parse_grouped_call(expr: &Expr) -> syn::Result<(Path, Vec<Expr>)> {
/// Foreground mount: creates a child component, runs `my_fn` under it with the
/// child `&Ctx` substituted for the first argument, and returns its value.
/// `(a, b)` are fingerprinted for the component-memo fast-path. The subpath is
-/// `key` if given, else the function's name.
+/// `key` (any `cocoindex::IntoStableKey`) if given, else the function's name.
#[proc_macro]
pub fn use_mount(input: TokenStream) -> TokenStream {
expand_single_mount(input, "use_mount", quote! { __use_mount_fp })
@@ -1568,8 +1610,10 @@ fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) ->
.iter()
.map(|id| component_arg_part(quote! { & #id }));
let key_tokens = match key_expr {
- Some(key) => quote! { ::std::string::ToString::to_string(&(#key)) },
- None => quote! { ::std::string::ToString::to_string(::core::stringify!(#fn_ident)) },
+ Some(key) => quote! { ::cocoindex::IntoStableKey::into_stable_key(#key) },
+ None => quote! {
+ ::cocoindex::IntoStableKey::into_stable_key(::core::stringify!(#fn_ident))
+ },
};
quote! {{
@@ -1582,7 +1626,7 @@ fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) ->
#hash_path,
::std::vec![ #(#fp_parts),* ],
)?;
- let __coco_key: ::std::string::String = #key_tokens;
+ let __coco_key: ::cocoindex::StableKey = #key_tokens;
__coco_parent.#method(
__coco_key,
::core::option::Option::Some(__coco_memo),
@@ -1597,13 +1641,37 @@ fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) ->
/// `mount_each!(items, |item| my_fn(ctx, item, a, b))` or
/// `mount_each!(prefix, items, |item| my_fn(ctx, item, a, b))`.
///
-/// One child component per `(key, value)` item (subpath `prefix/key`, prefix
-/// defaulting to the function name). The closure binds the item's **value**;
-/// inside the call, `ctx` β†’ child scope, the bound `item` β†’ that value, and any
-/// other arguments are captured extras that are fingerprinted (with the value)
-/// for each item's component-memo key.
+/// One background child component per `(key, value)` item, at `prefix/key`
+/// (`prefix` defaulting to the function name), the Rust analogue of Python's
+/// `coco.mount_each`: evaluates to a `Result<ComponentMountHandle>` whose
+/// `ready().await` waits until every child's target states are synced; the
+/// children are mounted as `items` is consumed, and `my_fn` returns
+/// `Result<()>`. `use_mount_each!` is the form that returns the values.
+///
+/// The closure binds the item's **value**; inside the call, `ctx` β†’ child
+/// scope, the bound `item` β†’ that value, and any other arguments are captured
+/// extras that are fingerprinted (with the value) for each item's
+/// component-memo key.
#[proc_macro]
pub fn mount_each(input: TokenStream) -> TokenStream {
+ expand_mount_each(input, "mount_each", quote! { __mount_each_fp })
+}
+
+/// `use_mount_each!(items, |item| my_fn(ctx, item, a, b))` or
+/// `use_mount_each!(prefix, items, |item| my_fn(ctx, item, a, b))`.
+///
+/// Like `mount_each!`, but the children run in the foreground and the macro
+/// evaluates to a `Result<Vec<T>>` of `my_fn`'s values in `items` order: the
+/// per-item form of `use_mount!`.
+#[proc_macro]
+pub fn use_mount_each(input: TokenStream) -> TokenStream {
+ expand_mount_each(input, "use_mount_each", quote! { __use_mount_each_fp })
+}
+
+/// Shared expansion of `mount_each!` and `use_mount_each!`: the same
+/// grouped-call parse and per-item component memo, dispatched to
+/// `Ctx::<method>`.
+fn expand_mount_each(input: TokenStream, name: &str, method: TokenStream2) -> TokenStream {
let parsed = parse_macro_input!(input with Punctuated::<Expr, Token![,]>::parse_terminated);
let elems: Vec<Expr> = parsed.into_iter().collect();
let (prefix_expr, items_expr, closure) = match elems.as_slice() {
@@ -1612,8 +1680,10 @@ pub fn mount_each(input: TokenStream) -> TokenStream {
_ => {
return SynError::new(
Span::call_site(),
- "mount_each! takes `items, |item| my_fn(ctx, item, ...)` \
- or `prefix, items, |item| my_fn(ctx, item, ...)`",
+ format!(
+ "{name}! takes `items, |item| my_fn(ctx, item, ...)` \
+ or `prefix, items, |item| my_fn(ctx, item, ...)`"
+ ),
)
.to_compile_error()
.into();
@@ -1683,7 +1753,7 @@ pub fn mount_each(input: TokenStream) -> TokenStream {
quote! {{
use ::cocoindex::mount::{ComponentArgViaMemoInput as _, ComponentArgViaSerialize as _};
#(#extra_binds)*
- (#ctx_arg).__mount_each_fp(
+ (#ctx_arg).#method(
#items_expr,
#prefix_tokens,
{
@@ -2603,14 +2673,14 @@ mod tests {
hash_const_name: hash_const_name.clone(),
hash_const_value: quote!(#hash),
logic_registration: quote!(),
- deps_fp: quote!(::core::option::Option::None),
+ logic_entry: Some(format_ident!("__COCO_FN_LOGIC_EMBED")),
};
let first_expanded =
- expand_batching_function(&first, &args, &logic_tokens(first_hash), true, true)
+ expand_batching_function(&first, &args, &logic_tokens(first_hash), true)
.unwrap()
.to_string();
let second_expanded =
- expand_batching_function(&second, &args, &logic_tokens(second_hash), true, true)
+ expand_batching_function(&second, &args, &logic_tokens(second_hash), true)
.unwrap()
.to_string();
let key_part = "write_key_fingerprint_part (& mut __coco_key , & __COCO_FN_HASH_EMBED)";