Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
docs(programming-guide): Rust pages for app, target state and processing component (#2754)
LJ π₯₯π΄88809f011518
diff --git a/docs/src/content/docs/programming_guide/app.mdx b/docs/src/content/docs/programming_guide/app.mdxindex a51f6626..0abfbcbc 100644--- a/docs/src/content/docs/programming_guide/app.mdx+++ b/docs/src/content/docs/programming_guide/app.mdx@@ -12,16 +12,29 @@ Read [Core Concepts](./core_concepts) for the App and source β transform β t:::An **App** is the top-level runnable unit in CocoIndex.-It names your pipeline and binds a main function with its parameters. When you call `app.update()`, CocoIndex runs that main function as the root [processing component](./processing_component) which can mount child processing components to do work and declare target states.+<Lang only="python">It names your pipeline and binds a main function with its parameters. When you call `app.update()`, CocoIndex runs that main function as the root [processing component](./processing_component) which can mount child processing components to do work and declare target states.</Lang><Lang only="rust">It names your pipeline and owns its state. When you call `app.run(app_main)` or `app.update(app_main)`, CocoIndex runs the main function as the root [processing component](./processing_component) which can mount child processing components to do work and declare target states.</Lang>## Creating an app+<Lang only="python">+To create an App, provide:1. **An `AppConfig`** (or just a name string) β identifies the pipeline2. **A main function** β the entry point for your pipeline3. **Arguments** β any additional arguments to pass to the main function+</Lang>++<Lang only="rust">++To create an App, provide:++1. **A main function** marked `#[cocoindex::app]` β the entry point for your pipeline+2. **A name** β identifies the pipeline; the function name unless you pass `name = "..."`++</Lang>+{/* Rust: examples/rust/text_embedding/src/main.rs, rust/sdk/SHOWCASE.md "Run apps with the `cocoindex` CLI" */}<LangTabs><Fragment slot="python">@@ -57,12 +70,12 @@ async fn index(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {}```-In Rust, the main function takes the root component's `Ctx` by value and returns a `Result`. `#[cocoindex::app]` registers it under a name, so `Environment::from_registered` and the Rust CLI find it. The name is the function name unless you pass `name = "..."`. Arguments are not bound to the app: the registered function reads its inputs itself, and a closure passes them when your own code runs the app (see below).+The main function takes the root component's `Ctx` by value and returns a `Result`. `#[cocoindex::app]` registers it under its name, so `Environment::from_registered` and the [`cocoindex` CLI](#managing-apps-with-cli) find it.</Fragment></LangTabs>-You can also pass just a name string instead of `AppConfig`:+<Lang only="python">You can also pass just a name string instead of `AppConfig`:</Lang><Lang only="rust">Your own code opens the app by name, with the path of its state database:</Lang>{/* Rust: rust/sdk/SHOWCASE.md "Open and run an app" (verified against rust/sdk/cocoindex/src/app.rs) */}<LangTabs>@@ -94,13 +107,29 @@ let app = Environment::builder()</Fragment></LangTabs>+<RustNote>+Arguments are not bound to the app. The registered function reads its inputs itself, and when your own code runs the app, a closure passes them (see [Updating an app](#updating-an-app)).+</RustNote>++<Lang only="python">+:::tip-The main function is usually async. <Lang only="python">See [How Sync and Async Work Together](./sdk_overview#how-sync-and-async-work-together) for details.</Lang><Lang only="rust">See [Async only](/docs/rust/programming_guide/sdk_overview/#async-only) for details.</Lang>+The main function is usually async. See [How Sync and Async Work Together](./sdk_overview#how-sync-and-async-work-together) for details.:::+</Lang>++<Lang only="rust">++:::tip+The main function is always an `async fn`. See [Async only](/docs/rust/programming_guide/sdk_overview/#async-only) for details.+:::++</Lang>+## Updating an app-Call `update()` to execute the pipeline. It returns an `UpdateHandle` that is also `Awaitable`, so the simplest usage stays the same:+<Lang only="python">Call `update()` to execute the pipeline. It returns an `UpdateHandle` that is also `Awaitable`, so the simplest usage stays the same:</Lang><Lang only="rust">Call `run()` or `update()` with the main function to execute the pipeline:</Lang>{/* Rust: rust/sdk/SHOWCASE.md "Run apps with the `cocoindex` CLI", examples/rust/text_embedding/src/main.rs, rust/sdk/cocoindex/tests/pipeline.rs */}<LangTabs>@@ -139,13 +168,27 @@ let result = app.update_blocking(app_main)?;</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `live` option keeps the app running after the initial scan so live components can continue watching for changes. See [Live Mode](./live_mode).- `report_to_stdout` option prints periodic progress updates during execution. Pass `True` for the default refresh interval, or a `timedelta` to set it.- `full_reprocess` option reprocesses everything, bypassing all memoization: every component **and** every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost β this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function's work, bump its [`version`](./function#version) instead.-In Rust, these options are the fields of `UpdateOptions`: `live`, `report_to_stdout` (with `progress_refresh_interval`), `full_reprocess`, `preview` and `timeout`. Pass them to `app.update_with_options`, or to `app.start_update_with_options` for a handle:+</Lang>++<Lang only="rust">++**Options** are the fields of `UpdateOptions`. Pass them to `app.update_with_options`, or to `app.start_update_with_options` for a handle:++- `live` keeps the app running after the initial scan so live components can continue watching for changes. See [Live Mode](./live_mode).+- `report_to_stdout` prints periodic progress updates during execution. `progress_refresh_interval` sets the refresh interval.+- `full_reprocess` reprocesses everything, bypassing all memoization: every component **and** every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost β this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function's work, bump its [`version`](./function#version) instead.+- `preview` computes the target actions without applying them.+- `timeout` bounds how long the update may run.++</Lang>{/* Rust: rust/sdk/cocoindex/tests/fs_live.rs */}<LangTabs>@@ -178,23 +221,23 @@ handle.result().await?;When you update an App, CocoIndex:-1. Runs the lifespan setup (if not already done)+1. <Lang only="python">Runs the lifespan setup (if not already done)</Lang><Lang only="rust">Uses the environment the lifespans configured (`Environment::from_registered` runs them before it opens the state database)</Lang>2. Executes the main function (the root processing component), which mounts child processing components3. Compares the declared target states with the previous run and applies only the necessary changes to external systemsGiven the same logic and inputs, updates are repeatable. When logic or inputs change, only the affected parts re-execute.-To watch progress beyond the `report_to_stdout` flag, the `UpdateHandle` returned by `app.update()` also exposes stats programmatically β poll with `handle.stats()` or stream with `handle.watch()`. For those structured APIs, and for splitting a run into separately-reported scopes with `coco.stats_group()`, see [Progress monitoring](../advanced_topics/progress_monitoring). In Rust, `app.start_update(f)` returns the `UpdateHandle`: poll with `handle.stats_snapshot()`, wait for a change with `handle.changed().await`, and take the value with `handle.result().await`.+<Lang only="python">To watch progress beyond the `report_to_stdout` flag, the `UpdateHandle` returned by `app.update()` also exposes stats programmatically β poll with `handle.stats()` or stream with `handle.watch()`. For those structured APIs, and for splitting a run into separately-reported scopes with `coco.stats_group()`, see [Progress monitoring](../advanced_topics/progress_monitoring).</Lang><Lang only="rust">To watch progress beyond the `report_to_stdout` option, `app.start_update(app_main)` returns an `UpdateHandle` that exposes stats programmatically: poll with `handle.stats_snapshot()`, wait for a change with `handle.changed().await`, and take the value with `handle.result().await`. See [Progress monitoring](../advanced_topics/progress_monitoring).</Lang>## How an app runsAn App is the top-level runner and entry point. A **processing component** is the unit of incremental execution *within* an app.- Your app's main function runs as the **root processing component** at the root path.-- Each call to `mount()` or `use_mount()` declares a **child processing component** at a child path. Sugar APIs like `mount_each()` and `mount_target()` also create child components.+- <Lang only="python">Each call to `mount()` or `use_mount()` declares a **child processing component** at a child path. Sugar APIs like `mount_each()` and `mount_target()` also create child components.</Lang><Lang only="rust">Each `mount!` or `use_mount!` (or `ctx.mount`, `ctx.scope`) declares a **child processing component** at a child path. `mount_each!` and the connectors' `mount_*_target` functions also create child components.</Lang>- Each processing component declares a set of target states, and CocoIndex syncs them as a unit when that component finishes β all writes happen after processing completes, and each target backend applies its batch atomically when supported.-This is why `app.update()` does not "run everything from scratch": CocoIndex uses the component path tree to decide what can be reused and what must re-run.+This is why <Lang only="python">`app.update()`</Lang><Lang only="rust">an update</Lang> does not "run everything from scratch": CocoIndex uses the component path tree to decide what can be reused and what must re-run.For example, an app that processes files might mount one component per file β the per-file fan-out from [Core Concepts](./core_concepts#processing-component), shown here as a path tree:@@ -217,7 +260,7 @@ The simplest way to configure the database path is via the `COCOINDEX_DB` enviroexport COCOINDEX_DB=./cocoindex.db```-With `COCOINDEX_DB` set, you can create and run apps without any additional configuration:+With `COCOINDEX_DB` set, you can create and run apps without any additional configuration<Lang only="rust"> when the environment comes from `Environment::from_registered()` or the `cocoindex` CLI</Lang>:{/* Rust: examples/rust/text_embedding/src/main.rs; `COCOINDEX_DB` fallback verified in rust/sdk/cocoindex/src/app.rs `Environment::from_registered` */}<LangTabs>@@ -244,7 +287,7 @@ let stats = app.run(app_main).await?;env.shutdown().await;```-In Rust, `COCOINDEX_DB` applies to `Environment::from_registered()` and the Rust CLI. A plain `Environment::builder().build()` or `App::builder(name).build()` reads no environment variables: give it the path with `.db_path(..)`.+A plain `Environment::builder().build()` or `App::builder(name).build()` reads no environment variables: give it the path with `.db_path(..)`.</Fragment></LangTabs>@@ -253,7 +296,7 @@ For details on what the internal database stores and how to tune its LMDB settin## Lifespan (optional)-A **lifespan function** defines the CocoIndex runtime lifecycle: its setup runs when the runtime starts (automatically before the first `app.update()`), and its cleanup runs when the runtime stops. Use it to configure CocoIndex settings programmatically or to initialize shared resources that processing components can reuse.+A **lifespan function** defines the CocoIndex runtime lifecycle: its setup runs when the runtime starts (<Lang only="python">automatically before the first `app.update()`</Lang><Lang only="rust">in `Environment::from_registered()`, before the state database opens</Lang>), and its cleanup runs when the runtime stops. Use it to configure CocoIndex settings programmatically or to initialize shared resources that processing components can reuse.:::tipIf you only need to set the database path, using the `COCOINDEX_DB` environment variable is simpler than defining a lifespan function.@@ -261,7 +304,7 @@ If you only need to set the database path, using the `COCOINDEX_DB` environment### Defining a lifespan-Use the `@lifespan` decorator to register a lifespan function. By default, all apps share the same lifespan (unless you explicitly specify an app in a different [*Environment*](../advanced_topics/multiple_environments)). The function receives an `EnvironmentBuilder` for configuration and uses `yield` to separate setup from cleanup:+<Lang only="python">Use the `@lifespan` decorator to register a lifespan function. By default, all apps share the same lifespan (unless you explicitly specify an app in a different [*Environment*](../advanced_topics/multiple_environments)). The function receives an `EnvironmentBuilder` for configuration and uses `yield` to separate setup from cleanup:</Lang><Lang only="rust">Mark an `async fn` with `#[cocoindex::lifespan]` to register a lifespan function. Every app opened from `Environment::from_registered()` shares the registered lifespans; an app opened from an `Environment` you build yourself is in a different [*Environment*](../advanced_topics/multiple_environments). The function receives an `EnvironmentBuilder`, configures it, and returns it:</Lang>{/* Rust: examples/rust/text_embedding/src/main.rs */}<LangTabs>@@ -296,12 +339,14 @@ async fn lifespan(builder: EnvironmentBuilder) -> Result<EnvironmentBuilder> {}```-In Rust, the lifespan is an `async fn` that takes the `EnvironmentBuilder` and returns it. There is no `yield`: register cleanup with `builder.on_shutdown(..)`. Hooks run in reverse order when the environment shuts down. `Environment::from_registered()` and the Rust CLI run every registered lifespan before they open the state database.+Register cleanup with `builder.on_shutdown(..)`. The hooks run in reverse order of registration when the environment shuts down. `Environment::from_registered()` and the `cocoindex` CLI run every registered lifespan before they open the state database.</Fragment></LangTabs>-Setting `db_path` in the lifespan takes precedence over the `COCOINDEX_DB` environment variable. If neither is provided, CocoIndex will raise an error.+Setting `db_path` in the lifespan takes precedence over the `COCOINDEX_DB` environment variable. If neither is provided, CocoIndex <Lang only="python">will raise an error</Lang><Lang only="rust">returns an error</Lang>.++<Lang only="python">The lifespan function can be sync or async:@@ -314,16 +359,30 @@ def coco_lifespan(builder: coco.EnvironmentBuilder) -> Iterator[None]:yield```-A Rust lifespan is always an `async fn`.+</Lang>++<RustNote>+A lifespan is always an `async fn`, and no `yield` splits setup from cleanup: the function returns the builder, and `on_shutdown` hooks do the cleanup.+</RustNote>You can also use the lifespan to provide resources (like database connections) that processing components can access. See [Context](./context) for details on sharing resources across your pipeline.### Explicit lifecycle control (optional)+<Lang only="python">+The lifespan runs automatically the first time any App updates β most users don't need to do anything beyond defining the lifespan and calling `app.update()`.If you need more explicit control (for example, to know when startup completes for health checks, or to explicitly trigger shutdown) you can manage the lifecycle directly:+</Lang>++<Lang only="rust">++The lifecycle is always explicit: `Environment::from_registered().await?` runs the registered lifespans, and `env.shutdown().await` runs the `on_shutdown` hooks and closes the state database. `#[cocoindex::main]` builds the Tokio runtime and answers `cocoindex ...` CLI invocations before the body runs:++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md "Run apps with the `cocoindex` CLI", verified against rust/sdk/cocoindex/tests/registered.rs */}<LangTabs><Fragment slot="python">@@ -357,11 +416,13 @@ async fn main() -> Result<()> {}```-In Rust, the lifecycle is always explicit: `Environment::from_registered().await?` runs the registered lifespans, and `env.shutdown().await` runs the `on_shutdown` hooks. `#[cocoindex::main]` builds the Tokio runtime and answers the Rust CLI before the body runs. A second `shutdown` is a no-op.+The hooks run once: a second `shutdown` only closes the database. Await every running update or drop before you call `shutdown`.</Fragment></LangTabs>+<Lang only="python">+Or use the `runtime()` context manager, which supports both sync and async usage:```python@@ -376,8 +437,6 @@ with coco.runtime():app.update_blocking()```-The Rust SDK has no `runtime()` context manager: call `env.shutdown().await` when the work is done.-The same App can be retained and reused across sequential runtime lifecycles. After`stop()` returns (or a `runtime()` block exits), its next update or drop starts a newlifespan and uses freshly initialized resources. Persisted memoization and target-state@@ -393,17 +452,27 @@ runtime.Finish update and drop operations before stopping the runtime. Shutdown concurrent within-flight operations is not supported.+</Lang>++<RustNote>+An `Environment` does not restart after `shutdown`: its state database is closed. To run again, build a new environment with `Environment::from_registered()`. Persisted memoization and target-state tracking in the state database carry over to it.+</RustNote>+## Managing apps with CLICocoIndex provides a CLI for managing your apps without writing additional code.-For a Rust project, the `cocoindex` binary from `rust/cli` builds the crate and drives its binary. The crate's `main` must carry `#[cocoindex::main]`, and each app must carry `#[cocoindex::app]`. The CLI's app target is `[path][:app_name]`: a crate directory (default `.`), a `Cargo.toml`, or a built binary, with the app's name after a colon when the crate registers more than one app.+<Lang only="rust">++The `cocoindex` binary from `rust/cli` builds your crate and drives its binary. The crate's `main` must carry `#[cocoindex::main]`, and each app must carry `#[cocoindex::app]`. The CLI's app target is `[path][:app_name]`: a crate directory (default `.`), a `Cargo.toml`, or a built binary, with the app's name after a colon when the crate registers more than one app.++</Lang>### Update an appRun your app once to sync all target states:-{/* Rust: /tmp/coco-land-rust-cli-help.txt (`cocoindex update --help`) */}+{/* Rust: rust/cli/src/main.rs (`Command::Update`, the `[path][:app_name]` target) */}<LangTabs><Fragment slot="python">@@ -428,7 +497,7 @@ This executes your pipeline and applies all declared target states to external sRemove an app and revert all its target states:-{/* Rust: /tmp/coco-land-rust-cli-help.txt (`cocoindex drop --help`); `App::drop_state` in rust/sdk/cocoindex/tests/registered.rs */}+{/* Rust: rust/cli/src/main.rs (`Command::Drop`); `App::drop_state` in rust/sdk/cocoindex/tests/registered.rs */}<LangTabs><Fragment slot="python">@@ -450,6 +519,6 @@ From code, `app.drop_state().await?` does the same for one `App`.This will delete all target states created by the app (e.g., drop tables, delete rows) and clear its internal state.-`drop` is an explicit, foreground operation β any failure during the recursive delete (root or any descendant) raises rather than being silently logged. The internal tracking record for a component whose delete failed is preserved so the next `drop` (with the underlying problem fixed) can complete the cleanup. See [Error Handling](../advanced_topics/exception_handlers) for the general principle.+`drop` is an explicit, foreground operation β any failure during the recursive delete (root or any descendant) <Lang only="python">raises</Lang><Lang only="rust">returns an error</Lang> rather than being silently logged. The internal tracking record for a component whose delete failed is preserved so the next `drop` (with the underlying problem fixed) can complete the cleanup. See [Error Handling](../advanced_topics/exception_handlers) for the general principle.-See [CLI Reference](../cli) for more commands and options.+See <Lang only="python">[CLI Reference](../cli)</Lang><Lang only="rust">[CLI Reference](/docs/rust/cli/)</Lang> for more commands and options.diff --git a/docs/src/content/docs/programming_guide/processing_component.mdx b/docs/src/content/docs/programming_guide/processing_component.mdxindex 2ba629bd..ce67a12f 100644--- a/docs/src/content/docs/programming_guide/processing_component.mdx+++ b/docs/src/content/docs/programming_guide/processing_component.mdx@@ -4,6 +4,10 @@ description: >Processing components are the units of incremental execution and the syncboundaries for target states. Covers mounting APIs (mount, use_mount,mount_each, mount_target), component paths, and granularity tradeoffs.+rust_description: >+ Processing components are the units of incremental execution and the sync+ boundaries for target states. Covers mounting APIs (mount!, use_mount!,+ mount_each!, mount_target), component paths, and granularity tradeoffs.---import MountVsUseMount from '/src/components/diagrams/concepts/MountVsUseMount.astro';import LangTabs from '../../../components/LangTabs.astro';@@ -18,7 +22,7 @@ Most apps process many independent source items β files, rows, or entities. AA **component path** is the stable identifier for a processing component across runs (think of it like a path in a tree). CocoIndex uses it to match a component to its previous run, detect what changed for that item, and sync that component's target states as a unit when it finishes. This sync happens per component; CocoIndex does not wait for other components in the same app to complete.-Component paths are hierarchical and form a tree structure. You specify child paths using `coco.component_subpath()` with stable identifiers like string literals, file names, row keys, or entity IDs:+Component paths are hierarchical and form a tree structure. You specify child paths <Lang only="python">using `coco.component_subpath()`</Lang><Lang only="rust">as the key of each mount</Lang> with stable identifiers like string literals, file names, row keys, or entity IDs:{/* Rust: rust/sdk/cocoindex/tests/mount.rs (`mount!("b.md", ..)`, `ctx.with_subpath(&"process").mount(&"x", ..)`) */}<LangTabs>@@ -39,7 +43,7 @@ mount!("hello.pdf", process_file(ctx, file, target)).await?;ctx.with_subpath(&"user").mount(&user_id, |ctx| async move { /* ... */ Ok(()) }).await?;```-In Rust there is no `component_subpath` value. A mount takes its key as a `Display` value (a `&str`, a `String`, a number), and `ctx.with_subpath(&"user")` returns a `Ctx` whose mounts go one level down.+A key is any `IntoStableKey`: a `&str`, a `String`, an integer, a UUID, bytes or a `StableKey`. `ctx.with_subpath(&"user")` returns a `Ctx` whose mounts go one level down.</Fragment></LangTabs>@@ -55,7 +59,7 @@ Here's an example component path tree for a pipeline that processes files:βββ "world.pdf" β process_file component```-The tree is populated dynamically as the app runs β each `mount()` / `mount_each()` call adds a subpath.+The tree is populated dynamically as the app runs β each <Lang only="python">`mount()` / `mount_each()`</Lang><Lang only="rust">`mount!` / `mount_each!`</Lang> call adds a subpath.See [StableKey](./sdk_overview#stablekey) in the SDK Overview for details on what values can be used in component paths.@@ -65,11 +69,24 @@ Mounting is how you declare (instantiate) a processing component within an app aCocoIndex provides two core mounting APIs:+<Lang only="python">+- **`mount()`** β sets up a processing component in a child path without depending on data from it. This allows the component to refresh independently in live mode.- **`use_mount()`** β returns a value from the component's execution to the caller. The component at that path cannot refresh independently without re-executing the caller.+</Lang>++<Lang only="rust">++- **`mount!`** β sets up a processing component in a child path without depending on data from it. This allows the component to refresh independently in live mode.+- **`use_mount!`** β returns a value from the component's execution to the caller. The component at that path cannot refresh independently without re-executing the caller.++</Lang>+<MountVsUseMount />+<Lang only="python">+**Which one you reach for comes down to a single question: does the caller need a value back?** `use_mount()` consumes the child's return value, which *couples* the two β the call blocks until the child finishes and commits its target states, and the child can't refresh on its own without re-running the caller. `mount()` takes nothing back and returns as soon as the child is scheduled, so the child runs on its own and can [refresh independently in live mode](./live_mode) when its inputs change.And two sugar APIs that simplify common patterns:@@ -79,7 +96,26 @@ 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!`, `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:+</Lang>++<Lang only="rust">++**Which one you reach for comes down to a single question: does the caller need a value back?** `use_mount!` consumes the child's return value, which *couples* the two β the call waits until the child finishes and commits its target states, and the child can't refresh on its own without re-running the caller. `mount!` takes nothing back and returns as soon as the child is scheduled, so the child runs on its own and can [refresh independently in live mode](./live_mode) when its inputs change.++And APIs that simplify common patterns:++- **`mount_each!`** β mounts one component per item in a keyed collection; **`use_mount_each!`** also returns each child's value+- **`mount_target()`** β mounts a target without an explicit subpath; connectors wrap it in their `mount_*_target` functions++See also [`ctx.map`](#using-ctxmap-to-apply-transformations) for a utility API that operates within a component without creating new ones.++Each API has 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. `ctx.mount_each_live` is `ctx.mount_each` for a live source.++</Lang>++<RustNote title="Coming from Python">++The Python API names map to the Rust forms as follows:| Python | Rust macro | Rust method ||--------|------------|-------------|@@ -90,8 +126,10 @@ The Rust SDK has each API in two forms. The macros `mount!`, `use_mount!`, `moun| `coco.mount_target(target)` | β | `mount_target(&ctx, target_state)`, or a connector's `mount_*_target` || `coco.map(fn, items, ...)` | β | `ctx.map(items, async \|item\| { ... })` |+</RustNote>+### Automatic subpath derivation-`mount()`, `use_mount()`, and `mount_each()` all accept an optional `ComponentSubpath` as their first argument. When omitted, the subpath is **auto-derived** from the function name using `Symbol(fn.__name__)`.+<Lang only="python">`mount()`, `use_mount()`, and `mount_each()` all accept an optional `ComponentSubpath` as their first argument. When omitted, the subpath is **auto-derived** from the function name using `Symbol(fn.__name__)`.</Lang><Lang only="rust">`mount!`, `use_mount!`, `mount_each!` and `use_mount_each!` all accept an optional key as their first argument. When omitted, the subpath is **auto-derived** from the function name, as a plain string key.</Lang>{/* Rust: rust/sdk/cocoindex_macros/src/lib.rs (`mount!` doc), rust/sdk/cocoindex/tests/mount.rs */}<LangTabs>@@ -112,11 +150,13 @@ mount!(process_file(ctx, file, target)).await?;mount!("process_file", process_file(ctx, file, target)).await?;```-The Rust macros derive the subpath from the function's name too. The key is a plain string, not a `Symbol`. The methods `ctx.mount`, `ctx.scope` and `ctx.mount_each` always take an explicit key.+The methods `ctx.mount`, `ctx.scope` and `ctx.mount_each` always take an explicit key.</Fragment></LangTabs>+<Lang only="python">+This means the component path for a `process_file` function is `parent / Symbol("process_file")`. The function must have a `__name__` attribute; if it doesn't (e.g., a lambda), provide an explicit subpath.Since sibling component paths must not collide, you need an explicit subpath when:@@ -124,9 +164,22 @@ Since sibling component paths must not collide, you need an explicit subpath whe- **Different functions happen to share a `__name__`** β rare, but possible with wrappers or closures- **You want a specific path name** β different from the function name-### `mount()`+</Lang>++<Lang only="rust">++This means the component path for a `process_file` function is `parent / "process_file"`.++Since sibling component paths must not collide, you need an explicit key when:+- **The same function is mounted more than once** β auto-derived paths would be identical, so each call needs a distinct key+- **Functions in different modules share a name** β the derived key is the bare function name+- **You want a specific path name** β different from the function name++</Lang>-Use `mount()` when you don't need a return value from the processing component. It schedules the processing component to run and returns a handle:+### `mount`++Use <Lang only="python">`mount()`</Lang><Lang only="rust">`mount!`</Lang> when you don't need a return value from the processing component. It schedules the processing component to run and returns a handle:{/* Rust: rust/sdk/SHOWCASE.md "Mount processing components", verified against rust/sdk/cocoindex/tests/mount.rs */}<LangTabs>@@ -199,11 +252,11 @@ The handle is a `ComponentMountHandle`. Without `ready()`, the parent still waitYou usually only need to call `ready()` when you have logic that depends on the processing component's target states being applied β for example, querying the latest data from a target table after syncing it.-`mount()` also accepts **LiveComponent classes** β components that process continuously and react to changes incrementally instead of rescanning everything. See [Live Components](../advanced_topics/live_component) for details. In Rust, a `LiveComponent` is mounted with `ctx.mount_live(&key, component)`.+<Lang only="python">`mount()` also accepts **LiveComponent classes** β components that process continuously and react to changes incrementally instead of rescanning everything.</Lang><Lang only="rust">`ctx.mount_live(&key, component)` mounts a **`LiveComponent`** β a component that processes continuously and reacts to changes incrementally instead of rescanning everything.</Lang> See [Live Components](../advanced_topics/live_component) for details.-### `use_mount()`+### `use_mount`-Use `use_mount()` when you need the processing component's return value. It mounts the component, waits until it's ready, and returns the value directly:+Use <Lang only="python">`use_mount()`</Lang><Lang only="rust">`use_mount!`</Lang> when you need the processing component's return value. It mounts the component, waits until it's ready, and returns the value directly:{/* Rust: rust/sdk/SHOWCASE.md "Mount processing components", verified against rust/sdk/cocoindex/tests/memo_deps.rs (`use_mount!`) */}<LangTabs>@@ -254,11 +307,22 @@ The return value of a `use_mount!` child must implement `Serialize` and `Deseria</Fragment></LangTabs>-A common use of `use_mount()` is to obtain a [target](./target_state#where-do-targets-come-from) after its container target state is applied.+A common use of <Lang only="python">`use_mount()`</Lang><Lang only="rust">a foreground mount</Lang> is to obtain a [target](./target_state#where-do-targets-come-from) after its container target state is applied.++### `mount_each`++<Lang only="python">-### `mount_each()``mount_each()` mounts one processing component per item in a keyed iterable.+</Lang>++<Lang only="rust">++`mount_each!` mounts one processing component per item in a keyed collection.++</Lang>+{/* Rust: examples/rust/files_transform/src/main.rs */}<LangTabs><Fragment slot="python">@@ -281,6 +345,8 @@ mount_each!(files, |file| process_file(ctx, file, target)).await?;</Fragment></LangTabs>+<Lang only="python">+Each item in the iterable is a `(key, value)` tuple. The value is passed as the first argument to the function, and any additional arguments are passed through. Items are mounted under an [auto-derived subpath](#automatic-subpath-derivation) (`Symbol(fn.__name__)`), so the component path for each item is `parent / Symbol("process_file") / key`.In the static case this is just the keyed-loop form of [`mount()`](#mount) β the same per-file fan-out shown in [Core Concepts](./core_concepts#processing-component). The snippet above is equivalent to looping over the items and calling `mount(coco.component_subpath(coco.Symbol("process_file"), key), process_file, value, target)` for each one. The per-item `key` is what keeps each component's path stable across runs, so the engine matches, updates, and cleans up each item individually.@@ -292,10 +358,22 @@ handle = await coco.mount_each(process_file, files.items(), target)await handle.ready() # waits until every per-item component is ready```-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).+</Lang>++<Lang only="rust">++Each item is a `(key, value)` pair. The closure's call receives the value, and any other arguments are passed through. Items are mounted under an [auto-derived subpath](#automatic-subpath-derivation) (the function name), so the component path for each item is `parent / "process_file" / key`.++In the static case this is just the keyed-loop form of [`mount!`](#mount) β the same per-file fan-out shown in [Core Concepts](./core_concepts#processing-component). The per-item `key` is what keeps each component's path stable across runs, so the engine matches, updates, and cleans up each item individually.++Like `mount!`, `mount_each!` and `ctx.mount_each` do not carry return values from the mounted functions. They 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, the foreground forms `use_mount_each!` and `ctx.use_mount_each` 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 [`ctx.map`](#using-ctxmap-to-apply-transformations).++</Lang>+You can provide an explicit subpath as the first argument:{/* Rust: rust/sdk/cocoindex_macros/src/lib.rs (`mount_each!` doc), examples/rust/text_embedding/src/main.rs */}@@ -323,9 +401,11 @@ ctx.mount_each_live(&"process_file", files, move |ctx, file: FileEntry| {</Fragment></LangTabs>-Source connectors provide an `items()` method that returns `(StableKey, T)` pairs. For example, `localfs.walk_dir(...).items()` yields `(relative_path, File)` tuples. In Rust, `walk_items(dir, patterns)` returns the pairs as a `Vec`, and `walk_dir(dir).live()` returns a live feed for `ctx.mount_each_live`.+<Lang only="python">++Source connectors provide an `items()` method that returns `(StableKey, T)` pairs. For example, `localfs.walk_dir(...).items()` yields `(relative_path, File)` tuples.-Keys must be unique within one `mount_each()` call. If the iterable yields the same key twice, `mount_each()` raises a `coco.AlreadyDeclaredError` (a `ValueError` subclass) that names the repeated component path. In Rust, `ctx.mount_each` returns an error that names the duplicate key.+Keys must be unique within one `mount_each()` call. If the iterable yields the same key twice, `mount_each()` raises a `coco.AlreadyDeclaredError` (a `ValueError` subclass) that names the repeated component path.An item's key is relative to its source, so two sources can yield the same key. When you mount several sources under one parent component, give each `mount_each()` its own subpath:@@ -340,9 +420,25 @@ Without the subpaths, both calls mount under `Symbol("process_file")`, so a `REAIt also does one thing a hand-written loop can't: when a source connector supports live watching, its `items()` returns a `LiveMapView` or `LiveMapFeed` instead of a plain iterable, and `mount_each()` detects this and automatically adds, updates, and removes per-item components as the source changes β no changes to `mount_each()` itself are needed. See [Live Mode](./live_mode).+</Lang>++<Lang only="rust">++Source connectors return `(key, value)` pairs. For example, `walk_items(dir, patterns)` returns `(relative_path, FileEntry)` pairs as a `Vec`.++Keys must be unique within one `mount_each!` call. If the items yield the same key twice, the call returns an error that names the duplicate key.++An item's key is relative to its source, so two sources can yield the same key. When you mount several sources under one parent component, give each `mount_each!` its own prefix, as in `mount_each!("files", files, ..)` above. Without the prefixes, both calls mount under `"process_file"`, so a `README.md` in each source gets the same component path, and the second call returns the same error. The target states that the items declare need distinct keys too, so give each source its own target.++A live source takes the closure form: `walk_dir(dir).live()` returns a live feed, and `ctx.mount_each_live` adds, updates, and removes per-item components as the source changes. See [Live Mode](./live_mode).++</Lang>+### `mount_target()``mount_target()` mounts a target without requiring an explicit subpath.+<Lang only="python">+```pythonfrom cocoindex.connectors import localfs@@ -351,7 +447,13 @@ dir_target = await coco.mount_target(localfs.dir_target(outdir))The component path is derived automatically from the target's globally unique key β you don't need to create a `component_subpath` for it. This is sugar over calling `use_mount()` with a target declaration function.-In Rust, `mount_target(&ctx, target_state)` is the generic form, for connector authors. Pipelines use the connectors' `mount_*` functions below.+</Lang>++<Lang only="rust">++`mount_target(&ctx, target_state)` derives the component path from the target's globally unique key, so you don't choose a key for it. It is the generic form, for connector authors; pipelines use the connectors' `mount_*` functions below.++</Lang>Connectors also provide convenience methods that wrap `mount_target()`:@@ -394,10 +496,25 @@ let target_table = postgres::mount_table_target(</Fragment></LangTabs>+<Lang only="python">+### Using `component_subpath` as a context managerYou can use `component_subpath()` as a context manager to create nested paths without repeating common prefixes:+</Lang>++<Lang only="rust">++{/* Keeps the Python anchor, which other pages link to, valid on the Rust page. */}+<span id="using-component_subpath-as-a-context-manager"></span>++### Nesting paths with `with_subpath`++You can use `ctx.with_subpath()` to create nested paths without repeating common prefixes:++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md "Nested component paths", verified against rust/sdk/cocoindex/tests/mount.rs */}<LangTabs><Fragment slot="python">@@ -424,11 +541,13 @@ for file in files {}```-`ctx.with_subpath(&"process")` returns a scoped `Ctx`; the original is unchanged. Chain calls for a multi-part prefix. The scoped context still belongs to the same component, so target states declared through it are the component's own. `use_state` is an error on a subpath context, as in Python.+`ctx.with_subpath(&"process")` returns a scoped `Ctx`; the original is unchanged. Chain calls for a multi-part prefix. The scoped context still belongs to the same component, so target states declared through it are the component's own. `use_state` is an error on a subpath context: the state belongs to the component, not to the subpath.</Fragment></LangTabs>+<Lang only="python">+This is equivalent to:```python@@ -441,13 +560,15 @@ for f in files:)```+</Lang>+:::tip-When iterating over keyed items, prefer [`mount_each()`](#mount_each) β it handles the loop and subpath creation for you.+When iterating over keyed items, prefer <Lang only="python">[`mount_each()`](#mount_each)</Lang><Lang only="rust">[`mount_each!`](#mount_each)</Lang> β it handles the loop and subpath creation for you.:::## Memoized components-`memo=True` on a function you **mount** memoizes the whole component β the *processing-component-level* memoization introduced in [Core Concepts](./core_concepts#function-memoization-skip-unchanged-computations). On a cache hit the body doesn't run, and everything the previous run produced is carried over as a unit: the component's declared [target states](./target_state) **and** its child mounts. Cleanup of no-longer-mounted children only applies when the body actually *runs* β a run that no longer mounts a child removes that child's subtree, while a cache hit retains it.+<Lang only="python">`memo=True`</Lang><Lang only="rust">`memo`</Lang> on a function you **mount** memoizes the whole component β the *processing-component-level* memoization introduced in [Core Concepts](./core_concepts#function-memoization-skip-unchanged-computations). On a cache hit the body doesn't run, and everything the previous run produced is carried over as a unit: the component's declared [target states](./target_state) **and** its child mounts. Cleanup of no-longer-mounted children only applies when the body actually *runs* β a run that no longer mounts a child removes that child's subtree, while a cache hit retains it.{/* Rust: examples/rust/text_embedding/src/main.rs */}<LangTabs>@@ -477,18 +598,22 @@ ctx.mount_each_live(&"process_file", files, move |ctx, file: FileEntry| {.await?;```-In Rust, the macros `mount!`, `use_mount!` and `mount_each!` memoize the component on the function's logic and arguments even without `memo`: an unchanged child is skipped on the next run. The closure forms (`ctx.mount`, `ctx.scope`, `ctx.mount_each`, `ctx.mount_each_live`) always run the body, so put `memo` on the function they call, as above. The table target is not `MemoInput`; `memo_key(table = skip)` leaves it out of the key.+The closure forms (`ctx.mount`, `ctx.scope`, `ctx.mount_each`, `ctx.mount_each_live`) always run the body, so put `memo` on the function they call, as above. The table target is not `MemoInput`; `memo_key(table = skip)` leaves it out of the key.</Fragment></LangTabs>+<RustNote>+The macros `mount!`, `use_mount!` and `mount_each!` memoize the component on the function's logic and arguments even without `memo`: an unchanged child is skipped on the next run.+</RustNote>+Skipping a stable item this way costs almost nothing in storage, provided you follow one principle:-- **Declare large values as target states; don't return them.** Every memo entry β whether for a memoized component or for a memoized function called directly inside one (the *transform-level* memoization from Core Concepts) β must store its return value in order to serve a cache hit. A component that outputs via [`declare_row(...)`](./target_state) and returns `None` keeps its entry tiny: the declared values live in the component's own tracking, which [sync](#how-target-states-sync) needs regardless. A memoized function that *returns* a large value (an embedding vector, a parsed document) stores that value in every entry. A secondary difference: a directly-called memoized function's entry also records a reference to each target state it declared, so a hit can keep those states alive β a per-state cost that mounting avoids. See the cost note in [When to memoize](./function#when-to-memoize).-- **A memoized component may mount children.** A memoized function *called directly* cannot mount β mounting is a side effect its cache can't replay ([`memo=True` constraints](./function#memoization)) β but the restriction doesn't apply once the function is mounted as a component. A memoized parent that mounts children still invalidates when a child's logic changes β the child's fingerprint is part of the parent's recorded logic deps.-- **A component that reads beyond its arguments records what it read.** With [`coco.use_data_dep`](./function#data-dependencies-datadep-and-use_data_dep) (experimental) a body records the files (or anything else) it chose to read while running, and its entry is reused only while those reads validate. The records stay in that component's own entry; a memoized ancestor of such a component is reused only after validating those records from that entry too, through the path it stored, so one invalid read anywhere beneath it re-runs the ancestor's body (which is what re-runs the component that read). Its memoized children are carried over with it on a hit, and still hit on their own entries when its body runs.+- **Declare large values as target states; don't return them.** Every memo entry β whether for a memoized component or for a memoized function called directly inside one (the *transform-level* memoization from Core Concepts) β must store its return value in order to serve a cache hit. A component that outputs via [`declare_row(...)`](./target_state) and returns <Lang only="python">`None`</Lang><Lang only="rust">`()`</Lang> keeps its entry tiny: the declared values live in the component's own tracking, which [sync](#how-target-states-sync) needs regardless. A memoized function that *returns* a large value (an embedding vector, a parsed document) stores that value in every entry. A secondary difference: a directly-called memoized function's entry also records a reference to each target state it declared, so a hit can keep those states alive β a per-state cost that mounting avoids. See the cost note in [When to memoize](./function#when-to-memoize).+- **A memoized component may mount children.** A memoized function *called directly* cannot mount β mounting is a side effect its cache can't replay ([<Lang only="python">`memo=True` constraints</Lang><Lang only="rust">memoization constraints</Lang>](./function#memoization)) β but the restriction doesn't apply once the function is mounted as a component. A memoized parent that mounts children still invalidates when a child's logic changes β the child's fingerprint is part of the parent's recorded logic deps.+- **A component that reads beyond its arguments records what it read.** With [<Lang only="python">`coco.use_data_dep`</Lang><Lang only="rust">`ctx.use_data_dep`</Lang>](./function#data-dependencies-datadep-and-use_data_dep) (experimental) a body records the files (or anything else) it chose to read while running, and its entry is reused only while those reads validate. The records stay in that component's own entry; a memoized ancestor of such a component is reused only after validating those records from that entry too, through the path it stored, so one invalid read anywhere beneath it re-runs the ancestor's body (which is what re-runs the component that read). Its memoized children are carried over with it on a hit, and still hit on their own entries when its body runs.-Where to put `memo=True` follows the placement rule in [When to memoize](./function#when-to-memoize) β *memoize a boundary only if its key can hit while every enclosing memo boundary misses*: the per-file pipeline above composes a file-level component memo with a chunk-level embedding memo, while a *memoized* component whose path is keyed by a content hash of its input makes any inner memo over the same content mostly redundant.+<Lang only="python">Where to put `memo=True`</Lang><Lang only="rust">Where to put `memo`</Lang> follows the placement rule in [When to memoize](./function#when-to-memoize) β *memoize a boundary only if its key can hit while every enclosing memo boundary misses*: the per-file pipeline above composes a file-level component memo with a chunk-level embedding memo, while a *memoized* component whose path is keyed by a content hash of its input makes any inner memo over the same content mostly redundant.## How target states sync@@ -512,15 +637,26 @@ CocoIndex processes each component in two phases: **processing** (running your f### Failure isolation-The framework's general rule: **a call raises on failure iff the failed work was on the critical path for the call to return.**+The framework's general rule: **a call <Lang only="python">raises</Lang><Lang only="rust">returns an error</Lang> on failure iff the failed work was on the critical path for the call to return.**++<Lang only="python">- **`use_mount()`** β you're awaiting the child's *value*, so the child succeeding is on the critical path. The child's exception propagates to the parent.- **`mount()` and `mount_each()`** β these return as soon as the work is *scheduled* (you get a handle back). The child's execution runs in the background, off your critical path. A failure in one child does **not** affect the parent or siblings β by default the exception is logged and other components continue. One bad file shouldn't take down the entire pipeline.+</Lang>++<Lang only="rust">++- **`use_mount!`** (and `use_mount_each!`, `ctx.scope`) β you're awaiting the child's *value*, so the child succeeding is on the critical path. The child's error propagates to the parent.+- **`mount!` and `mount_each!`** (and `ctx.mount`, `ctx.mount_each`) β these return as soon as the work is *scheduled* (you get a handle back). The child's execution runs in the background, off your critical path. A failure in one child does **not** affect the parent or siblings β by default the error is logged and other components continue. One bad file shouldn't take down the entire pipeline.++</Lang>+To react to background failures, you can:-- Install [exception handlers](../advanced_topics/exception_handlers#exception-handlers) β global or scoped β to send alerts, record metrics, or implement custom logic. A handler that raises propagates the failure through `await handle.ready()` if you choose to await it. In Rust, `EnvironmentBuilder::exception_handler` installs a global handler and `ctx.with_exception_handler(handler)` returns a scoped `Ctx`; a child mounted from it inherits the handler chain. A handler returns `Ok(())` to swallow the failure or `Err(_)` to pass it on, and the last error reaches `handle.ready()`.-- [Monitor app progress](../advanced_topics/progress_monitoring) β `UpdateStats` exposes per-component stats including error counts, so you can detect failures programmatically.+- Install [exception handlers](../advanced_topics/exception_handlers#exception-handlers) β global or scoped β to send alerts, record metrics, or implement custom logic. <Lang only="python">A handler that raises propagates the failure through `await handle.ready()` if you choose to await it.</Lang><Lang only="rust">`EnvironmentBuilder::exception_handler` installs a global handler and `ctx.with_exception_handler(handler)` returns a scoped `Ctx`; a child mounted from it inherits the handler chain. A handler returns `Ok(())` to swallow the failure or `Err(_)` to pass it on, and the last error reaches `handle.ready()`.</Lang>+- [Monitor app progress](../advanced_topics/progress_monitoring) β <Lang only="python">`UpdateStats`</Lang><Lang only="rust">`RunStats`</Lang> exposes per-component stats including error counts, so you can detect failures programmatically.For the full picture (including the critical-path principle applied to every API, interrupted update recovery, and the exception handler API) see [Error Handling](../advanced_topics/exception_handlers).@@ -537,10 +673,22 @@ When defining processing components, think about granularity (what one path reprFor example, if you're processing files:+<Lang only="python">+- **Coarse**: one component for "all files" (`coco.component_subpath("process")`)- **Medium**: one component per file (`coco.component_subpath("process", file_path)`)- **Fine**: one component per chunk (`coco.component_subpath("process", file_path, chunk_id)`)+</Lang>++<Lang only="rust">++- **Coarse**: one component for "all files" (path `process`)+- **Medium**: one component per file (path `process / file_path`)+- **Fine**: one component per chunk (path `process / file_path / chunk_id`)++</Lang>+In general:- **Coarse-grained** (fewer, larger components): More target states sync together as a unit, but you only see updates after the larger component finishes.@@ -548,6 +696,8 @@ In general:For small datasets, a single processing component that owns all target states is simple and ensures all target states sync together. As data grows, consider breaking it down into one component per source item (e.g., one per file) to reduce latency: you see each item's target states synced as soon as it's processed, without waiting for the full dataset to complete. This also helps isolate failures to that item.+<Lang only="python">+## Explicit context managementCocoIndex automatically propagates component context through Python's `contextvars`, which works for ordinary function calls (both sync and async). However, in situations where context variables are not preserved (for example, when using `concurrent.futures.ThreadPoolExecutor`), you need to explicitly capture and attach the context.@@ -574,7 +724,13 @@ def app_main() -> None:This pattern ensures that CocoIndex can track component relationships and target state ownership even across thread boundaries.-The Rust SDK has no ambient context to capture: the `Ctx` is an explicit, `Clone` value. Pass a clone into a spawned task:+</Lang>++<Lang only="rust">++## Passing the context to other tasks++The component context is the `Ctx` value your function receives, so it goes wherever you pass it. A `Ctx` is `Clone`: pass a clone into a spawned task, and CocoIndex still tracks component relationships and target state ownership there:{/* Rust: rust/sdk/cocoindex/tests/batching_runner.rs */}```rust@@ -582,11 +738,30 @@ let ctx = ctx.clone();tokio::spawn(async move { limited(&ctx, item).await })```+</Lang>++<RustNote>+There is no ambient context to capture and attach: every function takes the `Ctx` explicitly.+</RustNote>+## Processing helpers+<Lang only="python">+### Using CocoIndex `map()` to apply transformations+The `map()` API (also known as `coco.map()`) applies an async function to each item in a collection, running all calls concurrently within the current processing component. Unlike [`mount()`](#mount) and [`mount_each()`](#mount_each), it does **not** create child processing components β it's purely concurrent execution (similar to `asyncio.gather()`).+</Lang>++<Lang only="rust">++### Using `ctx.map` to apply transformations++`ctx.map(items, f)` applies an async closure to each item in a collection, running all calls concurrently within the current processing component. Unlike [`mount!`](#mount) and [`mount_each!`](#mount_each), it does **not** create child processing components β it's purely concurrent execution (similar to `futures::future::join_all`).++</Lang>+{/* Rust: examples/rust/text_embedding/src/main.rs */}<LangTabs><Fragment slot="python">@@ -625,14 +800,29 @@ async fn process_file(ctx: &Ctx, file: &FileEntry, table: &postgres::TableTarget}```-`ctx.map(items, f)` takes an async closure. The futures run in place, so the closure may borrow the caller's values (the text, the `IdGenerator`, the target).+The futures run in place, so the closure may borrow the caller's values (the text, the `IdGenerator`, the target).</Fragment></LangTabs>-The first argument to the function receives each item; additional arguments are passed through to every call. The `coco.map()` API returns a `list` of the results, in the same order as the input items. The Rust `ctx.map` returns a `Vec` in the same order.+<Lang only="python">++The first argument to the function receives each item; additional arguments are passed through to every call. The `coco.map()` API returns a `list` of the results, in the same order as the input items.#### When to use the `map()` API vs `mount_each()`- Use **`mount_each()`** when each item should be its own processing component β with its own component path, target state ownership, and target states sync boundary.- Use the **`map()`** API when you want to process items concurrently *within* the current component, without creating new component boundaries. This is common for sub-item work like processing chunks within a file β the same within-component chunk work the [chunk-embedding pipeline in Core Concepts](./core_concepts#processing-component) walks through.++</Lang>++<Lang only="rust">++The closure receives each item. `ctx.map` returns a `Vec` of the results, in the same order as the input items. Every started item runs to completion, then the first error in input order is returned.++#### When to use `ctx.map` vs `mount_each!`++- Use **`mount_each!`** when each item should be its own processing component β with its own component path, target state ownership, and target states sync boundary.+- Use **`ctx.map`** when you want to process items concurrently *within* the current component, without creating new component boundaries. This is common for sub-item work like processing chunks within a file β the same within-component chunk work the [chunk-embedding pipeline in Core Concepts](./core_concepts#processing-component) walks through.++</Lang>diff --git a/docs/src/content/docs/programming_guide/target_state.mdx b/docs/src/content/docs/programming_guide/target_state.mdxindex 1cac42d4..42a99b88 100644--- a/docs/src/content/docs/programming_guide/target_state.mdx+++ b/docs/src/content/docs/programming_guide/target_state.mdx@@ -14,7 +14,7 @@ Read [Core Concepts](./core_concepts) for target states and the declarative *tarA **target state** represents what you want to exist in an external system. You *declare* target states in your code; CocoIndex keeps them in sync with your intent β creating, updating, or removing them as needed.:::note[Terminology]-A **target** is the external system you write to β a directory, a database table, a vector store collection, etc. In Python, targets are represented by objects like `DirTarget` and `TableTarget`; in Rust, by `DirTarget` and the connectors' `TableTarget` types. A **target state** is what you want to exist *in* that target β a specific file, row, or embedding.+A **target** is the external system you write to β a directory, a database table, a vector store collection, etc. Targets are represented by objects like `DirTarget` and <Lang only="python">`TableTarget`</Lang><Lang only="rust">the connectors' `TableTarget` types</Lang>. A **target state** is what you want to exist *in* that target β a specific file, row, or embedding.CocoIndex treats your declarations as the source of truth: if you stop declaring a target state, CocoIndex will remove it from the target.:::@@ -193,11 +193,17 @@ The row type derives `SchemaFields`, and `TableSchema::from_row::<Row>(keys)` buThese convenience methods wrap [`mount_target()`](./processing_component#mount_target), which automatically derives the component path from the target's globally unique key. See [Processing Component](./processing_component) for more on mounting APIs.+<Lang only="python">+:::tip[Type safety]Targets like `DirTarget` and `TableTarget` have two statuses: **pending** (just created) and **resolved** (after the container target state is ready). The type system tracks this β if you try to use a pending target before it's resolved, type checkers like mypy will flag the error.:::-The Rust targets have no pending status: `mount_table_target` is `async` and returns the target once the container is ready, and `DirTarget::mount` returns a ready handle. A target handle is `Clone`, so one handle can be passed to every per-item component.+</Lang>++<RustNote>+A target has no pending status: `mount_table_target` is `async` and returns the target once the container is ready, and `DirTarget::mount` returns a ready handle. A target handle is `Clone`, so one handle can be passed to every per-item component.+</RustNote>## How CocoIndex syncs target states@@ -252,15 +258,19 @@ Under the hood, CocoIndex compares your declared target states with the previousCocoIndex ensures a container exists before its contents are added, and syncs the contents individually only while the container is still declared. Once a container is no longer declared, its contents are handled by the container's own removal, in one of two ways defined by the connector:- **Destroy** β CocoIndex owns the container and removes it together with its contents: dropping a table takes its rows with it, removing a directory takes its files, dropping a graph node table takes every node carrying its label.-- **Abandon** β the container is user-managed (a Kafka or Iggy topic, or a table or collection declared with `managed_by="user"`). CocoIndex stops writing to it and leaves its contents untouched: no per-row deletes or per-message tombstones are issued.+- **Abandon** β the container is user-managed (a Kafka or Iggy topic, or a table or collection declared with <Lang only="python">`managed_by="user"`</Lang><Lang only="rust">`ManagedTargetOptions::user_managed()`</Lang>). CocoIndex stops writing to it and leaves its contents untouched: no per-row deletes or per-message tombstones are issued.-`App.drop()` follows the same rule: it destroys CocoIndex-owned containers and abandons user-managed ones. To remove the contents of a user-managed container, drain it first by keeping the container declared with no contents for one update β see [Kafka](../connectors/kafka#abandoning-a-topic) and [Iggy](../connectors/iggy#abandoning-a-topic) for the recipe.+<Lang only="python">`App.drop()`</Lang><Lang only="rust">`App::drop_state()`</Lang> follows the same rule: it destroys CocoIndex-owned containers and abandons user-managed ones. To remove the contents of a user-managed container, drain it first by keeping the container declared with no contents for one update β see [Kafka](../connectors/kafka#abandoning-a-topic) and [Iggy](../connectors/iggy#abandoning-a-topic) for the recipe.A target state's identity is its key. CocoIndex doesn't detect two different keys that reach the same physical object: two directories that overlap or alias through a symlink, two [`ContextKey`s](./context#contextkey-as-stable-identity) for one database, or two names or IDs that the backend treats as equal (for example, table names that differ only in case). CocoIndex syncs them as two target states, so syncing one can overwrite or delete the other. Keeping the objects behind different keys apart is your responsibility.### Inspecting stored target states-The state database records every tracked target state with the component that owns it. Both CLIs print them with `cocoindex show --target-states`. In Rust code, `cocoindex::inspect` reads the same records from an `App`, or from an `Environment` and an app name with the `_by_name` functions:+The state database records every tracked target state with the component that owns it. The CLI prints them with `cocoindex show --target-states`.++<Lang only="rust">++From code, `cocoindex::inspect` reads the same records from an `App`, or from an `Environment` and an app name with the `_by_name` functions:{/* Rust: rust/sdk/SHOWCASE.md "Inspect stored state", verified against rust/sdk/cocoindex/tests/inspect.rs */}```rust@@ -276,6 +286,8 @@ while let Some(entry) = entries.try_next().await? {Each `TargetStateEntry` carries the target state's readable path, its fingerprint path, and its owner's component path. `inspect::list_stable_paths` and `inspect::iter_stable_path_details` list the components themselves, with the count of target states each one owns.+</Lang>+### What happens when a target's schema changesWhen you change a container target state's declaration (e.g., add a column to a table schema, change a primary key), CocoIndex detects the change and does its best to alter the target in place. If the change is too large to alter (e.g., changing primary keys), the target is dropped and recreated.@@ -289,6 +301,4 @@ For cases where connector-specific APIs don't cover your needs, CocoIndex provid- `declare_target_state()` β declare a leaf target state- `declare_target_state_with_child()` β declare a target state that provides child target states-These are exported from `cocoindex` and used internally by connectors. For defining custom targets, see [Custom Target States Connector](../advanced_topics/custom_target_connector).--The Rust SDK exports the same two functions, `declare_target_state(ctx, provider.target_state(key, value))` and `declare_target_state_with_child`, next to `register_root_target_states_provider(ctx, name, handler)`, which registers a `TargetHandler` and returns the provider. The Rust tests in `rust/sdk/cocoindex/tests/mount.rs` show a minimal handler.+These are exported from `cocoindex` and used internally by connectors.<Lang only="rust"> A leaf declaration reads `declare_target_state(ctx, provider.target_state(key, value))`. `register_root_target_states_provider(ctx, name, handler)` registers a `TargetHandler` and returns the provider; the tests in `rust/sdk/cocoindex/tests/mount.rs` show a minimal handler.</Lang> For defining custom targets, see [Custom Target States Connector](../advanced_topics/custom_target_connector).