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(advanced): Python and Rust pages for the advanced topics (#2752)
LJ π₯₯π΄1a50db5f257f
diff --git a/docs/src/content/docs/advanced_topics/concurrency_control.mdx b/docs/src/content/docs/advanced_topics/concurrency_control.mdxindex a4467963..5a69c471 100644--- a/docs/src/content/docs/advanced_topics/concurrency_control.mdx+++ b/docs/src/content/docs/advanced_topics/concurrency_control.mdx@@ -12,7 +12,7 @@ CocoIndex executes each [processing component](../programming_guide/processing_c## Setting the limit-Set `max_inflight_components` in `AppConfig`:+Set <Lang only="python">`max_inflight_components` in `AppConfig`</Lang><Lang only="rust">`max_inflight_components` on the `App` builder</Lang>:{/* Rust: rust/sdk/cocoindex/src/app.rs (AppBuilder::max_inflight_components, EnvironmentBuilder::max_inflight_components) */}<LangTabs>@@ -42,9 +42,15 @@ let app = App::builder("MyPipeline")</Fragment></LangTabs>-With `max_inflight_components=4`, at most 4 processing components execute at the same time. When a component finishes, the next pending one starts. A `mount()`, `use_mount()` or `mount_each()` call waits while no slot is free, so a parent cannot run ahead of its children without bound: a loop that mounts a child per source item advances only as fast as children finish.+With a limit of 4, at most 4 processing components execute at the same time. When a component finishes, the next pending one starts. A <Lang only="python">`mount()`, `use_mount()` or `mount_each()`</Lang><Lang only="rust">`ctx.mount`, `ctx.scope` / `use_mount!` or `ctx.mount_each`</Lang> call waits while no slot is free, so a parent cannot run ahead of its children without bound: a loop that mounts a child per source item advances only as fast as children finish.-Setting `max_inflight_components=1` serializes all components β only one runs at a time.+<Lang only="rust">++`ctx.mount_each` and `ctx.mount_each_stream` mount each item as a background child and admit the items at the pace slots free up; `ctx.use_mount_each` runs the items in the foreground and returns their values in input order. Both draw on the same limit.++</Lang>++A limit of 1 serializes all components β only one runs at a time.You can also set the limit via the `COCOINDEX_MAX_INFLIGHT_COMPONENTS` environment variable:@@ -52,47 +58,59 @@ You can also set the limit via the `COCOINDEX_MAX_INFLIGHT_COMPONENTS` environmeexport COCOINDEX_MAX_INFLIGHT_COMPONENTS=4```-**Precedence:** `AppConfig` value (in Rust, the builder's `max_inflight_components`) > environment variable > default (1024). Rust reads the variable when an app is created.+**Precedence:** <Lang only="python">`AppConfig` value</Lang><Lang only="rust">the builder's `max_inflight_components`</Lang> > environment variable > default (1024).<Lang only="rust"> The variable is read when an app is created.</Lang>## Nested mounts: a parent lends its slot-A parent component usually waits for its children: `use_mount()` returns the child's result, and a component's own target states are committed only once all its children are done. If a waiting parent simply kept its slot, a small limit could fill up with waiting parents and leave no slot for the children they wait for.+A parent component usually waits for its children: <Lang only="python">`use_mount()`</Lang><Lang only="rust">`use_mount!` / `ctx.scope`</Lang> returns the child's result, and a component's own target states are committed only once all its children are done. If a waiting parent simply kept its slot, a small limit could fill up with waiting parents and leave no slot for the children they wait for.Instead, a parent keeps its slot while it waits and **lends it to one child at a time**:* The first child a parent mounts runs on the parent's slot; it needs no free slot of its own.-* Further children take free slots from the pool, and their `mount()` / `use_mount()` calls wait while the pool is empty.+* Further children take free slots from the pool, and their mount calls wait while the pool is empty.* When the child running on the lent slot finishes, the slot passes to the parent's next waiting child.-So a parent that is blocked β on its children, or on anything else after mounting one, such as an application-level `asyncio.Semaphore` β always has one child that can run, and a hierarchy of any depth completes even with `max_inflight_components=1`. The limit bounds the components that execute at the same time; counting the parents waiting on them, the components in flight are bounded by the limit times the depth of the component hierarchy.+So a parent that is blocked β on its children, or on anything else after mounting one, such as an application-level <Lang only="python">`asyncio.Semaphore`</Lang><Lang only="rust">`tokio::sync::Semaphore`</Lang> β always has one child that can run, and a hierarchy of any depth completes even with a limit of 1. The limit bounds the components that execute at the same time; counting the parents waiting on them, the components in flight are bounded by the limit times the depth of the component hierarchy.A few related rules:-* A component that awaits a function call β including a batched one (`@coco.fn.as_async(batching=True)`) β keeps its slot; only mounting a child lends it.-* When several parents mount the same component at once (two `App.update()` calls overlapping, or several owners of a shared component), only the run that executes takes a slot. The others wait for it without a slot and reuse its result.-* Live components (`coco.auto_refresh`, `mount_each()` over a live map) borrow the slot of the component that mounted them for their cycles and item updates, like its other children, for as long as it runs; afterwards they take slots from the pool like any other component.-* Deleting components (cleaning up a removed subtree, `App.drop()`) is bounded by the same limit.+* A component that awaits a function call β including a batched one (<Lang only="python">`@coco.fn.as_async(batching=True)`</Lang><Lang only="rust">`#[cocoindex::function(batching)]`</Lang>) β keeps its slot; only mounting a child lends it.+* When several parents mount the same component at once (two app updates overlapping, or several owners of a shared component), only the run that executes takes a slot. The others wait for it without a slot and reuse its result.+* Live components (<Lang only="python">`coco.auto_refresh`, `mount_each()` over a live map</Lang><Lang only="rust">`ctx.auto_refresh`, `ctx.mount_live`, `ctx.mount_each_live`</Lang>) borrow the slot of the component that mounted them for their cycles and item updates, like its other children, for as long as it runs; afterwards they take slots from the pool like any other component.+* Deleting components (cleaning up a removed subtree, dropping an app) is bounded by the same limit.## Live components share the limit fairly[Live components](./live_component) update on their own schedules, and one of them can have far more work queued than another: a full re-index next to a refresh of a few changed items. The limit is shared fairly between **independent updates**, so a small update never waits for a large one's whole backlog:-* An independent update is an `App.update()`, one cycle of a live component (each refresh of `coco.auto_refresh`), or one item update of `mount_each()` over a live map. Every component an update mounts belongs to that update.+* An independent update is an app update, one cycle of a live component (each refresh of <Lang only="python">`coco.auto_refresh`</Lang><Lang only="rust">`ctx.auto_refresh`</Lang>), or one item update of <Lang only="python">`mount_each()` over a live map</Lang><Lang only="rust">`ctx.mount_each_live`</Lang>. Every component an update mounts belongs to that update.* A component that finds a free slot takes it at once, and no slot is reserved, so an update that runs alone can use the whole limit.* When no slot is free, a slot that frees up goes to whichever waiting side holds the fewest slots: first among the app's updates and its live components, then, inside the live component that wins, among its own updates and the live components they mounted. Among equals it goes to the one that started waiting first, and within one update components start in the order they asked.* A live component mounted by another live component's update counts as part of that live component.Fairness only decides which waiting component gets a slot that frees up. It never takes a slot from a running component, and the lending above works the same way.-## Other concurrency controls in the Rust SDK+## Other concurrency controls++The component limit bounds how many components run at once. Four more controls each act on a smaller unit of work.++<Lang only="python">++### Concurrent items with `coco.map`++`coco.map(fn, items)` runs `fn` for every item at once, inside the current component, and collects the results in input order. No processing components are created. Every started item runs to completion; then the first error in input order is raised. Use `coco.mount_each` instead when each item should be its own component.-The component limit bounds how many components run at once. The Rust SDK has three more controls, each on a smaller unit of work.+</Lang>++<Lang only="rust">### Concurrent items with `ctx.map``ctx.map(items, f)` runs `f` for every item at once, inside the current component, and collects the results in input order. Every started item runs to completion; then the first error in input order is returned. Use `ctx.mount_each` instead when each item should be its own component.-{/* Rust: rust/sdk/cocoindex/src/ctx.rs (Ctx::map doc comment) */}+</Lang>++{/* Python: python/cocoindex/_internal/api.py (map). Rust: rust/sdk/cocoindex/src/ctx.rs (Ctx::map doc comment) */}<LangTabs><Fragment slot="python">@@ -114,7 +132,7 @@ let results = ctx.map(tasks, |task| async move {### Batch size of a batched function-A `#[cocoindex::function(batching, max_batch_size = N)]` body receives up to `N` items at once; concurrent single-item calls are grouped into physical batches of at most that size. See [Batching](../programming_guide/function#batching) for the attribute, and `Error::retry_with_smaller_batch` for a batch the backend rejects.+A batched function with <Lang only="python">`max_batch_size=N`</Lang><Lang only="rust">`max_batch_size = N`</Lang> receives up to `N` items at once; concurrent single-item calls are grouped into physical batches of at most that size. See [Batching](../programming_guide/function#batching) for the <Lang only="python">decorator options</Lang><Lang only="rust">attribute, and `Error::retry_with_smaller_batch` for a batch the backend rejects</Lang>.{/* Rust: rust/sdk/cocoindex_macros/src/lib.rs (function macro docs), rust/sdk/cocoindex/tests/batching_runner.rs */}<LangTabs>@@ -142,7 +160,9 @@ let embedding: Vec<f32> = embed(ctx, text).await?;### GPU runners-`runner = cocoindex::GPU` makes each call hold one whole GPU from the process-wide pool while its body runs, so bodies on one GPU run one at a time. `runner = cocoindex::GPURunner::fraction(0.5)` holds half a GPU, so two calls share one. With `batching`, each physical batch holds the share instead. Inside the body, `cocoindex::current_gpu()`, `current_gpus()` and `current_gpu_fraction()` report the assignment.+<Lang only="python">`runner=coco.GPU`</Lang><Lang only="rust">`runner = cocoindex::GPU`</Lang> makes each call hold one whole GPU from the process-wide pool while its body runs, so bodies on one GPU run one at a time. <Lang only="python">`runner=coco.GPU(fraction=0.5)`</Lang><Lang only="rust">`runner = cocoindex::GPURunner::fraction(0.5)`</Lang> holds half a GPU, so two calls share one. With batching, each physical batch holds the share instead. Inside the body, <Lang only="python">`coco.current_gpu()`, `coco.current_gpus()` and `coco.current_gpu_fraction()`</Lang><Lang only="rust">`cocoindex::current_gpu()`, `current_gpus()` and `current_gpu_fraction()`</Lang> report the assignment.++The pool size is detected from `COCOINDEX_NUM_GPUS`, then `CUDA_VISIBLE_DEVICES`, then `nvidia-smi`, and falls back to one. <Lang only="python">`coco.configure_gpu_pool(n)`</Lang><Lang only="rust">`configure_gpu_pool(n)`</Lang> overrides it; call it before any GPU function runs.{/* Rust: rust/sdk/cocoindex/tests/batching_runner.rs (whole_gpu, half_gpu, gpu_batch), rust/sdk/cocoindex/src/runner.rs */}<LangTabs>@@ -183,18 +203,24 @@ async fn gpu_batch(_ctx: &Ctx, items: Vec<i64>) -> Result<Vec<i64>> {configure_gpu_pool(NonZeroUsize::new(2).unwrap());```-The pool size is detected from `COCOINDEX_NUM_GPUS`, then `CUDA_VISIBLE_DEVICES`, then `nvidia-smi`, and falls back to one. `configure_gpu_pool(n)` overrides it; call it before any function with a runner runs.-</Fragment></LangTabs>+<Lang only="python">++Set `COCOINDEX_RUN_GPU_IN_SUBPROCESS=1` to run GPU functions in a subprocess for isolation.++</Lang>++<RustNote>Python's GPU subprocess mode (`COCOINDEX_RUN_GPU_IN_SUBPROCESS`) and its dedicated GPU thread exist for the GIL and CUDA's fork rules. A Rust body runs on the Tokio runtime and has neither problem, so the Rust SDK has no equivalent.+</RustNote>### Rate limiting outbound calls-`RateLimiter` is a token bucket for calls to an external service, for example a source or target connector that must stay under an API's rate limit. `acquire(n).await` waits until `n` tokens are available; concurrent callers are served in FIFO order. Clones share one bucket.+`RateLimiter` is a token bucket for calls to an external service, for example a source or target connector that must stay under an API's rate limit. `acquire(n)` waits until `n` tokens are available; concurrent callers are served in FIFO order. Clones share one bucket.-{/* Rust: rust/sdk/cocoindex/src/resources/rate_limit.rs */}+{/* Python: python/cocoindex/_internal/core.pyi (RateLimiter). Rust: rust/sdk/cocoindex/src/resources/rate_limit.rs */}<LangTabs><Fragment slot="python">@@ -212,7 +238,7 @@ await limiter.acquire(1)use std::time::Duration;use cocoindex::RateLimiter;-// 10 calls per second; a `burst_window` of one second matches the Python default.+// 10 calls per second, with up to one second of tokens saved up while idle.let limiter = RateLimiter::new(10.0, Duration::from_secs(1))?;limiter.acquire(1).await?;```diff --git a/docs/src/content/docs/advanced_topics/exception_handlers.mdx b/docs/src/content/docs/advanced_topics/exception_handlers.mdxindex 13c4aadf..5fae42fc 100644--- a/docs/src/content/docs/advanced_topics/exception_handlers.mdx+++ b/docs/src/content/docs/advanced_topics/exception_handlers.mdx@@ -4,6 +4,11 @@ description: >How CocoIndex isolates component failures, recovers from interrupted updatesvia two-phase processing, and lets you register exception handlers globallyvia lifespan or scoped via context manager to observe background errors.+rust_description: >+ How CocoIndex isolates component failures, recovers from interrupted updates+ via two-phase processing, and lets you register exception handlers globally+ on the environment builder or for one scope with ctx.with_exception_handler+ to observe background errors.---import LangTabs from '../../../components/LangTabs.astro';@@ -13,7 +18,9 @@ For a quick overview of failure isolation and the two-phase model, see [What hap## The guiding principle-**Whether a CocoIndex call raises on failure depends on what's on the critical path for the call to finish and return.** Things on that path that fail surface as exceptions; things off that path don't.+**Whether a CocoIndex call <Lang only="python">raises</Lang><Lang only="rust">returns an error</Lang> on failure depends on what's on the critical path for the call to finish and return.** Things on that path that fail surface as <Lang only="python">exceptions</Lang><Lang only="rust">errors</Lang>; things off that path don't.++<Lang only="python">| API | What it takes to return | Raises on failure? ||---|---|---|@@ -23,19 +30,57 @@ For a quick overview of failure isolation and the two-phase model, see [What hap| `await coco.use_mount(...)` | the inner component's *value* is produced | **Yes** β component success is on the critical path || `await app.drop()` (and `cocoindex drop`) | GC succeeds at *every* level | **Yes**, at any depth β leaking target state would otherwise go silent |-The Rust SDK follows the same table: `ctx.mount` / `mount!` schedule work and return a handle; `handle.ready().await` resolves `Ok` on an unhandled failure (the failure is logged); `LiveComponentOperator::update_full` does the same; `ctx.scope` / `use_mount!` return the child's error; `app.drop_state()` returns the error of a failed delete. One difference: Rust's `ctx.mount_each` is a foreground call that returns the children's values, so a failed item returns its error to the caller, as `scope` does.+</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/ctx.rs (Ctx::mount, mount_each, scope, use_mount_each), src/live_component.rs (LiveComponentOperator), src/app.rs (App::drop_state) */}++| API | What it takes to return | Returns an error on failure? |+|---|---|---|+| `ctx.mount` / `mount!`, `ctx.mount_each` / `mount_each!`, `LiveComponentOperator::start_update` / `start_delete` | the work is *scheduled* (returns a handle) | **No** β execution runs in the background |+| `handle.ready().await` (any of the above) | reaches *ready state* | **No by default** β logged at `ERROR`; opt into propagation by installing a handler that returns `Err` |+| `LiveComponentOperator::update_full`, `update`, `delete` | reaches *ready state* of the full cycle or the child | **No by default** β same shape as `handle.ready()` |+| `ctx.scope` / `use_mount!`, `ctx.use_mount_each` / `use_mount_each!` | the inner component's *value* is produced | **Yes** β component success is on the critical path |+| `app.drop_state().await` (and `cocoindex drop`) | GC succeeds at *every* level | **Yes**, at any depth β leaking target state would otherwise go silent |++</Lang>-**Why `ready`/`update_full` tolerate errors by default:** `handle.ready()` is usually not awaited (callers spawn many mounts in a loop and rely on the parent's `wait_for_children`), so raising into nobody would silently disappear. Logging the failure gives operators a signal regardless. The same applies to `update_full` β a periodic refresh that died on the first cycle failure would be worse than one that logs and retries on the next tick.+**Why `ready`/`update_full` tolerate errors by default:** `handle.ready()` is usually not awaited (callers spawn many mounts in a loop and rely on the parent waiting for its children), so <Lang only="python">raising into nobody</Lang><Lang only="rust">an error returned to nobody</Lang> would silently disappear. Logging the failure gives operators a signal regardless. The same applies to `update_full` β a periodic refresh that died on the first cycle failure would be worse than one that logs and retries on the next tick.++<Lang only="python">**Why `app.drop` raises at every level:** clearing tracking records is only safe if every component's delete actually ran its sink calls. If a descendant delete silently fails, `await app.drop()` would return Ok while target state is still live in your database β a leak. So failures at any depth surface as an exception.+</Lang>++<Lang only="rust">++**Why `app.drop_state` fails at every level:** clearing tracking records is only safe if every component's delete actually ran its sink calls. If a descendant delete silently fails, `app.drop_state()` would return `Ok` while target state is still live in your database β a leak. So failures at any depth surface as an error.++</Lang>+## How to opt into propagation+<Lang only="python">+Install an exception handler (described below). A handler that **returns normally** swallows; a handler that **raises** propagates through `handle.ready()` (or `update_full()`) up to your awaiting code. For `app.drop`, propagation is built in β you don't need to install anything.[Live components](./live_component) follow the same principle: their `update`/`delete`/`update_full` calls route failures through this chain with `mount_kind="process_live"`. The operator also exposes [`report_exception(exc)`](./live_component#report_exception) for surfacing errors raised in `process_live`'s body that aren't already routed by `update`/`delete`/`update_full`.-In Rust, a handler returns `Ok(())` to swallow a failure and `Err(_)` to propagate it. The Rust `LiveComponentOperator` has no `report_exception`: return the error from `process_live` instead.+</Lang>++<Lang only="rust">++Install an exception handler (described below). A handler that returns **`Ok(())`** swallows; a handler that returns **`Err(_)`** propagates through `handle.ready()` (or `update_full()`) up to your awaiting code. For `app.drop_state`, propagation is built in β you don't need to install anything.++[Live components](./live_component) follow the same principle: their `update_full`, `update` and `delete` calls route failures through this chain, with `mount_kind` set to `UpdateFull`, `Update` or `Delete`.++</Lang>++<RustNote>+The Rust `LiveComponentOperator` has no `report_exception`: return the error from `process_live` instead.+</RustNote>## Processing and submit phases@@ -48,19 +93,19 @@ This separation means a processing failure never leaves partial data in your tar## Interrupted updates and recovery-An update can be interrupted by various events: a process kill (SIGKILL), Ctrl+C (SIGINT), an unhandled exception, or a target backend failure during submit.+An update can be interrupted by various events: a process kill (SIGKILL), Ctrl+C (SIGINT), an unhandled <Lang only="python">exception</Lang><Lang only="rust">error</Lang>, or a target backend failure during submit.**What state is left behind?**CocoIndex's internal database (LMDB) uses transactions, so its own state is always consistent even after a crash. CocoIndex tracks all possible states a target could be in β if an update is interrupted partway through a commit, both the old and new states are retained as possibilities. This ensures no state is ever lost.-**Recovery is automatic.** On the next `app.update()`, CocoIndex computes the current desired state and reconciles against all possible previous states. The target connector converges the target to the correct state regardless of whether the previous commit partially succeeded or never ran.+**Recovery is automatic.** On the next app update, CocoIndex computes the current desired state and reconciles against all possible previous states. The target connector converges the target to the correct state regardless of whether the previous commit partially succeeded or never ran.For details on how target handlers deal with multiple possible previous states after an interruption, see [Custom Target Connector β Handle multiple previous states](./custom_target_connector#handle-multiple-previous-states).## Monitoring errors-`app.update()` returns an `UpdateHandle` that exposes processing stats, including error counts:+<Lang only="python">`app.update()`</Lang><Lang only="rust">`app.start_update(...)`</Lang> returns an `UpdateHandle` that exposes processing stats, including error counts:{/* Rust: rust/sdk/cocoindex/tests/detailed_stats.rs, rust/sdk/cocoindex/src/app.rs (UpdateHandle), src/stats.rs */}<LangTabs>@@ -109,6 +154,8 @@ See [Progress monitoring](./progress_monitoring) for the full `UpdateHandle` API## Exception handlers+<Lang only="python">+For background-mounted components (`mount()` and `mount_each()`), you can register **exception handlers** to observe or react to failures β for example, to send alerts, record metrics, or implement custom logic.CocoIndex supports two levels of exception handlers:@@ -116,15 +163,32 @@ CocoIndex supports two levels of exception handlers:- **Global (environment-level)**: registered once in your lifespan function; applies to all background mounts in the environment.- **Scoped**: an async context manager that applies to all `mount()` / `mount_each()` calls made within it.-In the Rust SDK the global handler is `EnvironmentBuilder::exception_handler`, and a scoped handler is `ctx.with_exception_handler(handler)`, which returns a scoped `Ctx`. A handler is `Fn(&Error, &ExceptionContext) -> Result<()>`: return `Ok(())` to swallow the failure, `Err(_)` to propagate it.-:::noteException handlers only apply to `mount()` and `mount_each()`. `use_mount()` propagates errors directly to the caller since the parent has an explicit dependency on the result.:::+</Lang>++<Lang only="rust">++For background-mounted components (`ctx.mount` / `mount!`, `ctx.mount_each` / `mount_each!`, live components and `ctx.auto_refresh`), you can register **exception handlers** to observe or react to failures β for example, to send alerts, record metrics, or implement custom logic.++CocoIndex supports two levels of exception handlers:++- **Global (environment-level)**: registered once with `EnvironmentBuilder::exception_handler`, usually in your lifespan function; applies to all background mounts in the environment.+- **Scoped**: `ctx.with_exception_handler(handler)` returns a scoped `Ctx`; the handler applies to the background mounts made from that `Ctx`. `ctx.mount_live_with_handler` attaches a handler to one live component.++A handler is `Fn(&Error, &ExceptionContext) -> Result<()>`: return `Ok(())` to swallow the failure, `Err(_)` to propagate it.++:::note+Exception handlers only apply to background mounts. `ctx.scope` / `use_mount!` and `use_mount_each!` return the child's error directly to the caller, since the parent has an explicit dependency on the result.+:::++</Lang>+### Global exception handler-Register a handler inside your `@coco.lifespan` function using `builder.set_exception_handler()`:+Register a handler inside your <Lang only="python">`@coco.lifespan` function using `builder.set_exception_handler()`</Lang><Lang only="rust">`#[cocoindex::lifespan]` function using `builder.exception_handler(...)`</Lang>:{/* Rust: rust/sdk/cocoindex/tests/mount.rs (temp_app_with_handler), rust/sdk/cocoindex/src/app.rs (EnvironmentBuilder::exception_handler) */}<LangTabs>@@ -164,7 +228,7 @@ This replaces the default "log error" behavior for all background mounts in the### Scoped exception handler-Use `coco.exception_handler()` as an async context manager to apply a handler to a specific dynamic scope:+<Lang only="python">Use `coco.exception_handler()` as an async context manager to apply a handler to a specific dynamic scope:</Lang><Lang only="rust">Use `ctx.with_exception_handler(handler)` to get a `Ctx` whose background mounts go through the handler first:</Lang>{/* Rust: rust/sdk/cocoindex/tests/mount.rs (scoped_handler_applies_only_to_mounts_from_the_scoped_ctx) */}<LangTabs>@@ -206,14 +270,28 @@ Only mounts made from `scoped` see the handler. A mount made from the unscoped `</Fragment></LangTabs>+<Lang only="python">+The handler applies to all `mount()` / `mount_each()` calls within the `async with` block, including those in nested functions called from within the block, and to every item of a `mount_each()` whether it iterates a collection or a [`LiveMapView` / `LiveMapFeed`](./live_component#livemapfeed-and-livemapview).It does not reach the mounts those components make themselves: a component's own `mount()` / `mount_each()` calls start from the global handler, plus any handler the component scopes itself. To observe the failures of components at any depth, register a global handler.-The Rust SDK differs here on purpose. A child component's `Ctx` inherits the handler chain of the `Ctx` it was mounted from, so a handler installed with `ctx.with_exception_handler` also sees the failures of the mounts that child makes itself, at any depth. The global handler is the outermost entry of every chain.+</Lang>++<Lang only="rust">++The handler applies to every background mount made from the scoped `Ctx` (or a `Ctx` derived from it, for example with `with_subpath`), including every item of a `mount_each` and every child of a live component mounted from it.++</Lang>++<RustNote>+A child component's `Ctx` inherits the handler chain of the `Ctx` it was mounted from, so a handler installed with `ctx.with_exception_handler` also sees the failures of the mounts that child makes itself, at any depth. In Python, a scoped handler does not reach the mounts those components make themselves. The global handler is the outermost entry of every chain.+</RustNote>### Handler type+<Lang only="python">+Both sync and async handlers are supported:```python@@ -228,6 +306,8 @@ async def async_handler(exc: BaseException, ctx: coco.ExceptionContext) -> None:await send_alert(exc, ctx)```+</Lang>+The type alias is:{/* Rust: rust/sdk/cocoindex/src/live_component.rs (ExceptionHandler) */}@@ -249,11 +329,17 @@ pub type ExceptionHandler =Arc<dyn Fn(&Error, &ExceptionContext) -> Result<()> + Send + Sync + 'static>;```-`EnvironmentBuilder::exception_handler` and `ctx.with_exception_handler` accept any closure with that signature and wrap it. Rust handlers are synchronous closures.+`EnvironmentBuilder::exception_handler`, `ctx.with_exception_handler` and `ctx.mount_live_with_handler` accept any closure with that signature and wrap it.</Fragment></LangTabs>+<RustNote>+Rust handlers are synchronous closures; Python also accepts async handlers.+</RustNote>++<Lang only="python">+### What `exc` isHandlers receive the same exception object that a foreground call such as `await coco.use_mount(...)` would raise for the same failure:@@ -265,6 +351,16 @@ An exception raised by a handler keeps its type as well: `await handle.ready()`Earlier releases handed every component failure to handlers as a `RuntimeError` whose message embedded the formatted traceback, and re-wrapped handler-raised exceptions the same way. A handler that checked `isinstance(exc, RuntimeError)` or parsed `str(exc)` for the traceback should switch to the checks above.+</Lang>++<Lang only="rust">++### What `err` is++Handlers receive the same `Error` that a foreground call such as `ctx.scope(...)` would return for the same failure. A failure your own code returned with `Error::user(..)` arrives as `Error::User(inner)`; `inner.downcast_ref::<T>()` recovers its type. `Error::DeadlineExceeded` is the cooperative deadline. An error a handler returns keeps its value as well: `handle.ready()` returns exactly what the last handler in the chain returned.++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/mount.rs (handler_error_propagates_through_ready_with_its_type) */}<LangTabs><Fragment slot="python">@@ -307,13 +403,13 @@ if let Err(e) = handle.ready().await {}```-A Rust handler receives `&Error`. A failure your own code returned with `Error::user(..)` arrives as `Error::User(inner)`; `inner.downcast_ref::<T>()` recovers its type. `Error::DeadlineExceeded` is the cooperative deadline.-</Fragment></LangTabs>### `ExceptionContext` fields+<Lang only="python">+Your handler receives an `ExceptionContext` dataclass with information about the failure:| Field | Type | Description |@@ -327,27 +423,47 @@ Your handler receives an `ExceptionContext` dataclass with information about the| `source` | `"component" \| "handler"` | `"component"` for the original failure; `"handler"` if a handler itself raised || `original_exception` | `BaseException \| None` | The original component exception, set only when `source == "handler"` |-The Rust `ExceptionContext` is a struct with the fields the Rust SDK can fill:+</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/live_component.rs (ExceptionContext, MountKind, ExceptionSource) */}-| Field | Rust type | Notes |+Your handler receives an `ExceptionContext` struct with information about the failure:++| Field | Type | Notes ||---|---|---|| `env_name` | `String` | Name of the app the failing component runs under || `stable_path` | `String` | Stable path of the failing component || `parent_stable_path` | `Option<String>` | Set for a child mount or delete || `processor_name` | `Option<String>` | Name of the processor that failed, if known |-| `mount_kind` | `MountKind` | `Mount` (`ctx.mount` / `mount!`), `UpdateFull`, `Update` or `Delete` (the live component operator) |-| `is_background` | `bool` | `true` for background work |+| `mount_kind` | `MountKind` | `Mount` (`ctx.mount` / `mount!`, `ctx.mount_each` / `mount_each!`), `UpdateFull` (a live component's full pass, or an `auto_refresh` cycle), `Update` or `Delete` (the live component operator) |+| `is_background` | `bool` | `true` for a background mount; for a live component, `true` once it is ready and running in live mode || `source` | `ExceptionSource` | `Component` for the component's own error; `Handler` for an error a nearer handler returned |+</Lang>++<RustNote>There is no `original_exception` field in Rust. The error a handler returns replaces the component's error for the next handler.+</RustNote>### Handler stacking and fallbackHandlers are stacked: the most specific (innermost) handler runs first.+<Lang only="python">+If the innermost handler raises an exception, the next outer handler is called with that new exception. In this case `ctx.source` is `"handler"` and `ctx.original_exception` holds the original component error.-This continues up the stack. If every handler raises, the last handler's exception propagates through `handle.ready()` (see [How to opt into propagation](#how-to-opt-into-propagation)). If no handler is registered, CocoIndex falls back to the built-in behavior: logging the error at `ERROR` level, with no crash.+</Lang>++<Lang only="rust">++If the innermost handler returns `Err`, the next outer handler is called with that new error. In this case `exc.source` is `ExceptionSource::Handler`.++</Lang>++This continues up the stack. If every handler <Lang only="python">raises, the last handler's exception</Lang><Lang only="rust">returns `Err`, the last handler's error</Lang> propagates through `handle.ready()` (see [How to opt into propagation](#how-to-opt-into-propagation)). If no handler is registered, CocoIndex falls back to the built-in behavior: logging the error at `ERROR` level, with no crash.{/* Rust: rust/sdk/cocoindex/tests/mount.rs (scoped handler then global handler with source == Handler) */}<LangTabs>@@ -411,4 +527,4 @@ app.update(|ctx| async move {</Fragment></LangTabs>-Users who never register handlers see identical behavior to the default β exceptions from background mounts are logged at `ERROR` level and siblings continue unaffected.+Users who never register handlers see identical behavior to the default β <Lang only="python">exceptions</Lang><Lang only="rust">errors</Lang> from background mounts are logged at `ERROR` level and siblings continue unaffected.diff --git a/docs/src/content/docs/advanced_topics/index.mdx b/docs/src/content/docs/advanced_topics/index.mdxindex c7cb3745..6d96bc11 100644--- a/docs/src/content/docs/advanced_topics/index.mdx+++ b/docs/src/content/docs/advanced_topics/index.mdx@@ -8,6 +8,22 @@ description: >import DocCardGrid from '@cocoindex/brand/DocCardGrid.astro';import { advancedTopicsGroups } from '/src/data/section-grids';-You can build complete pipelines with the [programming guide](/docs/programming_guide/core_concepts/) alone. Reach for these pages when you want to go a level deeper into how the engine behaves, and extend it past what it ships with.+{/* The card hrefs in section-grids.ts are root-relative Python URLs; the Rust copy points them at /docs/rust/. */}+export const rustAdvancedTopicsGroups = advancedTopicsGroups.map((g) => ({+ ...g,+ cards: g.cards.map((c) => ({ ...c, href: c.href.replace(/^\/docs\//, '/docs/rust/') })),+}));++You can build complete pipelines with the [programming guide](../programming_guide/core_concepts) alone. Reach for these pages when you want to go a level deeper into how the engine behaves, and extend it past what it ships with.++<Lang only="python"><DocCardGrid groups={advancedTopicsGroups} ariaLabel="Advanced topics" />++</Lang>++<Lang only="rust">++<DocCardGrid groups={rustAdvancedTopicsGroups} ariaLabel="Advanced topics" />++</Lang>diff --git a/docs/src/content/docs/advanced_topics/internal_storage.mdx b/docs/src/content/docs/advanced_topics/internal_storage.mdxindex 3abc4c52..9692ceb1 100644--- a/docs/src/content/docs/advanced_topics/internal_storage.mdx+++ b/docs/src/content/docs/advanced_topics/internal_storage.mdx@@ -44,7 +44,7 @@ async fn lifespan(builder: EnvironmentBuilder) -> Result<EnvironmentBuilder> {</Fragment></LangTabs>-Or pass it directly when creating a [`Settings`](./multiple_environments) object:+<Lang only="python">Or pass it directly when creating a [`Settings`](./multiple_environments) object:</Lang><Lang only="rust">Or set it on the builder when you create an [`Environment`](./multiple_environments) or an `App` directly:</Lang>{/* Rust: rust/sdk/cocoindex/src/app.rs (Environment::builder, App::builder) */}<LangTabs>@@ -66,9 +66,21 @@ let app = App::builder("MyApp").db_path("./cocoindex.db").build().await?;</Fragment></LangTabs>+<Lang only="python">+Setting `db_path` in the lifespan or `Settings` takes precedence over the `COCOINDEX_DB` environment variable. If neither is provided, CocoIndex will raise an error.-In the Rust SDK only `Environment::from_registered()` reads `COCOINDEX_DB`: it runs every `#[cocoindex::lifespan]` and uses the variable when no lifespan set a `db_path`; with neither, it returns an error. That is the path the `cocoindex` CLI takes. A plain `Environment::builder().build()` reads no environment variables and defaults `db_path` to `./coco_state`.+</Lang>++<Lang only="rust">++Setting `db_path` in a lifespan takes precedence over the `COCOINDEX_DB` environment variable. `Environment::from_registered()` runs every `#[cocoindex::lifespan]` and uses the variable when no lifespan set a `db_path`; if neither is provided, it returns an error. That is the path the `cocoindex` CLI takes.++</Lang>++<RustNote>+Only `Environment::from_registered()` reads `COCOINDEX_DB`. A plain `Environment::builder().build()` or `App::builder(name).build()` reads no environment variables and defaults `db_path` to `./coco_state`.+</RustNote>## Opening and closing the database@@ -76,22 +88,32 @@ Opening a `db_path` opens its LMDB environment, and LMDB allows one environment## LMDB tuning-The LMDB database has two tunable settings, grouped under `coco.LmdbSettings` and attached to `Settings` as `db_settings`. The defaults work well for most use cases β you only need to adjust them for large-scale deployments. The Rust builder exposes them as `lmdb_max_dbs(..)` and `lmdb_map_size(..)`, with the same defaults; `Environment::from_registered()` reads the two environment variables when a lifespan did not set them.+<Lang only="python">++The LMDB database has two tunable settings, grouped under `coco.LmdbSettings` and attached to `Settings` as `db_settings`. The defaults work well for most use cases β you only need to adjust them for large-scale deployments.++</Lang>++<Lang only="rust">++The LMDB database has two tunable settings, set with the builder's `lmdb_max_dbs(..)` and `lmdb_map_size(..)`. The defaults work well for most use cases β you only need to adjust them for large-scale deployments. `Environment::from_registered()` reads the two environment variables when a lifespan did not set them.++</Lang>| Setting | Default | Env Variable | Description ||---------|---------|-------------|-------------|-| `max_dbs` | `1024` | `COCOINDEX_LMDB_MAX_DBS` | Maximum number of apps (named LMDB sub-databases) sharing one `db_path`. Unlike `map_size`, this **is** a hard cap β creating one app beyond it fails. Applied at open time, so raising it takes effect on the next start. Must be ≥ 1. |-| `map_size` | `4294967296` (4 GiB) | `COCOINDEX_LMDB_MAP_SIZE` | *Initial* size of the LMDB memory map in bytes. CocoIndex enlarges the map automatically as the state grows, so this is a starting point, not a cap. Must be > 0; rounded up to the nearest multiple of the system page size. |+| <Lang only="python">`max_dbs`</Lang><Lang only="rust">`lmdb_max_dbs`</Lang> | `1024` | `COCOINDEX_LMDB_MAX_DBS` | Maximum number of apps (named LMDB sub-databases) sharing one `db_path`. Unlike the map size, this **is** a hard cap β creating one app beyond it fails. Applied at open time, so raising it takes effect on the next start. Must be ≥ 1. |+| <Lang only="python">`map_size`</Lang><Lang only="rust">`lmdb_map_size`</Lang> | `4294967296` (4 GiB) | `COCOINDEX_LMDB_MAP_SIZE` | *Initial* size of the LMDB memory map in bytes. CocoIndex enlarges the map automatically as the state grows, so this is a starting point, not a cap. Must be > 0; rounded up to the nearest multiple of the system page size. |### When to adjust-- **`map_size`** β most deployments never need to touch it. The map grows on its own and each step is cheap, so it is worth setting only when that growth actually costs you something: a large state re-climbing from 4 GiB on every restart, or resize pauses you can measure. If you do size it up, every enlargement logs `LMDB map full, auto-resizing to N bytes and retrying` β the largest `N` you see is the number to use. On 64-bit systems, `map_size` is a virtual address space reservation, so setting it larger than needed is safe and consumes neither physical memory nor disk.-- **`max_dbs`** β raise it if you have an unusually large number of apps sharing a single database directory.+- **<Lang only="python">`map_size`</Lang><Lang only="rust">`lmdb_map_size`</Lang>** β most deployments never need to touch it. The map grows on its own and each step is cheap, so it is worth setting only when that growth actually costs you something: a large state re-climbing from 4 GiB on every restart, or resize pauses you can measure. If you do size it up, every enlargement logs `LMDB map full, auto-resizing to N bytes and retrying` β the largest `N` you see is the number to use. On 64-bit systems, the map size is a virtual address space reservation, so setting it larger than needed is safe and consumes neither physical memory nor disk.+- **<Lang only="python">`max_dbs`</Lang><Lang only="rust">`lmdb_max_dbs`</Lang>** β raise it if you have an unusually large number of apps sharing a single database directory.:::note[How the map grows]When a write runs out of map space, CocoIndex doubles the map and retries, repeating until the write fits. The remap itself is cheap (no data copy, no file rewrite) but it needs exclusivity: it waits for every LMDB transaction open in the process to finish, and queues new ones behind it. That's imperceptible for ordinary reads and writes, but a long streaming read (`cocoindex show` over a large app) holds its transaction for the whole stream, and the resize waits that long.-The enlarged size doesn't carry over. The next process opens at the configured `map_size`, raised to at least the space the data file already occupies β the file's high-water mark, not the live data, since LMDB reuses freed pages but never shrinks the file. So a database that outgrew its `map_size` still opens and reads fine, just with no headroom: the next write needing new space enlarges it again. A map that grew to 16 GiB over a 10 GiB file reopens at 10 GiB, not 16, then doubles to 20 GiB on the next write that needs space.+The enlarged size doesn't carry over. The next process opens at the configured map size, raised to at least the space the data file already occupies β the file's high-water mark, not the live data, since LMDB reuses freed pages but never shrinks the file. So a database that outgrew its configured map size still opens and reads fine, just with no headroom: the next write needing new space enlarges it again. A map that grew to 16 GiB over a 10 GiB file reopens at 10 GiB, not 16, then doubles to 20 GiB on the next write that needs space.::::::note[What typically grows the store]@@ -138,11 +160,13 @@ async fn lifespan(builder: EnvironmentBuilder) -> Result<EnvironmentBuilder> {}```-The same setters exist on `App::builder(name)`.+The same setters exist on `App::builder(name)` and `Environment::builder()`.</Fragment></LangTabs>+<Lang only="python">+Or when creating a `Settings` object directly:```python@@ -161,9 +185,13 @@ When using `Settings.from_env()`, the LMDB settings are automatically loaded froFor backward compatibility, `Settings` still accepts `lmdb_max_dbs` and `lmdb_map_size` as keyword arguments, and exposes them as attributes (e.g., `settings.lmdb_map_size = ...`). These read and write the same underlying values as `settings.db_settings.max_dbs` / `settings.db_settings.map_size`. Passing both `db_settings=` and the legacy keywords in the same `Settings(...)` call raises `ValueError`.:::+</Lang>+## Inspecting the database-The [`cocoindex ls` and `cocoindex show`](../cli#ls) commands read the database directly when you pass `--db` (and `--app-name` for `show`), without loading your app:+The <Lang only="python">[`cocoindex ls` and `cocoindex show`](../cli#ls)</Lang><Lang only="rust">[`cocoindex ls` and `cocoindex show`](/docs/rust/cli/#ls)</Lang> commands read the database directly when you pass `--db` (and `--app-name` for `show`), without loading your app:++<Lang only="python">```bashcocoindex ls --db ./cocoindex.db@@ -172,21 +200,64 @@ cocoindex show --db ./cocoindex.db --app-name MyApp --target-statesThe database format does not depend on the SDK that wrote it. The Python CLI lists and shows a database written by an app built with the Rust SDK, and prints the same output as the Rust SDK's own `cocoindex` CLI.-The Rust `cocoindex` CLI reads a database the same way, with the same flags:+</Lang>++<Lang only="rust">```bashcocoindex ls --db ./cocoindex.dbcocoindex show --db ./cocoindex.db --app-name MyApp+cocoindex show --db ./cocoindex.db --app-name MyApp --target-statescocoindex show --db ./cocoindex.db --app-name MyApp '/"a.md"'```Without `--db`, `ls` uses `COCOINDEX_DB`. With an app target instead of `--db` and `--app-name`, the CLI builds the crate and asks the app for its database.-### Inspecting from Rust code+The database format does not depend on the SDK that wrote it. The [Python CLI](/docs/cli/) lists and shows a database written by a Rust app, and prints the same output.++</Lang>++### Inspecting from code++<Lang only="python">++`cocoindex.inspect` reads the same data from a program: an app's stable paths, the details of each one, and the target states it tracks. Every function takes an `App`; its `_by_name` form takes an `Environment` and an app name, for an app whose pipeline the program does not hold. The functions only read.++</Lang>++<Lang only="rust">`cocoindex::inspect` reads the same data from a program: an app's stable paths, the details of each one, and the target states it tracks. Every function takes an `App`; its `_by_name` form takes an `Environment` and an app name, for an app whose pipeline the binary does not hold. The functions only read.-{/* Rust: rust/sdk/cocoindex/src/inspect.rs (module docs), rust/sdk/cocoindex/tests/inspect.rs */}+</Lang>++{/* Python: python/cocoindex/_internal/inspect_api.py, python/cocoindex/_internal/core.pyi (TargetStateEntry). Rust: rust/sdk/cocoindex/src/inspect.rs (module docs), rust/sdk/cocoindex/tests/inspect.rs */}+<LangTabs>+<Fragment slot="python">++```python+import cocoindex as coco+from cocoindex import inspect as coco_inspect++for path in await coco_inspect.list_stable_paths(app):+ print(path)++# Target states with the component that owns each.+async for entry in coco_inspect.iter_target_states(app):+ print(entry.readable_path, "owner:", entry.owner_component_path)++# One path, with the paths directly under it.+details = await coco_inspect.query_stable_path_details(+ app, coco.ROOT_PATH, include_children=True+)++# Without the `App`: an environment and the app's name.+one = await coco_inspect.get_stable_path_detail_by_name(env, "MyApp", coco.ROOT_PATH)+```++</Fragment>+<Fragment slot="rust">+```rustuse cocoindex::inspect::{self, StablePath, StablePathQuery};use futures::TryStreamExt;@@ -209,4 +280,7 @@ let details = inspect::query_stable_path_details(&app, &StablePath::root(), querlet one = inspect::get_stable_path_detail_by_name(&env, "MyApp", &StablePath::root()).await?;```+</Fragment>+</LangTabs>+A streaming read holds its LMDB transaction for the whole stream, so a map resize waits for it to finish (see [How the map grows](#lmdb-tuning)).diff --git a/docs/src/content/docs/advanced_topics/live_component.mdx b/docs/src/content/docs/advanced_topics/live_component.mdxindex 2fa22ca6..a0eb7ad8 100644--- a/docs/src/content/docs/advanced_topics/live_component.mdx+++ b/docs/src/content/docs/advanced_topics/live_component.mdx@@ -5,17 +5,34 @@ description: >process_live(operator) for incremental updates β covers LiveComponentOperator(update_full, update, delete, mark_ready) and LiveMapFeed / LiveMapViewabstractions over event sources.+rust_description: >+ Implement the LiveComponent trait with process() for full scans and+ process_live(operator) for incremental updates β covers LiveComponentOperator+ (update_full, update, delete, mark_ready), the LiveMapFeed / LiveMapView /+ LiveStream traits over event sources, and the in-process LiveMap.---import LangTabs from '../../../components/LangTabs.astro';-By default, a [processing component](../programming_guide/processing_component) runs in **catch-up mode** β on each `app.update()`, it declares all target states and mounts all sub-components from scratch. CocoIndex handles incremental updates by skipping [memoized](../programming_guide/function) sub-components and reconciling target states at the end, then the component exits. This works well when the dataset is small enough to scan fully each cycle.+By default, a [processing component](../programming_guide/processing_component) runs in **catch-up mode** β on each app update, it declares all target states and mounts all sub-components from scratch. CocoIndex handles incremental updates by skipping [memoized](../programming_guide/function) sub-components and reconciling target states at the end, then the component exits. This works well when the dataset is small enough to scan fully each cycle.When the dataset is large or you need to react to changes continuously (e.g., watching a file system), you want the component itself to stay running and react incrementally. A **live component** does an initial full scan (same as catch-up mode), then keeps running and reacts to individual changes without rescanning everything.+<Lang only="python">+## The LiveComponent protocolA live component is a class with three methods:+</Lang>++<Lang only="rust">++## The LiveComponent trait++A live component is a type that implements the `LiveComponent` trait, with two methods:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/live_component.rs (LiveComponent trait), rust/sdk/cocoindex/tests/live_map.rs (Producer) */}<LangTabs><Fragment slot="python">@@ -65,19 +82,33 @@ impl LiveComponent for MyLiveComponent {}```-In Rust a live component is a type that implements the `LiveComponent` trait. Its fields take the place of `__init__`: you build the value and pass it to `ctx.mount_live(&key, component)`. `process` receives the component's `Ctx`. `process_live` has a default body: one full pass, then `mark_ready`.-</Fragment></LangTabs>+<Lang only="python">+- **`__init__`** receives arguments passed to `coco.mount()`.- **`process()`** does a full scan β mounts children via `coco.mount()` and declares target states, just like a traditional component function. Called indirectly via `operator.update_full()`.- **`process_live(operator)`** is the long-running entry point. It orchestrates full and incremental updates using the operator.-CocoIndex detects a live component by checking if the class has both `process` and `process_live` methods. In Rust the trait is the marker, and `ctx.mount_live` is the mount call.+CocoIndex detects a live component by checking if the class has both `process` and `process_live` methods.++</Lang>++<Lang only="rust">++- **The fields** hold the component's arguments: you build the value and pass it to `ctx.mount_live(&key, component)`.+- **`process(ctx)`** does a full scan β mounts children via `ctx.mount` / `ctx.mount_each` and declares target states, just like a traditional component function. Called indirectly via `operator.update_full()`.+- **`process_live(operator)`** is the long-running entry point. It orchestrates full and incremental updates using the operator. Its default body runs one full pass, then `mark_ready`.++The trait is the marker, and `ctx.mount_live` is the mount call.++</Lang>## LiveComponentOperator+<Lang only="python">+The `operator` passed to `process_live()` provides five methods:| Method | Description |@@ -88,35 +119,49 @@ The `operator` passed to `process_live()` provides five methods:| `await operator.mark_ready()` | Signal that processing has caught up to the time `process_live()` was called. || `await operator.report_exception(exc)` | Surface a `process_live`-body exception through the parent's exception handler chain. |-The Rust `LiveComponentOperator` has the same methods, with the child's body as a closure:+</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/live_component.rs (LiveComponentOperator) */}++The `operator` passed to `process_live()` provides these methods, with the child's body as a closure:-| Rust method | Description |+| Method | Description ||--------|-------------|-| `operator.update_full().await?` | Run `process()` with a full submission phase. |+| `operator.update_full().await?` | Run `process()` with a full submission phase (GCs removed children). Blocks until fully ready. || `operator.update(key, \|ctx\| async move { .. }).await?` | Mount a child component under `key` incrementally. Awaits until its state has synced. |-| `operator.delete(key).await?` | Delete a child component. |-| `operator.mark_ready().await` | Signal that processing has caught up. |+| `operator.start_update(key, \|ctx\| ..).await?` | The same without waiting: returns a `ReadyHandle` whose `ready()` awaits the sync. |+| `operator.delete(key).await?` / `start_delete(key)` | Delete a child component, waiting for the sync or returning a `ReadyHandle`. |+| `operator.mark_ready().await` | Signal that processing has caught up to the time `process_live()` was called. || `operator.is_live()` | Whether the update runs in live mode. |+| `operator.read_committed_state(key)` / `write_committed_state(key, &value)` | A durable value of the component's own, such as a cursor, kept across runs. |++</Lang>-There is no `report_exception` in Rust. Return the error from `process_live` instead: before `mark_ready`, the mount fails with it; after `mark_ready`, it is logged. The operator also has `read_committed_state` and `write_committed_state` for a durable cursor of the component's own.+<RustNote>+There is no `report_exception` in Rust. Return the error from `process_live` instead: before `mark_ready`, the mount fails with it; after `mark_ready`, it is logged.+</RustNote>### `update_full()`Triggers a full processing cycle: calls `process()`, submits target states, waits for all children to be ready, and garbage-collects children that are no longer mounted. This is the same mechanism as a traditional component's update cycle.-Exceptions raised inside `process()` (including a failed `use_mount` child's, which surfaces there) are routed through the parent's [exception handler chain](./exception_handlers#exception-handlers) β same as background `coco.mount()` failures β and **do not propagate** to the caller. Components that `process()` mounts in the background report their own failures through the chain in effect where they are mounted, as any `coco.mount()` does. This lets long-running `process_live` loops (such as periodic refreshers) keep going across transient cycle failures while still surfacing the failure to operators.+<Lang only="python">Exceptions raised inside `process()` (including a failed `use_mount` child's, which surfaces there)</Lang><Lang only="rust">Errors returned from `process()`</Lang> are routed through the parent's [exception handler chain](./exception_handlers#exception-handlers) β same as background <Lang only="python">`coco.mount()`</Lang><Lang only="rust">`ctx.mount`</Lang> failures β and **do not propagate** to the caller. Components that `process()` mounts in the background report their own failures through the chain in effect where they are mounted, as any background mount does. This lets long-running `process_live` loops (such as periodic refreshers) keep going across transient cycle failures while still surfacing the failure to operators.### `update()` and `delete()`Mount or delete individual child components without a full scan. These are concurrent with each other but serialized with `update_full()` β if `update_full()` is running, incremental operations wait until it finishes.-When multiple operations target the same subpath, only the latest one (by invocation order) takes effect.+When multiple operations target the same <Lang only="python">subpath</Lang><Lang only="rust">key</Lang>, only the latest one (by invocation order) takes effect.-Failures in the mounted child (or in the delete itself) are routed through the parent's [exception handler chain](./exception_handlers#exception-handlers) with `mount_kind="process_live"` and `stable_path` set to the *child's* path β same shape as background `coco.mount` failures, never propagated to `handle.ready()`. The live loop is unaffected by child failures.+Failures in the mounted child (or in the delete itself) are routed through the parent's [exception handler chain](./exception_handlers#exception-handlers) with <Lang only="python">`mount_kind="process_live"`</Lang><Lang only="rust">`mount_kind` set to `MountKind::Update` or `MountKind::Delete`</Lang> and `stable_path` set to the *child's* path β same shape as background <Lang only="python">`coco.mount`</Lang><Lang only="rust">`ctx.mount`</Lang> failures<Lang only="python">, never propagated to `handle.ready()`</Lang>. The live loop is unaffected by child failures.### `mark_ready()`-Signals to the parent that the live component has caught up. The parent's `await handle.ready()` returns when `mark_ready()` is called. If `process_live()` returns without calling `mark_ready()`, it is called automatically.+Signals to the parent that the live component has caught up. The parent's <Lang only="python">`await handle.ready()`</Lang><Lang only="rust">`ctx.mount_live(...)` call</Lang> returns when `mark_ready()` is called. If `process_live()` returns without calling `mark_ready()`, it is called automatically.++<Lang only="python">### `report_exception()`@@ -139,7 +184,15 @@ The handler receives an `ExceptionContext` with `mount_kind="process_live"` andYou **don't** need `report_exception` around `update_full` / `update` / `delete` themselves β those route their own errors automatically.-In Rust, `update_full`, `update` and `delete` route their failures the same way, with `mount_kind` set to `MountKind::UpdateFull`, `MountKind::Update` or `MountKind::Delete`. Register a handler with `ctx.mount_live_with_handler(&key, component, handler)` for one component, or on the environment builder for all of them (see [Exception handlers](./exception_handlers#exception-handlers)).+</Lang>++<Lang only="rust">++### Handling failures++`update_full`, `update` and `delete` route their failures through the handler chain, with `mount_kind` set to `MountKind::UpdateFull`, `MountKind::Update` or `MountKind::Delete`. Register a handler with `ctx.mount_live_with_handler(&key, component, handler)` for one component, with `ctx.with_exception_handler` for the mounts of one scope, or on the environment builder for all of them (see [Exception handlers](./exception_handlers#exception-handlers)).++</Lang>## Example: file system watcher@@ -226,7 +279,7 @@ impl LiveComponent for FolderWatcher {}```-For a real directory, the Rust SDK ships the watcher: `walk_dir(dir).live()` returns a `LiveMapView`, and `ctx.mount_each_live` mounts one child per file (see `examples/rust/text_embedding`). Write a `LiveComponent` by hand when the change source is your own.+For a real directory, `cocoindex` ships the watcher: `walk_dir(dir).live()` returns a `LiveMapView`, and `ctx.mount_each_live` mounts one child per file (see `examples/rust/text_embedding`). Write a `LiveComponent` by hand when the change source is your own.</Fragment></LangTabs>@@ -265,6 +318,10 @@ app.update(move |ctx| async move {A traditional single-function component:+{/* Rust: the body of rust/sdk/cocoindex/tests/live_component.rs (Declarer::process), inside an app.update root as in that file's tests */}+<LangTabs>+<Fragment slot="python">+```python@coco.fnasync def process_all(data) -> None:@@ -272,6 +329,22 @@ async def process_all(data) -> None:coco.declare_target_state(target.target_state(key, value))```+</Fragment>+<Fragment slot="rust">++```rust+app.update(move |ctx| async move {+ for (k, v) in rows {+ declare_target_state(&ctx, provider.target_state(k, v.to_string()))?;+ }+ Ok(())+})+.await?;+```++</Fragment>+</LangTabs>+is equivalent to this LiveComponent:{/* Rust: rust/sdk/cocoindex/tests/live_component.rs (Declarer) */}@@ -318,10 +391,25 @@ impl LiveComponent for ProcessAll {The key difference: the LiveComponent version can later be extended to handle incremental changes in `process_live()` without changing `process()`.+<Lang only="python">+## Example: periodic refresh with `coco.auto_refresh`A common pattern is "run a regular processor on a fixed schedule." `coco.auto_refresh` wraps any processor function as a LiveComponent that re-runs it on an interval β no need to write `process_live` yourself.+</Lang>++<Lang only="rust">++## Example: periodic refresh with `ctx.auto_refresh`++{/* Keeps the anchor that the Rust copy of programming_guide/live_mode links to. */}+<span id="example-periodic-refresh-with-cocoauto_refresh"></span>++A common pattern is "run a regular processor on a fixed schedule." `ctx.auto_refresh` mounts a live component that re-runs a closure on an interval β no need to write `process_live` yourself.++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/live_component.rs (auto_refresh), rust/sdk/cocoindex/src/ctx.rs (Ctx::auto_refresh) */}<LangTabs><Fragment slot="python">@@ -372,18 +460,28 @@ Behavior:- In live mode, the loop continues: `sleep(interval) β run process_fn β ...` with a **fixed delay** between cycles (cycles never overlap; a slow cycle just stretches the gap).- In catch-up mode, the first cycle runs and `auto_refresh` terminates β observationally identical to mounting `process_fn` directly. The interval is ignored.- Cycle failures are routed through the parent's [exception handler chain](./exception_handlers#exception-handlers) (see `update_full()` above); the loop keeps going.-- **Each cycle reconciles target states against the previous cycle.** If `process_fn` no longer declares some target state (e.g. a row that vanished from your source table), CocoIndex automatically deletes the corresponding target β same garbage-collection model as a regular `coco.mount` re-run. You write the function as if processing from scratch each time; the framework handles the diff. See [Target State](../programming_guide/target_state) for the underlying model.+- **Each cycle reconciles target states against the previous cycle.** If `process_fn` no longer declares some target state (e.g. a row that vanished from your source table), CocoIndex automatically deletes the corresponding target β same garbage-collection model as a regular component re-run. You write the function as if processing from scratch each time; the framework handles the diff. See [Target State](../programming_guide/target_state) for the underlying model.++<Lang only="python">The returned class's `__init__` accepts the same positional and keyword arguments as `process_fn` β anything you'd pass to `coco.mount(process_fn, ...)` you can pass to `coco.mount(coco.auto_refresh(process_fn, interval=...), ...)`.+</Lang>++<Lang only="rust">++Here `process_fn` is the closure passed to `ctx.auto_refresh`.++</Lang>+## LiveMapFeed and LiveMapView:::tipFor an introduction to live mode, see [Live Mode](../programming_guide/live_mode). Connector authors can implement the protocols below to supply live collections.:::-Two protocols represent live keyed collections that `mount_each()` can consume. Choose based on whether your source can enumerate its current state:+Two <Lang only="python">protocols</Lang><Lang only="rust">traits</Lang> represent live keyed collections that <Lang only="python">`mount_each()`</Lang><Lang only="rust">`ctx.mount_each_live`</Lang> can consume. Choose based on whether your source can enumerate its current state:-- **`LiveMapView`** β the source has enumerable current state that can be scanned (e.g., a directory listing, database table). Supports both full scans via `__aiter__()` and incremental changes via `watch()`.+- **`LiveMapView`** β the source has enumerable current state that can be scanned (e.g., a directory listing, database table). Supports both full scans via <Lang only="python">`__aiter__()`</Lang><Lang only="rust">`scan()`</Lang> and incremental changes via `watch()`.- **`LiveMapFeed`** β the source only streams changes, with no "current state" to scan (e.g., a Kafka consumer, a webhook event stream). Provides only `watch()`.{/* Rust: rust/sdk/cocoindex/src/live_component.rs (LiveMapFeed, LiveMapView) */}@@ -421,22 +519,34 @@ pub trait LiveMapView<K, V>: LiveMapFeed<K, V> {}```-`ctx.mount_each_live(&key, feed, process_fn)` takes a `LiveMapView`. A watch-only source implements `scan` as an empty snapshot, so everything arrives through `watch()`. A durable feed can override `skip_initial_scan` to resume from a cursor it kept with `operator.read_committed_state`.-</Fragment></LangTabs>+<Lang only="python">+`LiveMapView` extends `LiveMapFeed` β any `LiveMapView` is also a valid `LiveMapFeed`. When `mount_each()` receives either protocol as its `items` argument, it automatically creates an internal `LiveComponent`:- **`LiveMapView`**: `__aiter__()` yields all `(key, value)` pairs for full scans (called inside the internal `process()`). `watch()` handles the full lifecycle.- **`LiveMapFeed`**: `process()` is a no-op (no snapshot to scan). All work happens in `watch()`.-In Rust the live mount is a separate method, `ctx.mount_each_live`, and `ctx.mount_each` only takes a plain collection.+</Lang>++<Lang only="rust">++`LiveMapView` extends `LiveMapFeed`. `ctx.mount_each_live(&key, feed, process_fn)` takes a `LiveMapView` and creates an internal `LiveComponent`: `scan()` yields all `(key, value)` pairs for full scans (called inside the internal `process()`), and `watch()` handles the incremental changes. A watch-only source implements `scan` as an empty snapshot, so everything arrives through `watch()`. A durable feed can override `skip_initial_scan` to resume from a cursor it kept with `operator.read_committed_state`.++</Lang>++<RustNote>+The live mount is a separate method, `ctx.mount_each_live`; `ctx.mount_each` and `ctx.mount_each_stream` only take a plain collection or stream of items.+</RustNote>### LiveMapSubscriberThe `subscriber` passed to `watch()` mirrors `LiveComponentOperator`:+<Lang only="python">+| LiveMapSubscriber | LiveComponentOperator | Description ||---|---|---|| `await subscriber.update_all()` | `await operator.update_full()` | Full re-scan of all items |@@ -444,7 +554,23 @@ The `subscriber` passed to `watch()` mirrors `LiveComponentOperator`:| `await subscriber.update(key, value)` | `await operator.update(subpath, fn, ...)` | Incremental update; returns `ComponentMountHandle` || `await subscriber.delete(key)` | `await operator.delete(subpath)` | Incremental delete; returns `ComponentMountHandle` |-The Rust `LiveMapSubscriber<K, V>` has the same four methods: `update_all().await?`, `mark_ready().await`, `update(key, value).await?` and `delete(key).await?`, plus `is_live()`. `update` and `delete` await until the child's state has synced.+</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/live_component.rs (LiveMapSubscriber) */}++| LiveMapSubscriber | LiveComponentOperator | Description |+|---|---|---|+| `subscriber.update_all().await?` | `operator.update_full().await?` | Full re-scan of all items |+| `subscriber.mark_ready().await` | `operator.mark_ready().await` | Signal readiness |+| `subscriber.update(key, value).await?` | `operator.update(key, f).await?` | Incremental update; awaits until the child's state has synced |+| `subscriber.delete(key).await?` | `operator.delete(key).await?` | Incremental delete; awaits until the deletion has synced |+| `subscriber.start_update(key, value).await?` / `start_delete(key)` | `operator.start_update` / `start_delete` | The same without waiting; returns a `ReadyHandle` |++The subscriber also has `is_live()`, and `read_committed_state` / `write_committed_state` for the feed's own durable cursor.++</Lang>A typical `watch()` implementation for a `LiveMapView`:@@ -495,14 +621,28 @@ The framework runs the initial scan itself, before `watch()`, so `watch()` start### Implementing live support for a connector-To add live support to a source connector, make your source return an object that implements `LiveMapView` (if the source has scannable state) or `LiveMapFeed` (if it only streams changes):+To add live support to a source connector, make your source return <Lang only="python">an object that implements</Lang><Lang only="rust">a type that implements</Lang> `LiveMapView` (if the source has scannable state) or `LiveMapFeed` (if it only streams changes):++<Lang only="python">- **`LiveMapView` example**: The [`localfs`](../connectors/localfs) connector's `DirWalker` β `walk_dir(..., live=True).items()` returns a `LiveMapView` backed by `watchfiles`.- **`LiveMapFeed` example**: The [`kafka`](../connectors/kafka) connector β `topic_as_map()` returns a `LiveMapFeed` that consumes messages from a Kafka topic.-The Rust SDK has the same two: `walk_dir(dir).live()` (feature `fs_live`) is a `LiveMapView`, and the `kafka` connector's topic map implements `LiveMapView`, with a scan that reads the latest message per key. A third one is `LiveMap<K, V>`, an in-process live source, described below.+</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/resources/fs.rs (DirWalker::live), src/connectors/kafka.rs (KafkaTopicMap), src/resources/live_map.rs */}-### LiveMap: an in-process live source (Rust)+- **`LiveMapView` example**: The [`localfs`](../connectors/localfs) walker β `walk_dir(dir).live()` (feature `fs_live`) returns a `LiveMapView`.+- **`LiveMapView` over a stream**: The [`kafka`](../connectors/kafka) connector β `kafka::topic_as_map(&consumer, topic)` implements `LiveMapView`, with a scan that reads the latest message per key.+- **In-process**: `LiveMap<K, V>`, described below.++</Lang>++<Lang only="rust">++### LiveMap: an in-process live source`LiveMap<K, V>` joins live data-*producing* logic and live data-*consuming* logic inside one session. The producer declares `(key, value)` entries as target states with `declare_entry`; the consumer reads the map as a `LiveMapView` through `ctx.mount_each_live`. An entry exists as long as some component declares it; when its declaring component stops declaring it, the entry is removed, and the consumer's child for it is deleted.@@ -548,11 +688,13 @@ let lm: LiveMap<String, String> = LiveMap::create(&ctx).await?;`LiveMap::create(&ctx)` mounts the map's backing container target. The map is an in-memory, live-mode primitive, not state that persists across runs.+</Lang>+### Single-subscriber contract-A live feed (`LiveMapView`, `LiveMapFeed`, or `LiveStream`) is **single-subscriber**. Its `watch()` typically owns an exclusive underlying resource (a consumer subscription, an OS file watch, a single in-memory change channel) that can't be fanned out to two concurrent callers β e.g. two subscriptions would race one consumer's offset commits. So a given feed instance supports **one active `watch()` (one `mount_each`) at a time**; consuming it from two places concurrently is unsupported. Fan-out to multiple subscribers, if ever needed, belongs in a layer above the feed.+A live feed (`LiveMapView`, `LiveMapFeed`, or `LiveStream`) is **single-subscriber**. Its `watch()` typically owns an exclusive underlying resource (a consumer subscription, an OS file watch, a single in-memory change channel) that can't be fanned out to two concurrent callers β e.g. two subscriptions would race one consumer's offset commits. So a given feed instance supports **one active `watch()` (one <Lang only="python">`mount_each`</Lang><Lang only="rust">`mount_each_live`</Lang>) at a time**; consuming it from two places concurrently is unsupported. Fan-out to multiple subscribers, if ever needed, belongs in a layer above the feed.-Enforce this in your `watch()` with `cocoindex.connectorkits.SingleWatcherGuard`, which raises `RuntimeError` on a second concurrent call:+Enforce this in your `watch()` with <Lang only="python">`cocoindex.connectorkits.SingleWatcherGuard`, which raises `RuntimeError` on a second concurrent call</Lang><Lang only="rust">`cocoindex::live_component::SingleWatcherGuard`, which returns an error on a second concurrent call</Lang>:{/* Rust: rust/sdk/cocoindex/src/live_component.rs (SingleWatcherGuard doc comment) */}<LangTabs>@@ -592,10 +734,12 @@ Build the guard with `SingleWatcherGuard::new("MyFeed")`. `enter()` returns an e## LiveStream-The Rust SDK has no `LiveStream`: a Rust connector that consumes raw events implements `LiveMapFeed` and translates each event into `subscriber.update` / `subscriber.delete` itself.-Some change sources are not naturally keyed maps β they deliver opaque event payloads (e.g. cloud-storage event notifications, raw message buses) that the consuming connector translates into map updates on its own terms. For these, CocoIndex provides **`LiveStream`**: a keyless sibling of `LiveMapFeed` β an unkeyed sequence of messages without any "key" or "delete" semantics. Connectors typically wrap a user-supplied `LiveStream` into their own `LiveMapView` (or `LiveMapFeed`) by translating each event into the appropriate key-level operation.+{/* Rust: rust/sdk/cocoindex/src/live_component.rs (LiveStream, LiveStreamSubscriber, ReadyHandle) */}+<LangTabs>+<Fragment slot="python">+```pythonclass LiveStream(Protocol[M]):async def watch(self, subscriber: LiveStreamSubscriber[M]) -> None: ...@@ -605,7 +749,31 @@ class LiveStreamSubscriber(Protocol[M]):async def mark_ready(self) -> None: ...```-`send()` is awaited by the producer to obtain a `ReadyAwaitable` handle; the handle's `ready()` is then awaited later (often by an internal offset/commit tracker) to signal that the message has been fully processed. The stream awaits each `send()` inline, so a slow subscriber naturally throttles the producer β at most one message is in flight per stream, bounding adapter memory regardless of producer rate.+</Fragment>+<Fragment slot="rust">++```rust+#[async_trait]+pub trait LiveStream<M: Send + 'static>: Send + Sync + 'static {+ /// Deliver messages to `subscriber` until cancelled.+ async fn watch(&self, subscriber: &dyn LiveStreamSubscriber<M>) -> Result<()>;+}++#[async_trait]+pub trait LiveStreamSubscriber<M>: Send + Sync {+ async fn send(&self, message: M) -> Result<ReadyHandle>;+ async fn mark_ready(&self);+ // Also `read_committed_state` / `write_committed_state`, with+ // defaults that keep nothing, for a stream's own durable cursor.+}+```++A subscriber returns `ReadyHandle::immediate()` for a message that needs no work, and `ReadyHandle::from_future(..)` (for example the handle of `LiveMapSubscriber::start_update`) otherwise.++</Fragment>+</LangTabs>++`send()` is awaited by the producer to obtain a <Lang only="python">`ReadyAwaitable`</Lang><Lang only="rust">`ReadyHandle`</Lang> handle; the handle's `ready()` is then awaited later (often by an internal offset/commit tracker) to signal that the message has been fully processed. The stream awaits each `send()` inline, so a slow subscriber naturally throttles the producer β at most one message is in flight per stream, bounding adapter memory regardless of producer rate.`mark_ready()` must return promptly β it is awaited inline in the producer's loop. Subscribers that need to wait on additional preconditions (e.g. a pending scan) should spawn a background task and return.@@ -613,12 +781,26 @@ class LiveStreamSubscriber(Protocol[M]):A connector built on `LiveStream` typically:-1. Accepts a user-supplied `LiveStream[...]` as a constructor argument β the user wires up the underlying transport.-2. Wraps the stream into a `LiveMapView` (or `LiveMapFeed`): `__aiter__()` runs an initial scan if the source has scannable state; `watch()` subscribes to the stream and translates each event into `subscriber.update(key, value)` / `subscriber.delete(key)`.+1. Accepts a user-supplied <Lang only="python">`LiveStream[...]` as a constructor argument</Lang><Lang only="rust">`LiveStream<...>` as an argument</Lang> β the user wires up the underlying transport.+2. Wraps the stream into a `LiveMapView` (or `LiveMapFeed`): <Lang only="python">`__aiter__()`</Lang><Lang only="rust">`scan()`</Lang> runs an initial scan if the source has scannable state; `watch()` subscribes to the stream and translates each event into `subscriber.update(key, value)` / `subscriber.delete(key)`<Lang only="rust"> (or their `start_*` forms, whose `ReadyHandle` the stream awaits before it acknowledges the event)</Lang>.3. Lets the underlying `LiveStream` handle offset commits, readiness signaling, and back-pressure.-4. Guards its `watch()` against concurrent subscription β see [Single-subscriber contract](#single-subscriber-contract) β with `connectorkits.SingleWatcherGuard`.+4. Guards its `watch()` against concurrent subscription β see [Single-subscriber contract](#single-subscriber-contract) β with `SingleWatcherGuard`.++<Lang only="python">++**Example**: The [`oci_object_storage`](../connectors/oci_object_storage#live-bucket-watching) connector takes a `LiveStream[bytes]` (typically [`kafka.topic_as_stream(...).payloads()`](../connectors/kafka#as-a-live-stream)) and translates OCI Object Storage events into bucket-keyed updates.++</Lang>++<Lang only="rust">++{/* Rust: rust/sdk/cocoindex/src/connectors/oci_object_storage.rs (list_objects_live), src/connectors/kafka.rs (topic_as_stream, KafkaTopicStream::payloads) */}-**Example**: The [`oci_object_storage`](../connectors/oci_object_storage#live-bucket-watching) connector takes a `LiveStream[bytes]` (typically [`kafka.topic_as_stream(...).payloads()`](../connectors/kafka#as-a-live-stream)) and translates OCI Object Storage events into bucket-keyed updates. The Kafka connector exposes `topic_as_stream()` precisely so that downstream connectors like this one can plug into Kafka without inheriting the keyed-map semantics of `topic_as_map()`.+**Example**: The [`oci_object_storage`](../connectors/oci_object_storage#live-bucket-watching) connector's `list_objects_live` takes a `LiveStream<Vec<u8>>` of event payloads (typically [`kafka::topic_as_stream(..).payloads()`](../connectors/kafka#as-a-live-stream)) and translates OCI Object Storage events into bucket-keyed updates.++</Lang>++The Kafka connector exposes `topic_as_stream()` precisely so that downstream connectors like this one can plug into Kafka without inheriting the keyed-map semantics of `topic_as_map()`.## Live mode vs catch-up mode@@ -626,15 +808,28 @@ See [Live Mode](../programming_guide/live_mode) for how the two modes are enableFor a manual `LiveComponent`, the mode controls whether `process_live()` continues running after `mark_ready()`:+<Lang only="python">+- **Live mode** (`live=True`): `process_live()` continues after `mark_ready()` β the component keeps watching for changes.- **Catch-up mode** (`live=False`, default): `process_live()` terminates as soon as `mark_ready()` is awaited. No code after `await operator.mark_ready()` executes, so the component behaves like a traditional one-shot processor.This lets you use the same `LiveComponent` class in both modes without code changes.-In Rust, live mode is `UpdateOptions { live: true, .. }` on `app.update_with_options(..)`, or `cocoindex update -L` with the Rust CLI. `operator.is_live()` tells the body which mode it runs in.+</Lang>++<Lang only="rust">++- **Live mode** (`UpdateOptions { live: true, .. }` on `app.update_with_options(..)`, or `cocoindex update -L`): `process_live()` continues after `mark_ready()` β the component keeps watching for changes.+- **Catch-up mode** (the default): `process_live()` terminates as soon as `mark_ready()` is awaited. No code after `operator.mark_ready().await` executes, so the component behaves like a traditional one-shot processor.++This lets you use the same `LiveComponent` type in both modes without code changes. `operator.is_live()` tells the body which mode it runs in.++</Lang>## Restrictions+<Lang only="python">+### No `use_mount()` inside `process()``process()` may only call `coco.mount()` (background child mounts). Any setup that requires `use_mount()` (such as declaring target tables) must be done in the **parent** component before mounting the LiveComponent. This keeps the controller's provider set stable across full and incremental updates.@@ -647,11 +842,23 @@ LiveComponent classes can only be used with `coco.mount()` and `operator.update(While LiveComponent classes cannot be passed to `mount_each()`, use a [`LiveMapFeed` or `LiveMapView`](#livemapfeed-and-livemapview) β `mount_each()` automatically creates an internal LiveComponent when it detects one.:::-In Rust a `LiveComponent` is mounted only with `ctx.mount_live` (or `mount_live_with_handler`). To mount one live component per item, use `ctx.mount_each_live_component(items, key_fn, make_component)`; to fan one feed out into closure-driven children, use `ctx.mount_each_live`.+</Lang>++<Lang only="rust">++### No `use_mount!` inside `process()`++`process()` may only mount background children (`ctx.mount`, `mount!`, `ctx.mount_each`, `mount_each!`). Any setup that requires `ctx.scope` / `use_mount!` (such as declaring target tables) must be done in the **parent** component before mounting the LiveComponent. This keeps the controller's provider set stable across full and incremental updates.++### Mounting a LiveComponent++A `LiveComponent` is mounted only with `ctx.mount_live` (or `ctx.mount_live_with_handler`). To mount one live component per item, use `ctx.mount_each_live_component(items, key_fn, make_component)`; to fan one feed out into closure-driven children, use `ctx.mount_each_live`.++</Lang>## Readiness-The parent's `await handle.ready()` returns when `mark_ready()` is called inside `process_live()`, regardless of whether `process_live()` is still running.+The parent's <Lang only="python">`await handle.ready()`</Lang><Lang only="rust">`ctx.mount_live(...)` call</Lang> returns when `mark_ready()` is called inside `process_live()`, regardless of whether `process_live()` is still running.```mermaidsequenceDiagramdiff --git a/docs/src/content/docs/advanced_topics/memoization_keys.mdx b/docs/src/content/docs/advanced_topics/memoization_keys.mdxindex 7a27817b..1bb2c632 100644--- a/docs/src/content/docs/advanced_topics/memoization_keys.mdx+++ b/docs/src/content/docs/advanced_topics/memoization_keys.mdx@@ -4,18 +4,29 @@ description: >Customize how CocoIndex fingerprints memoized inputs via __coco_memo_key__ orregistered functions, and layer state validation (e.g. mtime, then content hash)on top β plus NotMemoKeyable to opt out for stateful types.+rust_description: >+ Customize how CocoIndex fingerprints memoized inputs through the MemoInput+ trait, layer state validation (e.g. mtime, then content hash) on top with+ memo_state, and declare dependencies beyond the arguments with deps,+ LogicDep and DataDep.---import LangTabs from '../../../components/LangTabs.astro';-CocoIndex detects [logic, input, and context changes](../programming_guide/function#change-detection) to decide whether it can reuse a memo. It fingerprints function arguments, [`deps`](../programming_guide/function#deps) values, and [context values](../programming_guide/context#change-detection) with `detect_change=True` through the same pipeline. Most types work automatically. You can customize fingerprinting and validation with:+CocoIndex detects [logic, input, and context changes](../programming_guide/function#change-detection) to decide whether it can reuse a memo. It fingerprints function arguments, [`deps`](../programming_guide/function#deps) values, and [context values](../programming_guide/context#change-detection) with <Lang only="python">`detect_change=True`</Lang><Lang only="rust">`detect_change`</Lang> through the same pipeline. Most types work automatically. You can customize fingerprinting and validation with:- **Memoization keys** β how to control what CocoIndex uses as the fingerprint for your objects.- **Memo states** β how to add post-fingerprint validation to check freshness beyond simple equality.-The Rust SDK keeps the same split between **identity** and **freshness**, through one trait: `MemoInput`. Its `write_memo_key` method is the key; its optional `memo_state` method is the state. The arguments of a `#[cocoindex::function(memo)]` function must implement `MemoInput`, unless `memo_key(..)` transforms or skips them. A `context_key!` value takes part only when the key is declared with `detect_change`.+<Lang only="rust">++Both go through one trait, `MemoInput`, which keeps **identity** and **freshness** apart: its `write_memo_key` method is the key; its optional `memo_state` method is the state. The arguments of a `#[cocoindex::function(memo)]` function must implement `MemoInput`, unless `memo_key(..)` transforms or skips them. A `context_key!` value takes part only when the key is declared with `detect_change`.++</Lang>## How data fingerprinting works+<Lang only="python">+For each data value (function argument, `deps` value, or context value), CocoIndex derives a canonical form with this precedence:1. If the object implements **`__coco_memo_key__()`**, CocoIndex uses its return value.@@ -31,7 +42,11 @@ The following types are handled automatically (no custom key needed):- **Class objects** (`type`): identified by module and qualified name- **Other picklable objects**: used as a fallback via `pickle`-In Rust there is no fallback: a type is a memo input when it implements `MemoInput`. The SDK implements it for the primitives (`bool`, the integer and float types, `char`, `String`, `str`), `PathBuf` / `Path`, `Duration`, `SystemTime`, `uuid::Uuid`, `Fingerprint`, `bytes::Bytes` and `serde_json::Value`; for Chrono date and time values with the `chrono` feature and for `rust_decimal::Decimal` with the `rust_decimal` feature (a connector feature turns these on). `Option`, arrays, slices, `Vec`, tuples, maps, sets, `Box` and `Arc` compose their children's `MemoInput`. For your own structs and enums, derive it:+</Lang>++<Lang only="rust">++For each data value (function argument, `deps` value, or context value), CocoIndex writes a canonical form through its `MemoInput` implementation. A type is a memo input when it implements `MemoInput`. The SDK implements it for the primitives (`bool`, the integer and float types, `char`, `String`, `str`), `PathBuf` / `Path`, `Duration`, `SystemTime`, `uuid::Uuid`, `Fingerprint`, `bytes::Bytes` and `serde_json::Value`; for Chrono date and time values with the `chrono` feature and for `rust_decimal::Decimal` with the `rust_decimal` feature (a connector feature turns these on). `Option`, arrays, slices, `Vec`, tuples, maps, sets, `Box` and `Arc` compose their children's `MemoInput`. For your own structs and enums, derive it:{/* Rust: examples/rust/conversation_to_knowledge/src/models.rs */}```rust@@ -52,14 +67,32 @@ pub struct SessionTranscript {The derive visits every field recursively, in order; the type itself does not need `Serialize`. Moving or renaming a derived type, or renaming one of its named fields, changes its identity and causes a one-time cache miss. A `Vec<u8>` is hashed element by element like any `Vec<T>`: for a large byte buffer, use `bytes::Bytes` for bulk hashing, or pass a precomputed `Fingerprint` (`cocoindex::Fingerprint`) when the content is already hashed.+</Lang>++<RustNote>+There is no fallback like Python's `pickle`: a type that does not implement `MemoInput` cannot be a memo input, and the compiler says so.+</RustNote>+The canonical forms are combined into a deterministic fingerprint. If the fingerprint matches a cached entry, the cached result is reused β unless **memo states** indicate it's stale (see [Memo state validation](#memo-state-validation) below).## Customizing the memoization key+<Lang only="python">+### Define `__coco_memo_key__` (when you control the type)Implement a method on your class that returns a stable, deterministic value:+</Lang>++<Lang only="rust">++### Implement `MemoInput` (when you control the type)++Implement `write_memo_key` on your type and write a stable, deterministic value:++</Lang>+{/* Rust: examples/rust/conversation_to_knowledge/src/clients.rs (impl MemoInput for LlmClient) */}<LangTabs><Fragment slot="python">@@ -91,7 +124,7 @@ impl MemoInput for LlmClient {Return something that uniquely identifies the **semantic content** your function depends on:- **Good**: small tuples of primitives, e.g. `(stable_id, version)`-- **Bad**: memory addresses, unstable UUIDs, open file handles, `datetime.now()`, or large raw payloads+- **Bad**: memory addresses, unstable UUIDs, open file handles, <Lang only="python">`datetime.now()`</Lang><Lang only="rust">`SystemTime::now()`</Lang>, or large raw payloads**Example β DB row:**@@ -131,6 +164,8 @@ impl cocoindex::MemoInput for UserRow {</Fragment></LangTabs>+<Lang only="python">+### Register a key function (when you don't control the type)If you can't add `__coco_memo_key__` (stdlib / third-party types), register a handler:@@ -150,7 +185,13 @@ register_memo_key_function(Path, path_key)- Registration is **MRO-aware**: if you register both a base class and a subclass, the **most specific** match wins.- Your key function must return the same kinds of stable objects as `__coco_memo_key__` (small primitives/tuples).-The Rust SDK has no registry. Rust's orphan rules stop a crate from implementing `MemoInput` for a type it does not own, so wrap a third-party type in a local newtype and implement the trait on that, or transform the argument at the call site with `memo_key(..)` (next section):+</Lang>++<Lang only="rust">++### Wrap it in a newtype (when you don't control the type)++Rust's orphan rules stop a crate from implementing `MemoInput` for a type it does not own, so wrap a third-party type in a local newtype and implement the trait on that, or transform the argument at the call site with `memo_key(..)` (next section):{/* Rust: shape of examples/rust/conversation_to_knowledge/src/clients.rs (impl MemoInput), rust/sdk/cocoindex/src/memo.rs module docs */}```rust@@ -166,10 +207,31 @@ impl cocoindex::MemoInput for ForeignId {}```+</Lang>++<RustNote>+There is no `register_memo_key_function` registry: a newtype or a call-site `memo_key(..)` takes its place.+</RustNote>++<Lang only="python">+### Override at the call site with `memo_key=`The two approaches above are **type-level**: every memoized function sees the same fingerprint for a given object. To customize fingerprinting **only for a specific function**, pass `memo_key=` to `@coco.fn` (or `@coco.fn.as_async`). It maps parameter names to either a callable (transform the value before fingerprinting) or `None` (exclude the parameter entirely).+</Lang>++<Lang only="rust">++### Override at the call site with `memo_key(..)`++{/* Keeps the anchor that the Rust copy of programming_guide/function links to. */}+<span id="override-at-the-call-site-with-memo_key"></span>++The two approaches above are **type-level**: every memoized function sees the same fingerprint for a given value. To customize fingerprinting **only for a specific function**, add `memo_key(..)` to `#[cocoindex::function(memo)]`. It maps parameter names to either a transform function (transform the value before fingerprinting) or `skip` (exclude the parameter entirely).++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (memo_key_transform_and_skip_for_function_macro) */}<LangTabs><Fragment slot="python">@@ -199,6 +261,8 @@ async fn transform_entry(ctx: &Ctx, entry: &Entry, extra: &String) -> Result<Str</Fragment></LangTabs>+<Lang only="python">+Each entry in `memo_key`:- **Callable** β applied to the argument; its return value is fingerprinted in place of the original. Semantically the same as `__coco_memo_key__()` on the type, but scoped to this one function. Useful when the type's default fingerprint is correct everywhere *else*, and only this function should treat the argument differently.@@ -212,9 +276,21 @@ It works for every parameter kind:- **`*args`** β name the varargs parameter; the callable receives the full tuple and must return a tuple. `None` excludes all variadic positional arguments.- **`**kwargs`** β name the varkw parameter; the callable receives a dict and must return a dict. `None` excludes all variadic keyword arguments.-`memo_key` is validated at decoration time: unknown parameter names raise `ValueError`, and values that are neither callable nor `None` raise `TypeError`. In Rust the macro checks the names at compile time. A transform also suppresses the argument type's `memo_state` validation; use a newtype when the freshness check must stay.+`memo_key` is validated at decoration time: unknown parameter names raise `ValueError`, and values that are neither callable nor `None` raise `TypeError`.++</Lang>++<Lang only="rust">++Each entry in `memo_key(..)`:-**Target handles in Rust.** A target handle is where output goes, not an input of the computation, so it is not `MemoInput`. `DirTarget` and the Postgres, SQLite, Doris, SurrealDB, LanceDB, Neo4j and FalkorDB table and relation targets are `Serialize` instead: as an argument of a memoized function or of `mount!`, `use_mount!` or `mount_each!`, one is keyed by its stable key, as in Python. The other connectors' handles are only `Clone`. Skip those in the memo key; you can skip any handle the same way:+- **`name = transform_fn`** β the transform's return value is fingerprinted in place of the argument. Semantically the same as the type's own `write_memo_key`, but scoped to this one function.+- **`name = skip`** β the parameter is excluded from the memo key. Changing its value never invalidates the cache. Useful for arguments that don't affect the result (logger handles, debug flags, target handles).+- **Not listed** β the parameter is fingerprinted normally, through its `MemoInput`.++The macro checks the names at compile time. A transform also suppresses the argument type's `memo_state` validation; use a newtype when the freshness check must stay.++**Target handles.** A target handle is where output goes, not an input of the computation, so it is not `MemoInput`. `DirTarget` and the Postgres, SQLite, Doris, SurrealDB, LanceDB, Neo4j and FalkorDB table and relation targets are `Serialize` instead: as an argument of a memoized function or of `mount!`, `use_mount!` or `mount_each!`, one is keyed by its stable key. The other connectors' handles are only `Clone`. Skip those in the memo key; you can skip any handle the same way:{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (target_state_of_nested_memo_survives_outer_memo_hit) */}```rust@@ -224,12 +300,28 @@ async fn declare_nested(ctx: &Ctx, target: DirTarget, content: String) -> Result}```+</Lang>++<Lang only="python">+:::tip[Picking the right tool]- You control the type and the fingerprint is the same wherever it's used β **`__coco_memo_key__`**.- You don't control the type but want a global handler β **`register_memo_key_function`**.- Only *this* function should treat an argument specially (transform or skip it) β **`memo_key=`**.:::+</Lang>++<Lang only="rust">++:::tip[Picking the right tool]+- You control the type and the fingerprint is the same wherever it's used β **implement or derive `MemoInput`**.+- You don't control the type β **a newtype that implements `MemoInput`**.+- Only *this* function should treat an argument specially (transform or skip it) β **`memo_key(..)`**.+:::++</Lang>+## Memo state validationSometimes fingerprint matching alone isn't enough to decide whether a cached result is valid. For example:@@ -242,6 +334,8 @@ Memo state validation addresses these by letting you attach a **state function**### How it works+<Lang only="python">+When CocoIndex finds a fingerprint match, it calls each state function with the stored state from the previous run:1. **First run** (no previous state): `prev_state` is `coco.NON_EXISTENCE`. Use `coco.is_non_existence(prev_state)` to detect this.@@ -258,13 +352,49 @@ This decouples "has the state changed?" from "can we reuse the memo?":- `MemoStateOutcome(state=same_state, memo_valid=True)` β nothing changed, cached result reused, no state update needed.- `MemoStateOutcome(state=new_state, memo_valid=True)` β state changed but cached result is still valid (e.g. mtime changed but content hash unchanged). The new state is persisted so the next run uses the updated state.+</Lang>++<Lang only="rust">++When CocoIndex finds a fingerprint match, it calls each value's `memo_state` with the stored state from the previous run:++1. **First run** (no previous state): `previous` is `None`.+2. **Subsequent runs**: `previous` is the state you stored last time; `previous.deserialize::<T>()` reads it back.++`memo_state` returns `Ok(Some(MemoStateDecision::new(&state, memo_valid)?))`:++- **`state`** β the current state value. CocoIndex stores it for the next run.+- **`memo_valid`** β whether the cached result is still valid.++This decouples "has the state changed?" from "can we reuse the memo?":++- `MemoStateDecision::new(&new_state, false)` β cache is invalid. Function re-executes, new state is stored. On the first run (no previous cache), return the initial state with `false`.+- `MemoStateDecision::new(&same_state, true)` β nothing changed, cached result reused.+- `MemoStateDecision::new(&new_state, true)` β state changed but cached result is still valid (e.g. mtime changed but content hash unchanged). The new state is persisted so the next run uses the updated state.++`Ok(None)` (the default) means the value needs no state validation.++</Lang>++<Lang only="python">+### Define `__coco_memo_state__` (when you control the type):::info[Type annotations]Annotate the `prev_state` parameter with its expected type (matching what you return in `MemoStateOutcome(state=...)`) so CocoIndex can properly reconstruct stored state values. See [Serialization](../programming_guide/serialization) for details on supported types.:::-Add a `__coco_memo_state__` method alongside `__coco_memo_key__`. In Rust, implement the async `memo_state` method of `MemoInput` beside `write_memo_key`; the Rust tab shows the shape with a version number as the state.+Add a `__coco_memo_state__` method alongside `__coco_memo_key__`.++</Lang>++<Lang only="rust">++### Implement `memo_state` (when you control the type)++Implement the async `memo_state` method of `MemoInput` beside `write_memo_key`, with `#[cocoindex::async_trait]` on the impl. The example uses a version number as the state.++</Lang>{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (type_owned_context_memo_state_invalidates_cached_function) */}<LangTabs>@@ -298,7 +428,7 @@ class LocalFile:# mtime unchanged β definitely reusable, no content read neededreturn coco.MemoStateOutcome(state=prev_state, memo_valid=True)# mtime changed β read content and check hash- content_hash = coco.connectorkits.fingerprint_bytes(self.path.read_bytes())+ content_hash = hashlib.sha256(self.path.read_bytes()).hexdigest()return coco.MemoStateOutcome(state=(new_mtime, content_hash), memo_valid=content_hash == prev_hash)```@@ -335,11 +465,13 @@ impl cocoindex::MemoInput for Resource {}```-`memo_state` runs after an identity match. `MemoStateDecision::new(&state, memo_valid)` is the Rust `MemoStateOutcome`: the state to store, and whether the cached result is still valid. Return `Ok(None)` for a value that needs no validation (the default). A stored state that no longer deserializes counts as a cache miss, not an error.+`memo_state` runs after an identity match. A stored state that no longer deserializes counts as a cache miss, not an error.</Fragment></LangTabs>+<Lang only="python">+:::tip[Keys vs states for files]Without state validation, you'd include `mtime` and `size` directly in the memo key:```python@@ -370,7 +502,17 @@ def path_state(p: Path, prev_state: tuple[int, int] | coco.NonExistenceType) ->register_memo_key_function(Path, path_key, state_fn=path_state)```-In Rust, the newtype that carries `write_memo_key` for a foreign type carries `memo_state` too.+</Lang>++<Lang only="rust">++### State for a type you don't control++The newtype that carries `write_memo_key` for a foreign type carries `memo_state` too.++</Lang>++<Lang only="python">### State that depends on what the function did@@ -401,19 +543,23 @@ class Tracked:The flag is only read when the cached result is not reused. It applies to memoized functions; a memoized component that returns it raises an error.-The Rust SDK has no `recollect_after_run`. For reads decided while the body runs, use `ctx.use_data_dep` (see [Dependencies beyond the arguments](#dependencies-beyond-the-arguments-rust) below).-When the state is the set of things the function *read* that are not among its arguments, record each read with [`coco.use_data_dep`](../programming_guide/function#data-dependencies-datadep-and-use_data_dep) (experimental) instead: it works for components too, and validates each read on its own.+</Lang>++<RustNote>+`MemoStateDecision` has no `recollect_after_run`: the state stored after a re-run is the one `memo_state` returned before the body ran. For reads decided while the body runs, record each read with `ctx.use_data_dep` (see [`DataDep`](#datadep-data-the-body-reads-while-it-runs-experimental) below).+</RustNote>+### Async state methods+<Lang only="python">+A state method can return an `Awaitable`. CocoIndex handles this automatically:- **In an async CocoIndex function**: awaitables from all state methods are gathered concurrently.- **In a sync CocoIndex function**: if no event loop is running, CocoIndex uses `asyncio.run()`. If a loop is already running, it raises an error β switch to an async function or use `@coco.fn.as_async`.-In Rust, `memo_state` is always `async`, and the state checks of nested values run concurrently. CocoIndex stores their results as one opaque state per top-level function argument or context dependency.-```pythonimport cocoindex as coco@@ -434,9 +580,19 @@ class S3Object:... # boto3 / aioboto3 HEAD call```-## Dependencies beyond the arguments (Rust)+</Lang>-A function's memo key covers its arguments and the context values it reads. The Rust SDK adds three ways to declare what else a result depends on. Python has the same three: [`deps`](../programming_guide/function#deps), [`LogicDep` / `use_logic_dep`](../programming_guide/function#per-call-dependencies-logicdep-and-use_logic_dep) and [`DataDep` / `use_data_dep`](../programming_guide/function#data-dependencies-datadep-and-use_data_dep).+<Lang only="rust">++`memo_state` is always `async`, so a freshness check can send a network request (an S3 `HEAD`, an HTTP `If-Modified-Since`), and the state checks of nested values run concurrently. CocoIndex stores their results as one opaque state per top-level function argument or context dependency.++</Lang>++<Lang only="rust">++## Dependencies beyond the arguments++A function's memo key covers its arguments and the context values it reads. Three more ways declare what else a result depends on: [`deps`](../programming_guide/function#deps), [`LogicDep` / `use_logic_dep`](../programming_guide/function#per-call-dependencies-logicdep-and-use_logic_dep) and [`DataDep` / `use_data_dep`](../programming_guide/function#data-dependencies-datadep-and-use_data_dep).### `version` and `deps` on the attribute@@ -535,11 +691,19 @@ let processed = ctx.memo(&fingerprint, |ctx| async move {Prefer `#[cocoindex::function(memo)]` for a whole function: it builds the key from the arguments and tracks the body's logic for you.+</Lang>+## Preventing memoizationSome types maintain internal state that makes memoization semantically incorrect. For example, a generator that tracks call counts would produce wrong results if memoized.-In Rust, a type that does not implement `MemoInput` cannot be an argument of a memoized function: the compiler rejects it with a note that names the three ways out (derive, implement, or a `memo_key` override). Leave the trait unimplemented for a stateful type, and use `memo_key(arg = skip)` where it must be passed through.+<Lang only="rust">++A type that does not implement `MemoInput` cannot be an argument of a memoized function: the compiler rejects it with a note that names the three ways out (derive, implement, or a `memo_key` override). Leave the trait unimplemented for a stateful type, and use `memo_key(arg = skip)` where it must be passed through.++</Lang>++<Lang only="python">### Inherit from `NotMemoKeyable` (when you control the type)@@ -566,10 +730,12 @@ coco.register_not_memo_keyable(StatefulGenerator)In either case, attempting to use the type as a memo key raises a clear error.+</Lang>+## Choosing keys and states-- **Keep keys small and deterministic**: use identifiers and versions, not full payloads. No `id(obj)`, pointer addresses, or random values.+- **Keep keys small and deterministic**: use identifiers and versions, not full payloads. No <Lang only="python">`id(obj)`, </Lang>pointer addresses, or random values.- **Separate identity from freshness**: put stable identifiers (file path, URL, primary key) in the key. Put freshness checks (mtime, ETag, version) in the state.- **Use state validation for expensive checks**: if freshness validation is costly (content hashing, network calls), a state function lets you do it only when the fingerprint matches, and only when a cheap pre-check (mtime) fails.-- **Use `MemoStateOutcome(state=new_state, memo_valid=True)` for cheap state updates**: when a cheap property changes (mtime) but the expensive check (content hash) confirms nothing meaningful changed, return `memo_valid=True` while updating the state. This avoids re-executing the function and avoids re-checking the expensive property next time.-- **Mark stateful types as `NotMemoKeyable`**: prevent subtle bugs from incorrect memoization of types with side effects.+- **Use <Lang only="python">`MemoStateOutcome(state=new_state, memo_valid=True)`</Lang><Lang only="rust">`MemoStateDecision::new(&new_state, true)`</Lang> for cheap state updates**: when a cheap property changes (mtime) but the expensive check (content hash) confirms nothing meaningful changed, mark the memo valid while updating the state. This avoids re-executing the function and avoids re-checking the expensive property next time.+- **<Lang only="python">Mark stateful types as `NotMemoKeyable`</Lang><Lang only="rust">Leave `MemoInput` unimplemented for stateful types</Lang>**: prevent subtle bugs from incorrect memoization of types with side effects.diff --git a/docs/src/content/docs/advanced_topics/multiple_environments.mdx b/docs/src/content/docs/advanced_topics/multiple_environments.mdxindex 3d13e608..4e7b93bd 100644--- a/docs/src/content/docs/advanced_topics/multiple_environments.mdx+++ b/docs/src/content/docs/advanced_topics/multiple_environments.mdx@@ -4,10 +4,14 @@ description: >Run isolated CocoIndex environments side by side with explicit Environment andSettings objects and separate db_paths β for multi-tenancy, librarydevelopment, and testing. The CLI targets named environments via @env_name.+rust_description: >+ Run isolated CocoIndex environments side by side with explicit Environment+ builders and separate db_paths β for multi-tenancy, library development,+ and testing.---import LangTabs from '../../../components/LangTabs.astro';-By default, all CocoIndex apps share the same environment, which manages a shared database and context. For most use cases, this default behavior is sufficient. However, you can create multiple isolated environments when you need:+<Lang only="python">By default, all CocoIndex apps share the same environment, which manages a shared database and context. For most use cases, this default behavior is sufficient. However, you can create multiple isolated environments when you need:</Lang><Lang only="rust">An environment manages a database and the context values shared by its apps. Most programs build one environment, through `Environment::from_registered()` or a builder. You can create multiple isolated environments when you need:</Lang>- **Library development**: Libraries that depend on CocoIndex can use their own environment to avoid sharing state with other libraries or the application- **Database isolation**: Different apps using separate databases@@ -16,7 +20,7 @@ By default, all CocoIndex apps share the same environment, which manages a share## Creating an Environment-Create an explicit environment by providing `Settings` with a `db_path`:+Create an explicit environment <Lang only="python">by providing `Settings` with a `db_path`</Lang><Lang only="rust">with `Environment::builder()` and a `db_path`</Lang>:{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (Environment::builder), rust/sdk/cocoindex/src/app.rs */}<LangTabs>@@ -46,6 +50,8 @@ An `Environment` built this way reads no environment variables. `Environment::fr</Fragment></LangTabs>+<Lang only="python">+You can optionally name the environment for easier identification:```python@@ -55,13 +61,23 @@ env = coco.Environment()```-A Rust `Environment` has no name of its own: the name a handler sees in `ExceptionContext::env_name` is the app's name.+`Settings` also accepts `db_settings` (a `coco.LmdbSettings` instance) for tuning the internal LMDB database. See [Internal Storage](./internal_storage#lmdb-tuning) for details.++</Lang>++<Lang only="rust">++The builder also has `lmdb_max_dbs(..)` and `lmdb_map_size(..)` for tuning the internal LMDB database. See [Internal Storage](./internal_storage#lmdb-tuning) for details.-`Settings` also accepts `db_settings` (a `coco.LmdbSettings` instance) for tuning the internal LMDB database. See [Internal Storage](./internal_storage#lmdb-tuning) for details. The Rust builder has `lmdb_max_dbs(..)` and `lmdb_map_size(..)` for the same settings.+</Lang>++<RustNote>+An `Environment` has no name of its own: the name a handler sees in `ExceptionContext::env_name` is the app's name.+</RustNote>## Associating Apps with an Environment-Pass the environment to `AppConfig` when creating an app:+<Lang only="python">Pass the environment to `AppConfig` when creating an app</Lang><Lang only="rust">Create the app from the environment</Lang>:{/* Rust: rust/sdk/cocoindex/src/app.rs (Environment::app), rust/sdk/SHOWCASE.md (verified) */}<LangTabs>@@ -86,10 +102,20 @@ Several apps can share one environment: each name is its own LMDB namespace, and</Fragment></LangTabs>-Apps that don't specify an environment use the default environment (configured via `@coco.lifespan` or the `COCOINDEX_DB` environment variable). In Rust, there is no implicit default environment: an `App` always comes from an `Environment` you built, or from `Environment::from_registered()`.+<Lang only="python">++Apps that don't specify an environment use the default environment (configured via `@coco.lifespan` or the `COCOINDEX_DB` environment variable).++</Lang>++<RustNote>+There is no implicit default environment: an `App` always comes from an `Environment` you built, or from `Environment::from_registered()`, which runs the `#[cocoindex::lifespan]` functions and reads `COCOINDEX_DB` when no lifespan set a db path.+</RustNote>## Closing an Environment+<Lang only="python">+An environment holds its database open, and LMDB allows one environment per `db_path` per process. An explicit environment's store is released when the last reference to it is gone: the environment itself, the Apps and `AppConfig`s bound to it, its `ContextProvider`, and any operations still finishing. Until then, opening the same `db_path` again fails:```text@@ -98,6 +124,16 @@ RuntimeError: the database at 'my_db.db' is already open in this process; closeCall `env.close()` once you're done with it to release the database without waiting for those references:+</Lang>++<Lang only="rust">++An environment holds its database open, and LMDB allows one environment per `db_path` per process: while one is open, building another on the same `db_path` fails with an error that says the database "is already open in this process".++Call `env.shutdown().await` once you're done with it to close the database:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/registered_nodb.rs (env.shutdown), rust/sdk/cocoindex/src/app.rs (Environment::shutdown) */}<LangTabs><Fragment slot="python">@@ -120,10 +156,14 @@ let env = Environment::builder().db_path("./my_db.db").build().await?;</Fragment></LangTabs>+<Lang only="python">+`close()` waits for in-flight writes to finish. After that, using the environment raises an error, and so does updating the apps that use it. Context values provided to the environment stay open: whoever provided them closes them. Stopping the default environment (leaving `coco.runtime()`, or calling `coco.stop()`) closes it for you.Garbage collection only helps when the last reference sits in a cycle: `gc.collect()` breaks the cycle and releases the store. Don't count on it otherwise. An environment created while an event loop is running (for example, inside a function run by `asyncio.run()`) runs its apps on that loop. On free-threaded Python 3.14+, that loop's worker threads, which connectors use for file I/O, then keep the environment alive, and its database open, for as long as the loop runs β even after you drop every reference to it. So do threads you start from your own functions while an app updates.+</Lang>+## Example: Multiple EnvironmentsThis example creates two apps in different environments, each with its own database:@@ -189,7 +229,9 @@ app2.run(|ctx| async move { build2(&ctx).await }).await?;## Same App Name in Different Environments-Apps with the same name can coexist in different environments. This is useful for multi-tenant scenarios or running the same pipeline against different databases:+Apps with the same name can coexist in different environments. This is useful for multi-tenant scenarios or running the same pipeline against different databases<Lang only="rust">: `env_alpha.app("MyApp")` and `env_default.app("MyApp")` are two apps with their own state, one per environment.</Lang><Lang only="python">:</Lang>++<Lang only="python">```pythonimport cocoindex as coco@@ -218,7 +260,9 @@ app_alpha = coco.App(coco.AppConfig(name="MyApp", environment=env_alpha), build)app_default = coco.App("MyApp", build) # Uses default environment```-The same holds in Rust: `env_alpha.app("MyApp")` and `env_default.app("MyApp")` are two apps with their own state, one per environment. The `cocoindex` CLI for Rust drives the one environment that `Environment::from_registered()` builds, so it has no `@env_name` syntax.+</Lang>++<Lang only="python">## CLI Support@@ -235,6 +279,12 @@ cocoindex update ./multi_env.py:MyApp@alphacocoindex update ./multi_env.py:MyApp@default```+</Lang>++<RustNote>+The `cocoindex` CLI for Rust drives the one environment that `Environment::from_registered()` builds, so it has no `@env_name` syntax.+</RustNote>+## Testing with Isolated EnvironmentsFor tests, create isolated environments to avoid interference between test runs:@@ -292,6 +342,8 @@ Keep the `TempDir` alive for the test: dropping it deletes the database director## When to Use Multiple Environments+<Lang only="python">+| Use Case | Approach ||----------|----------|| Single app, single database | Default environment (no explicit environment needed) |@@ -299,3 +351,17 @@ Keep the `TempDir` alive for the test: dropping it deletes the database director| Apps needing separate databases | Explicit environments with different `db_path` || Multi-tenant isolation | Named environments per tenant || Testing | Temporary isolated environments |++</Lang>++<Lang only="rust">++| Use Case | Approach |+|----------|----------|+| Single app, single database | `App::open(name, db_path)` or `App::builder(name)` (a single-app environment) |+| Multiple apps sharing state | One environment, several `env.app(..)` |+| Apps needing separate databases | Explicit environments with different `db_path` |+| Multi-tenant isolation | One environment per tenant |+| Testing | Temporary isolated environments |++</Lang>diff --git a/docs/src/content/docs/advanced_topics/progress_monitoring.mdx b/docs/src/content/docs/advanced_topics/progress_monitoring.mdxindex 024de071..4dc2e28c 100644--- a/docs/src/content/docs/advanced_topics/progress_monitoring.mdx+++ b/docs/src/content/docs/advanced_topics/progress_monitoring.mdx@@ -3,25 +3,55 @@ title: "*Progress* monitoring"description: >Beyond report_to_stdout β read structured update stats with UpdateHandle.stats()and watch(), and split a run into separately-reported scopes with stats_group().+rust_description: >+ Beyond report_to_stdout β read structured update stats from an UpdateHandle+ with detailed_stats_snapshot() and changed(), and split a run into+ separately-reported scopes with Ctx::stats_group().---import LangTabs from '../../../components/LangTabs.astro';+<Lang only="python">+Most runs only need the basics covered in [App](../programming_guide/app#updating-an-app): awaiting `app.update()` for the result, or the built-in stdout progress display β `report_to_stdout=True` on `app.update_blocking()` (or the CLI), or `await coco.show_progress(handle)` with the async API. `report_to_stdout` accepts a `timedelta` to set the refresh interval (`True` uses the default); `show_progress` takes a `refresh_interval` keyword.-In the Rust SDK the stdout display is `UpdateOptions { report_to_stdout: true, .. }` on `app.update_with_options(..)`; `progress_refresh_interval: Some(duration)` sets the refresh interval. The Rust `cocoindex update` command renders the same per-component lines on stderr when stderr is a terminal, and prints the final `[Stats]` line on stdout; `-q` / `--quiet` turns the stdout output off.+</Lang>++<Lang only="rust">++Most runs only need the basics covered in [App](../programming_guide/app#updating-an-app): awaiting `app.update(..)` for the result, or the built-in stdout progress display β `UpdateOptions { report_to_stdout: true, .. }` on `app.update_with_options(..)`. `progress_refresh_interval: Some(duration)` sets the refresh interval (`None` uses the default). The `cocoindex update` command renders the same per-component lines on stderr when stderr is a terminal, and prints the final `[Stats]` line on stdout; `-q` / `--quiet` turns the stdout output off.++</Lang>Use the structured progress APIs to stream progress from a daemon to a client, build a custom dashboard, or report pipeline phases separately.## Structured update stats+<Lang only="python">+`app.update()` returns an `UpdateHandle`. Besides being awaitable, it exposes the same stats that drive the terminal display β as Python objects you can read while the update runs.-In Rust, `app.start_update(f)` returns an `UpdateHandle<T>`. It starts the update at once; `handle.result().await` waits for the value. The handle has `detailed_stats_snapshot()` (per-component `UpdateStats`), `stats_snapshot()` (the coarse `RunStats`), and `changed().await` to wait for the next change.+</Lang>++<Lang only="rust">++`app.start_update(f)` returns an `UpdateHandle<T>`. It starts the update at once; `handle.result().await` waits for the value. The handle exposes the same stats that drive the terminal display: `detailed_stats_snapshot()` (per-component `UpdateStats`), `stats_snapshot()` (the coarse `RunStats`), and `changed().await` to wait for the next change.++</Lang>### Polling+<Lang only="python">+`handle.stats()` returns a snapshot of the current counters as an `UpdateStats` β or `None` before the handle has started running. It keeps working after completion, returning the final stats:+</Lang>++<Lang only="rust">++`handle.detailed_stats_snapshot()` returns a snapshot of the current counters as an `UpdateStats`. It keeps working after completion, returning the final stats:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/detailed_stats.rs, rust/sdk/cocoindex/src/app.rs (UpdateHandle) */}<LangTabs><Fragment slot="python">@@ -55,12 +85,32 @@ let result = handle.result().await?; // consumes the handle</Fragment></LangTabs>+<Lang only="python">+`app.update()` starts lazily β the handle begins running on the first `await` (or `watch()`), so `stats()` returns `None` until then. To read stats *while* an update is in flight, poll `handle.stats()` from a separate task, or use `watch()` (below) to receive each change as it happens.+</Lang>++<Lang only="rust">++To read stats *while* an update is in flight, loop on `changed()` (below) and read a snapshot after each change.++</Lang>+### Streaming+<Lang only="python">+`handle.watch()` is an async iterator that yields an `UpdateSnapshot` whenever the stats change β `RUNNING` while processing, then a final `READY` snapshot carrying the result:+</Lang>++<Lang only="rust">++`handle.changed().await` waits until the stats change. It returns `Progress::Changed(version)` while the update runs, then `Progress::Done` once it terminates; `result()` then returns the value:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/detailed_stats.rs, rust/sdk/cocoindex/src/app.rs (Progress, UpdateHandle::changed) */}<LangTabs><Fragment slot="python">@@ -98,10 +148,22 @@ There is no snapshot object in Rust: `changed()` wakes you, and `detailed_stats_</Fragment></LangTabs>-On a processing error, `watch()` raises the exception directly β handle it with a normal `try`/`except` around the loop. In Rust, `changed()` and `result()` return the error.+<Lang only="python">++On a processing error, `watch()` raises the exception directly β handle it with a normal `try`/`except` around the loop.In [live mode](../programming_guide/live_mode), `watch()` does not stop at the first `READY`: it keeps yielding `RUNNING` snapshots as live components deliver incremental updates, ending only when the app stops.+</Lang>++<Lang only="rust">++On a processing error, `changed()` and `result()` return the error.++In [live mode](../programming_guide/live_mode), the update does not terminate at the first ready state: `changed()` keeps returning `Progress::Changed` as live components deliver incremental updates, and returns `Progress::Done` only when the app stops.++</Lang>+### Stats types{/* Rust: rust/sdk/cocoindex/src/stats.rs */}@@ -165,11 +227,25 @@ pub enum Progress {## Scoped reports with `stats_group`-By default every component's stats roll up into one report for the whole `app.update()`. For a large pipeline you often want to watch a *part* of it on its own β "indexing the docs tree" separately from "indexing the code tree", or one expensive phase by itself.+By default every component's stats roll up into one report for the whole update. For a large pipeline you often want to watch a *part* of it on its own β "indexing the docs tree" separately from "indexing the code tree", or one expensive phase by itself.++<Lang only="python">`coco.stats_group(title)` opens a scope: everything mounted inside the block aggregates into a **separate** report under `title`, **split out** of the parent (the parent report no longer counts that work β there's no double counting). It's a plain `with` block, used inside a processing component like [`coco.component_subpath`](../programming_guide/processing_component#using-component_subpath-as-a-context-manager):-{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (ctx_stats_group_reports_scoped_child_stats), rust/sdk/cocoindex/src/ctx.rs (stats_group, stats_group_with_options) */}+</Lang>++<Lang only="rust">++`ctx.stats_group(title, f)` opens a scope: `f` runs with a scoped `Ctx`, and everything mounted from that `Ctx` aggregates into a **separate** report under `title`, **split out** of the parent (the parent report no longer counts that work β there's no double counting). It returns the closure's value and a `StatsGroupHandle`:++</Lang>++<RustNote>+A group is a closure, not a `with` block. `stats_group` prints nothing; `stats_group_with_options` takes `StatsGroupOptions` to print the group's progress.+</RustNote>++{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (ctx_stats_group_reports_scoped_child_stats, ctx_stats_group_with_options_reports_scoped_child_stats), rust/sdk/cocoindex/src/ctx.rs (stats_group, stats_group_with_options) */}<LangTabs><Fragment slot="python">@@ -192,7 +268,7 @@ async def app_main(docs_dir, code_dir, target):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 {@@ -205,19 +281,43 @@ let (sum, handle) = ctxOk::<_, cocoindex::Error>(values.into_iter().sum::<i32>())}).await?;-```-In Rust a group is a closure, not a block. `stats_group(title, f)` runs `f` with a scoped `Ctx` and returns `(T, StatsGroupHandle)`: everything mounted from `group_ctx` reports under `title`. `stats_group_with_options(title, StatsGroupOptions { report_to_stdout: true, refresh_interval: None }, f)` also prints the group's progress.+// The same group, with its progress printed to stdout:+let options = cocoindex::StatsGroupOptions {+ report_to_stdout: true,+ refresh_interval: Some(Duration::from_millis(50)),+};+let ((), reported_handle) = ctx+ .stats_group_with_options("Indexing docs (reported)", options, |group_ctx, _handle| async move {+ // mount from `group_ctx` ...+ Ok::<_, cocoindex::Error>(())+ })+ .await?;+```</Fragment></LangTabs>+<Lang only="python">+With `report_to_stdout=True`, the group's progress is also printed to stdout, labeled by its title, alongside the main `report_to_stdout` display without disrupting it. Pass a `timedelta` instead of `True` to set the group's refresh interval; while a terminal display runs, the group is a section of that display and redraws with it.A failure in a group, reported or not, still counts in the final status line of the main display: the run ends in `β Done in 2.0s Β· 3 failed`, even though the group's rows stay out of the main report.The block yields a `StatsGroupHandle` with the same `stats()` and `watch()` as `UpdateHandle` (a group has no return value, so there's no `result()`):+</Lang>++<Lang only="rust">++With `report_to_stdout: true`, the group's progress is also printed to stdout, labeled by its title, alongside the main `report_to_stdout` display without disrupting it. `refresh_interval: Some(duration)` sets the group's refresh interval; while a terminal display runs, the group is a section of that display and redraws with it.++A failure in a group, reported or not, still counts in the final status line of the main display: the run ends in `β Done in 2.0s Β· 3 failed`, even though the group's rows stay out of the main report.++The `StatsGroupHandle` has the same `stats_snapshot()`, `detailed_stats_snapshot()` and `changed()` as `UpdateHandle` (the closure's value is returned beside it, so there's no `result()`):++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (ctx_stats_group_reports_scoped_child_stats) */}<LangTabs><Fragment slot="python">@@ -254,7 +354,18 @@ The closure also receives the handle as its second argument, so the body can rea### Semantics+<Lang only="python">+- **Synchronous and non-blocking.** It's a regular `with` (not `async with`), even though the body `await`s mounts. Leaving the block does **not** wait for the work to finish β it only marks where member registration stops. The group becomes `READY` asynchronously once the block has exited *and* every component mounted inside it is ready; observe that via `sg.watch()` / `sg.stats()`.++</Lang>++<Lang only="rust">++- **Non-blocking.** Returning from the closure does **not** wait for background work mounted inside it (`mount`, `mount_each`) to finish β it only marks where member registration stops. The group becomes ready asynchronously once the closure has returned *and* every component mounted inside it is ready; observe that via `handle.changed()` / `handle.detailed_stats_snapshot()`.++</Lang>+- **Identity is unchanged.** Grouping only redirects where stats are *reported*. Component paths, change detection, target-state ownership, and the run's overall completion are unaffected β the grouped components are still ordinary children of the surrounding component.- **Nesting.** Groups may nest. The **innermost** group owns a mount's stats; an outer group's readiness still waits for the inner group's work to finish.-- **Live members.** A group containing [live components](./live_component) becomes `READY` after their initial catch-up and reports their ongoing incremental stats, just like the root.+- **Live members.** A group containing [live components](./live_component) becomes ready after their initial catch-up and reports their ongoing incremental stats, just like the root.diff --git a/docs/src/content/docs/advanced_topics/timeouts.mdx b/docs/src/content/docs/advanced_topics/timeouts.mdxindex 47426bf6..d3b4ffbf 100644--- a/docs/src/content/docs/advanced_topics/timeouts.mdx+++ b/docs/src/content/docs/advanced_topics/timeouts.mdx@@ -4,12 +4,30 @@ description: >Use `coco.timeout()` to put a time budget around a piece of processing βone file, one LLM call β with cooperative checks, deadline-aware retries,and clean time-boxing of whole updates.+rust_description: >+ Use `Ctx::with_timeout` to put a time budget around a piece of processing β+ one file, one LLM call β with cooperative checks, deadline-aware retries,+ and clean time-boxing of whole updates.---import LangTabs from '../../../components/LangTabs.astro';-Use `coco.timeout()` when a piece of CocoIndex work should stop after a time budget. In the Rust SDK the deadline lives on the `Ctx`: `ctx.with_timeout(duration)` returns a scoped `Ctx`, and the work you call with that `Ctx` sees the deadline. There is no ambient timeout in Rust: the budget follows the `Ctx` you pass.+<Lang only="python">++Use `coco.timeout()` when a piece of CocoIndex work should stop after a time budget.++</Lang>++<Lang only="rust">-The timeout is **cooperative**: CocoIndex checks the time at safe points and raises `coco.DeadlineExceededError` when the deadline has passed. Enforcement is best-effort beyond that β CocoIndex may additionally cancel an in-flight `await` where that is known to be safe (the built-in retry helpers do), but your own code inside an `await`, such as an HTTP request or database query, is generally not interrupted. Use that library's own timeout for individual I/O calls.+Use `ctx.with_timeout(duration)` when a piece of CocoIndex work should stop after a time budget. The deadline lives on the `Ctx`: `with_timeout` returns a scoped `Ctx`, and the work you call with that `Ctx` sees the deadline.++</Lang>++<RustNote>+There is no ambient timeout block like Python's `with coco.timeout(...)`: the budget follows the `Ctx` you pass. A call made with the unscoped `Ctx` does not see it.+</RustNote>++The timeout is **cooperative**: CocoIndex checks the time at safe points and <Lang only="python">raises `coco.DeadlineExceededError`</Lang><Lang only="rust">returns `Error::DeadlineExceeded`</Lang> when the deadline has passed. Enforcement is best-effort beyond that β CocoIndex may additionally cancel an in-flight `await` where that is known to be safe (the built-in retry helpers do), but your own code inside an <Lang only="python">`await`</Lang><Lang only="rust">`.await`</Lang>, such as an HTTP request or database query, is generally not interrupted. Use that library's own timeout for individual I/O calls.## Quick start@@ -53,9 +71,9 @@ async fn process_file(ctx: &Ctx, file: FileEntry, target: DirTarget) -> Result<(</Fragment></LangTabs>-If the budget runs out, the component fails with `coco.DeadlineExceededError` (Rust: `Error::DeadlineExceeded`) like any other processor error: nothing external is written for it, nothing is memoized, and the next update retries it cleanly.+If the budget runs out, the component fails with <Lang only="python">`coco.DeadlineExceededError`</Lang><Lang only="rust">`Error::DeadlineExceeded`</Lang> like any other processor error: nothing external is written for it, nothing is memoized, and the next update retries it cleanly.-Nested timeout blocks use the shorter remaining budget:+Nested timeouts use the shorter remaining budget:{/* Rust: rust/sdk/cocoindex/tests/deadline.rs (rust_sdk_deadline_conformance_subset) */}<LangTabs>@@ -96,6 +114,8 @@ let narrower = outer.with_timeout(Duration::from_secs(1));A timeout follows work the caller is directly waiting for. It does not follow background work or shared work.+<Lang only="python">+| Code shape | What happens || --- | --- || `with coco.timeout(...): app.update()` | The root processor inherits the timeout (see [Time-boxing a whole update](#time-boxing-a-whole-update-programmatic-callers)). |@@ -107,22 +127,26 @@ A timeout follows work the caller is directly waiting for. It does not follow ba| Target writes and connector sink calls | Do not inherit the processor timeout. Once processing has succeeded, CocoIndex lets target synchronization finish consistently. || Long loop inside a processor | Add `coco.check_cancellation()` where you want the loop to stop promptly. |-The same rule holds in the Rust SDK, where the deadline is carried by the `Ctx`:+</Lang>-| Code shape (Rust) | What happens |+<Lang only="rust">++| Code shape | What happens || --- | --- || `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.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. |+| Batched function body | A physical batch does not inherit any individual caller's deadline, because a batch can contain work from multiple callers. A batched body that needs a bound carries its own β `ApiEmbedder`, for example, bounds each request with its own timeout (`with_timeout`). |+| Target writes and connector sink calls | Do not inherit the processor deadline. Once processing has succeeded, CocoIndex lets target synchronization finish consistently. || Long loop inside a processor | Add `ctx.check_cancellation()?` where you want the loop to stop promptly. |+</Lang>+## Foreground child work-Use `use_mount()` when the parent depends on the child's value. The timeout applies to both parent and child:+Use <Lang only="python">`use_mount()`</Lang><Lang only="rust">`ctx.scope(..)` or `use_mount!`</Lang> when the parent depends on the child's value. The timeout applies to both parent and child:{/* Rust: rust/sdk/cocoindex/tests/deadline.rs (sdk_deadline_use_mount_inherit) */}<LangTabs>@@ -176,11 +200,21 @@ app.update(move |ctx| async move {</Fragment></LangTabs>+<Lang only="python">+If the deadline passes while `parse_file()` is in `file.read_text()`, CocoIndex does not interrupt that await. The timeout is observed when control reaches the next CocoIndex check, such as `coco.check_cancellation()` or the function return.+</Lang>++<Lang only="rust">++If the deadline passes while `parse_file` is inside an `.await`, CocoIndex does not interrupt it. The timeout is observed when control reaches the next CocoIndex check, such as `ctx.check_cancellation()?`.++</Lang>+## Background child work-Use `mount()` or `mount_each()` when the child is independent background work. The parent's timeout can stop the parent from waiting forever, but it does not become the child's timeout:+Use <Lang only="python">`mount()` or `mount_each()`</Lang><Lang only="rust">`ctx.mount(..)` or `ctx.mount_each(..)`</Lang> when the child is independent background work. The parent's timeout can stop the parent from waiting forever, but it does not become the child's timeout:{/* Rust: rust/sdk/cocoindex/src/ctx.rs (Ctx::mount, ComponentMountHandle::ready), rust/sdk/cocoindex/tests/mount.rs */}<LangTabs>@@ -233,17 +267,26 @@ If the parent times out while waiting for `handle.ready()`, the timeout belongsThe timing contract is deliberately loose:+<Lang only="python">+- Any CocoIndex-managed call **may** raise `coco.DeadlineExceededError` if the deadline passes before it returns.- CocoIndex checkpoints β `coco.check_cancellation()`, calling a `@coco.fn`, engine calls such as `coco.use_mount()` β **guarantee** to raise if the deadline has already passed when they are called.-In Rust the error is `Error::DeadlineExceeded`; `err.is_deadline_exceeded()` tests for it. The checkpoints are `ctx.check_cancellation()`, a memoized `#[cocoindex::function]` call, and engine calls such as `ctx.scope(..)` and `ctx.mount(..)`.+</Lang>-Don't rely on the exact point where the error is raised. It can move between versions, and enforcement can get tighter where cancelling is safe (the built-in retry helpers already cancel an in-flight attempt at the deadline).+<Lang only="rust">++- Any CocoIndex-managed call **may** return `Error::DeadlineExceeded` if the deadline passes before it returns; `err.is_deadline_exceeded()` tests for it.+- CocoIndex checkpoints β `ctx.check_cancellation()`, a memoized `#[cocoindex::function]` call, engine calls such as `ctx.scope(..)` and `ctx.mount(..)` β **guarantee** to return it if the deadline has already passed when they are called.++</Lang>++Don't rely on the exact point where the error is <Lang only="python">raised</Lang><Lang only="rust">returned</Lang>. It can move between versions, and enforcement can get tighter where cancelling is safe (the built-in retry helpers already cancel an in-flight attempt at the deadline).What you can rely on is the outcome:- A processor run that times out applies no target writes and memoizes nothing; the next update retries it cleanly.-- Completed work stays completed: committed components, finished `coco.map()` items, and in-progress target synchronization are never rolled back or interrupted by a timeout.+- Completed work stays completed: committed components, finished <Lang only="python">`coco.map()`</Lang><Lang only="rust">`ctx.map(..)`</Lang> items, and in-progress target synchronization are never rolled back or interrupted by a timeout.## Add checks in long processors@@ -282,6 +325,8 @@ This makes the loop stop near the deadline instead of waiting until the whole fu## Long I/O still needs its own timeout+<Lang only="python">+`coco.timeout()` does not replace client-level timeouts:```python@@ -300,11 +345,22 @@ Think of the two budgets as complementary:- client timeouts bound one external call- `coco.timeout()` bounds CocoIndex work between safe checks-The Rust SDK is the same: an `.await` on an HTTP client or a database driver is not interrupted. Give that client its own timeout, and call `ctx.check_cancellation()?` after it returns.+</Lang>++<Lang only="rust">++`ctx.with_timeout(..)` does not replace client-level timeouts: an `.await` on an HTTP client or a database driver is not interrupted. Give that client its own timeout, and call `ctx.check_cancellation()?` after it returns.++Think of the two budgets as complementary:++- client timeouts bound one external call+- the `Ctx` deadline bounds CocoIndex work between safe checks++</Lang>## Time-boxing a whole update (programmatic callers)-When you call `app.update()` yourself and the surrounding environment has its own clock (a CI job, a serverless handler, a shared cron window), you can put the budget around the whole update:+When you run an update yourself and the surrounding environment has its own clock (a CI job, a serverless handler, a shared cron window), you can put the budget around the whole update:{/* Rust: rust/sdk/cocoindex/tests/deadline.rs (update_with_options), rust/sdk/cocoindex/src/app.rs (UpdateOptions) */}<LangTabs>@@ -354,10 +410,12 @@ if let Err(err) = &result {</Fragment></LangTabs>-Because components commit independently and the engine rolls forward, a whole-update timeout never wastes completed work: everything that finished is committed and stays committed; the timeout only stops new progress, and the **next update resumes where this one left off**. `with coco.timeout(timedelta(minutes=10)): app.update()` means "index as much as possible in ten minutes, cleanly."+Because components commit independently and the engine rolls forward, a whole-update timeout never wastes completed work: everything that finished is committed and stays committed; the timeout only stops new progress, and the **next update resumes where this one left off**. <Lang only="python">`with coco.timeout(timedelta(minutes=10)): app.update()`</Lang><Lang only="rust">An update with `timeout: Some(Duration::from_secs(10 * 60))`</Lang> means "index as much as possible in ten minutes, cleanly."## Retries+<Lang only="python">+Retry helpers distinguish two kinds of limit:- **Attempt caps owned by the call site** β exhausting one re-raises the last transient error, so your normal error handling still applies.@@ -365,6 +423,18 @@ Retry helpers distinguish two kinds of limit:Adding a timeout therefore never increases retry effort, and removing one never decreases it. No retry attempt starts past any limit, no result is accepted past the deadline, and backoff sleeps never exceed the remaining time. Built-in operations (`LlmPairResolver`, LiteLLM embedding retries) share one helper with these semantics.+</Lang>++<Lang only="rust">++The built-in API operations (`ApiEmbedder`, `ApiTranscriber`, `ApiChatClient` and the `LlmPairResolver` built on it) retry transient failures inside one bound per request: the op's own `timeout` (10 minutes by default, set with `with_timeout`), shortened to the `Ctx`'s remaining deadline when that is earlier. A `Ctx` deadline can only shorten the bound, never extend it.++Fast failures (HTTP 408, 409, 425, 429, 5xx, a refused or reset connection) are retried with exponential backoff. A request that times out is not retried, and no backoff sleep runs past the bound. When the `Ctx` deadline is what ran out, the op returns `Error::DeadlineExceeded`; when the op's own timeout ran out, it returns an error that names the request.++The SDK has no public retry helper for your own calls. Bound them with the client's timeout and `ctx.remaining_deadline()`.++</Lang>+## API{/* Rust: rust/sdk/cocoindex/src/ctx.rs (with_timeout, with_timeout_scope, check_cancellation, has_deadline, remaining_deadline), rust/sdk/cocoindex/src/error.rs */}