Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
docs(programming-guide): Rust pages for function and serialization (#2755)
LJ π₯₯π΄f3d14fa9b4a9
diff --git a/docs/src/content/docs/programming_guide/function.mdx b/docs/src/content/docs/programming_guide/function.mdxindex 89fb6d2a..664ef01b 100644--- a/docs/src/content/docs/programming_guide/function.mdx+++ b/docs/src/content/docs/programming_guide/function.mdx@@ -68,36 +68,50 @@ The Rust SDK has no sync/async adapter (`as_async`, `as_sync`): a `#[cocoindex::</Lang>-Decorating a function tells CocoIndex that calls to it are part of the incremental update engine. You still write normal Python, but CocoIndex can now:+<Lang only="python">Decorating</Lang><Lang only="rust">Marking</Lang> a function tells CocoIndex that calls to it are part of the incremental update engine. You still write normal <Lang only="python">Python</Lang><Lang only="rust">Rust</Lang>, but CocoIndex can now:- Detect when inputs or code have changed (change detection)- Skip work when nothing has changed (memoization)-This is what lets CocoIndex avoid rerunning expensive steps on every `app.update()`. See [Processing Component](./processing_component) for how decorated functions are mounted at component paths.+This is what lets CocoIndex avoid rerunning expensive steps on every `app.update()`. See [Processing Component](./processing_component) for how <Lang only="python">decorated</Lang><Lang only="rust">marked</Lang> functions are mounted at component paths.-If you don't need any of the above for a helper, keep it as a plain Python function.+If you don't need any of the above for a helper, keep it as a plain <Lang only="python">Python</Lang><Lang only="rust">Rust</Lang> function.## Change detection and memoization-Every `@coco.fn` function participates in CocoIndex's change detection system. With `memo=True`, the function's results are cached and reused when nothing has changed. These two mechanisms (detecting changes and acting on them) work together to enable incremental updates. For the big-picture view (how memoization skips unchanged work across both input and code changes) see the [Function memoization section in Core Concepts](./core_concepts#function-memoization-skip-unchanged-computations).+Every <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> function participates in CocoIndex's change detection system. With <Lang only="python">`memo=True`</Lang><Lang only="rust">`memo`</Lang>, the function's results are cached and reused when nothing has changed. These two mechanisms (detecting changes and acting on them) work together to enable incremental updates. For the big-picture view (how memoization skips unchanged work across both input and code changes) see the [Function memoization section in Core Concepts](./core_concepts#function-memoization-skip-unchanged-computations).:::tip[Mental model]-A function's behavior is determined by its **logic** (source code, [`deps`](#deps), [`version`](#version)), its **inputs** (arguments), and the **context values** it reads via [`use_context()`](./context#retrieving-values). If none of those have changed, a memoized function returns its cached result without re-executing.+A function's behavior is determined by its **logic** (source code, [`deps`](#deps), [`version`](#version)), its **inputs** (arguments), and the **context values** it reads via <Lang only="python">[`use_context()`](./context#retrieving-values)</Lang><Lang only="rust">[`ctx.get_key()`](./context#retrieving-values)</Lang>. If none of those have changed, a memoized function returns its cached result without re-executing.:::### Change detectionCocoIndex detects three kinds of changes:+<Lang only="python">+**Logic changes** β a function's *logic* is its own source code (or, when you set [`version`](#version), that integer **instead of** the source), plus any [`deps`](#deps) values. Tracked by `@coco.fn`. Logic fingerprints **propagate transitively** up the call chain, following *runtime invocations* rather than the static call graph: every `@coco.fn` function reached during a memoized call β directly, or through plain undecorated helpers β contributes its logic to that call. So if `foo` (memoized) calls `bar` (also `@coco.fn`-decorated, with or without `memo=True`) and `bar`'s logic changes, `foo`'s memo is invalidated; undecorated helpers in between don't break the chain. What the decorator buys is having a function's *own* logic tracked: an undecorated helper is invisible to change detection, so editing it invalidates nothing. This is why `@coco.fn` matters for **any** function in the call chain, not just memoized ones β see [Common patterns](#common-patterns) and the [FAQ](../faq#how-does-logic-change-propagation-work). To stop propagation deliberately, set [`logic_tracking`](#logic_tracking) to `"self"` or `None`.**Input changes** β the function's arguments. Tracked by `@coco.fn`. When you call a function with different arguments, the fingerprints change. Input fingerprints do not propagate transitively.**Context changes** β [context values](./context) with [`detect_change=True`](./context#change-detection). Tracked by [`use_context()`](./context#retrieving-values) at the call site β independent of `@coco.fn`. Context reads propagate transitively: if a memoized `foo` calls `bar` and `bar` reads a change-detected context value, then changing that value invalidates `foo`'s memo too β even though `foo` itself never called `use_context()`. What matters is whether the key was read *anywhere* during the memoized call, not where in the call chain.+</Lang>++<Lang only="rust">++**Logic changes** β a function's *logic* is its own body (or, when you set [`version`](#version), that integer **instead of** the body), plus any [`deps`](#deps) value. Tracked by `#[cocoindex::function]`. Logic fingerprints **propagate transitively** up the call chain, following *runtime invocations* rather than the static call graph: every `#[cocoindex::function]` reached during a memoized call β directly, or through plain unmarked helpers that pass the `Ctx` on β contributes its logic to that call. So if `foo` (memoized) calls `bar` (also `#[cocoindex::function]`, with or without `memo`) and `bar`'s logic changes, `foo`'s memo is invalidated; unmarked helpers in between don't break the chain. What the attribute buys is having a function's *own* logic tracked: an unmarked helper is invisible to change detection, so editing it invalidates nothing. This is why `#[cocoindex::function]` matters for **any** function in the call chain, not just memoized ones β see [Common patterns](#common-patterns) and the [FAQ](../faq#how-does-logic-change-propagation-work). To stop propagation deliberately, set [`logic_tracking`](#logic_tracking) to `"self"` or `"none"`.++**Input changes** β the function's arguments. Tracked by `#[cocoindex::function]`. When you call a function with different arguments, the fingerprints change. Input fingerprints do not propagate transitively.++**Context changes** β [context values](./context) whose key is declared with [`detect_change`](./context#change-detection). Tracked by [`ctx.get_key()`](./context#retrieving-values) at the call site β independent of `#[cocoindex::function]`. Context reads propagate transitively: if a memoized `foo` calls `bar` and `bar` reads a change-detected context value, then changing that value invalidates `foo`'s memo too β even though `foo` itself never called `get_key()`. What matters is whether the key was read *anywhere* during the memoized call, not where in the call chain.++</Lang>+### Memoization-With `memo=True`, the function's result is cached. On subsequent calls, if no logic, input, or read context values have changed, the cached result is reused without executing the function body β it carries over [target states](./target_state) declared during the function's previous invocation and returns its previous return value.+With <Lang only="python">`memo=True`</Lang><Lang only="rust">`memo`</Lang>, the function's result is cached. On subsequent calls, if no logic, input, or read context values have changed, the cached result is reused without executing the function body β it carries over [target states](./target_state) declared during the function's previous invocation and returns its previous return value.{/* Rust: rust/sdk/SHOWCASE.md "Define functions", verified against rust/sdk/cocoindex/tests/memo_deps.rs */}<LangTabs>@@ -121,11 +135,13 @@ async fn parse_file(_ctx: &Ctx, file: FileEntry) -> Result<Vec<Section>> {}```-In Rust, every argument of a `memo` function is part of the key through its `MemoInput` implementation, and the return type must implement `serde::Serialize` and `Deserialize`. See [Serialization](./serialization).+Every argument of a `memo` function is part of the key: through its `MemoInput` implementation, or by its serialized value for a type that is only `Serialize` (such as a target handle). The return type must implement `serde::Serialize` and `Deserialize`. See [Serialization](./serialization).</Fragment></LangTabs>+<Lang only="python">+:::info[Type annotations]Add a **return type annotation** to memoized functions so CocoIndex can properly reconstruct cached values. Without a type annotation, cached values may deserialize as basic Python types (`dict`, `list`, etc.) instead of their original types. See [Serialization](./serialization) for details on supported types.:::@@ -137,9 +153,26 @@ A memoized function:- **Cannot mount child components when called directly** (`coco.mount(...)` / `coco.use_mount(...)` inside the body of a memoized function invoked as a plain call). Mounting is a side effect the call's cache cannot replay; CocoIndex raises an error if a directly-called memoized function attempts it. The restriction applies to the call, not the function β the fix, which the error message itself suggests, is to **mount the memoized function as a component**: a [memoized component](./processing_component#memoized-components) may mount children freely (a cache hit carries its child mounts over along with its target states). Alternatively, drop `memo=True`, or restructure so the mount happens in a non-memoized caller.:::+</Lang>++<Lang only="rust">++:::caution[`memo` constraints]+A memoized function:++- **Runs inside a [processing component](./processing_component).** It takes the component's `&Ctx`, and a `Ctx` exists only inside a running app, so the cache is always in effect.+- **Cannot mount child components when called directly** (`mount!`, `use_mount!` or `ctx.scope(..)` inside the body of a memoized function invoked as a plain call). Mounting is a side effect the call's cache cannot replay; the call fails with an error if a directly-called memoized function attempts it. The restriction applies to the call, not the function β the fix, which the error message itself suggests, is to **mount the memoized function as a component**: a [memoized component](./processing_component#memoized-components) may mount children freely (a cache hit carries its child mounts over along with its target states). Alternatively, drop `memo`, or restructure so the mount happens in a non-memoized caller.+:::++</Lang>+#### Cache-hit semantics-When a memoized function's cache hits, its **body does not run** β and neither do any nested `@coco.fn` calls inside it. The cached output is replayed directly: the previous return value is returned, and any target states the function declared on its previous run are carried over.+When a memoized function's cache hits, its **body does not run** β and neither do any nested <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> calls inside it. The cached output is replayed directly: the previous return value is returned, and any target states the function declared on its previous run are carried over.++{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs (`read_version`, `outer_read_version`) */}+<LangTabs>+<Fragment slot="python">```python@coco.fn(memo=True)@@ -160,15 +193,54 @@ result = await outer("hello")result = await outer("hello")```+</Fragment>+<Fragment slot="rust">++```rust+static OUTER_CALLS: AtomicUsize = AtomicUsize::new(0);+static INNER_CALLS: AtomicUsize = AtomicUsize::new(0);++#[cocoindex::function(memo)]+async fn read_version(ctx: &Ctx) -> Result<String> {+ INNER_CALLS.fetch_add(1, Ordering::SeqCst);+ Ok(ctx.get_key(version_key())?.clone())+}++#[cocoindex::function(memo)]+async fn outer_read_version(ctx: &Ctx) -> Result<String> {+ OUTER_CALLS.fetch_add(1, Ordering::SeqCst);+ read_version(ctx).await+}++// First update: both bodies run (OUTER_CALLS == 1, INNER_CALLS == 1).+// Second update with the same context value: neither counter moves β+// outer's cached value is returned directly, and read_version is not invoked.+```++</Fragment>+</LangTabs>+Propagation (logic, `deps`, context) is recorded during the **previous** invocation and replayed on cache lookup. You don't need to model the internals β change anything that affects behavior and the cache invalidates correctly.+<Lang only="python">+:::note[Exceptions and the cache]If a memoized function raises, no cache entry is written for that call. The next invocation with the same inputs sees a cache miss and re-executes the body β exceptions never poison the cache, so you don't need to wrap calls defensively.:::+</Lang>++<Lang only="rust">++:::note[Errors and the cache]+If a memoized function returns an `Err`, no cache entry is written for that call. The next invocation with the same inputs sees a cache miss and re-executes the body β errors never poison the cache, so you don't need to wrap calls defensively.+:::++</Lang>+#### When to memoize-**Cost:** A directly-called memoized function's cache entry must store everything needed to serve a hit β the return value, plus the *path* of every [target state](./target_state) it declared during the call (the state values themselves stay in the enclosing component's tracking; the recorded paths are what keep those states alive on a hit). Large return values, or a call that declares many target states, mean large entries. (A function *mounted* as a component avoids the per-state paths entirely: a [memoized component](./processing_component#memoized-components)'s entry holds fingerprints plus its return value β `None` for a typical mounted declarer.)+**Cost:** A directly-called memoized function's cache entry must store everything needed to serve a hit β the return value, plus the *path* of every [target state](./target_state) it declared during the call (the state values themselves stay in the enclosing component's tracking; the recorded paths are what keep those states alive on a hit). Large return values, or a call that declares many target states, mean large entries. (A function *mounted* as a component avoids the per-state paths entirely: a [memoized component](./processing_component#memoized-components)'s entry holds fingerprints plus its return value β <Lang only="python">`None`</Lang><Lang only="rust">`()`</Lang> for a typical mounted declarer.)**Benefit:** Memoization saves more when:@@ -191,31 +263,31 @@ A 1536-dim float32 vector is ~6 KB. An embedding memo under content-hash-keyed c### Controlling change detection scope-Three parameters on `@coco.fn` let you customize how logic changes are detected:+Three <Lang only="python">parameters on `@coco.fn`</Lang><Lang only="rust">arguments of `#[cocoindex::function]`</Lang> let you customize how logic changes are detected:- **`logic_tracking`** β controls the *scope* of automatic logic change detection- **`version`** β provides explicit manual control over when dependent memos are invalidated-- **`deps`** β declares external values (e.g. a module-level prompt string) as part of the function's logic, so changing them invalidates dependent memos+- **`deps`** β declares external values (e.g. a <Lang only="python">module-level prompt string</Lang><Lang only="rust">prompt `const`</Lang>) as part of the function's logic, so changing them invalidates dependent memos-These parameters control logic fingerprinting. Data fingerprinting (for arguments, `deps` values, and context values) is controlled by the objects themselves (see [Memoization Keys & States](../advanced_topics/memoization_keys)). Three more tools cover what a decorator parameter cannot: [`coco.LogicDep` / `coco.use_logic_dep`](#per-call-dependencies-logicdep-and-use_logic_dep) for a dependency decided per call, [`coco.DataDep` / `coco.use_data_dep`](#data-dependencies-datadep-and-use_data_dep) for data a body reads that is not among its arguments, and [`coco.logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers) for callbacks that cross a `"self"` boundary.+These <Lang only="python">parameters</Lang><Lang only="rust">arguments</Lang> control logic fingerprinting. Data fingerprinting (for arguments, `deps` values, and context values) is controlled by the objects themselves (see [Memoization Keys & States](../advanced_topics/memoization_keys)). Three more tools cover what <Lang only="python">a decorator parameter</Lang><Lang only="rust">an attribute argument</Lang> cannot: <Lang only="python">[`coco.LogicDep` / `coco.use_logic_dep`](#per-call-dependencies-logicdep-and-use_logic_dep)</Lang><Lang only="rust">[`LogicDep` / `ctx.use_logic_dep`](#per-call-dependencies-logicdep-and-use_logic_dep)</Lang> for a dependency decided per call, <Lang only="python">[`coco.DataDep` / `coco.use_data_dep`](#data-dependencies-datadep-and-use_data_dep)</Lang><Lang only="rust">[`DataDep` / `ctx.use_data_dep`](#data-dependencies-datadep-and-use_data_dep)</Lang> for data a body reads that is not among its arguments, and <Lang only="python">[`coco.logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers)</Lang><Lang only="rust">[`ctx.logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers)</Lang> for callbacks that cross a `"self"` boundary.#### `logic_tracking`-The `logic_tracking` parameter controls whether and how logic changes are detected:+The `logic_tracking` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> controls whether and how logic changes are detected:-- **`"full"` (default):** Track this function's logic AND all transitively called `@coco.fn` functions' logic. A change anywhere in the call chain invalidates dependent memos.+- **`"full"` (default):** Track this function's logic AND all transitively called <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> functions' logic. A change anywhere in the call chain invalidates dependent memos.- **`"self"`:** Track only this function's own logic β its fingerprint still propagates to its callers, but the logic of functions it calls does not propagate through it.-- **`None`:** Don't track logic through this function at all β neither its own logic nor its callees' reaches its callers.+- **<Lang only="python">`None`</Lang><Lang only="rust">`"none"`</Lang>:** Don't track logic through this function at all β neither its own logic nor its callees' reaches its callers.These settings govern nested *function calls*. A [mounted child component](./processing_component) is tracked through the component tree instead, so its logic reaches the parent regardless of the parent's `logic_tracking`.:::caution[Adopting tracking later does not re-store existing memo entries]-A memo entry records only the logic fingerprints its writer offered when it was stored. Decorating a function with `@coco.fn` after memoized callers have stored entries that ran it, or raising its `logic_tracking` from `None`, leaves those entries valid: nothing in them can fail. Ship such a change together with a [`version`](#version) bump or a memoization-key change on the memoized callers, so their entries are stored again with the new fingerprints.+A memo entry records only the logic fingerprints its writer offered when it was stored. <Lang only="python">Decorating a function with `@coco.fn`</Lang><Lang only="rust">Marking a function with `#[cocoindex::function]`</Lang> after memoized callers have stored entries that ran it, or raising its `logic_tracking` from <Lang only="python">`None`</Lang><Lang only="rust">`"none"`</Lang>, leaves those entries valid: nothing in them can fail. Ship such a change together with a [`version`](#version) bump or a memoization-key change on the memoized callers, so their entries are stored again with the new fingerprints.:::#### `version`-The `version` parameter lets you explicitly invalidate dependent memos by bumping an integer:+The `version` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> lets you explicitly invalidate dependent memos by bumping an integer:{/* Rust: rust/sdk/cocoindex_macros/src/lib.rs (`#[cocoindex::function]` doc), rust/sdk/cocoindex/tests/memo_deps.rs */}<LangTabs>@@ -245,7 +317,7 @@ Setting `version` makes the integer the function's logic **instead of** its sour#### `deps`-The `deps` parameter declares external value(s) the function logic depends on but that aren't visible in its body β for example a prompt string or a model identifier defined at module scope. When the value changes, the function's logic fingerprint changes and dependent memos are invalidated, exactly as if the function body had been edited.+The `deps` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> declares external value(s) the function logic depends on but that aren't visible in its body β for example a prompt string or a model identifier defined at <Lang only="python">module scope</Lang><Lang only="rust">item level</Lang>. When the value changes, the function's logic fingerprint changes and dependent memos are invalidated, exactly as if the function body had been edited.{/* Rust: rust/sdk/SHOWCASE.md "Declare dependencies beyond the arguments", verified against rust/sdk/cocoindex/tests/memo_deps.rs */}<LangTabs>@@ -276,7 +348,7 @@ async fn summarize(_ctx: &Ctx, text: &str) -> Result<String> {</Fragment></LangTabs>-For multiple dependencies, pass a tuple or dict:+For multiple dependencies, pass a <Lang only="python">tuple or dict</Lang><Lang only="rust">tuple</Lang>:{/* Rust: rust/sdk/cocoindex/tests/memo_deps.rs (`deps = (PROMPT, ...)`) */}<LangTabs>@@ -299,25 +371,49 @@ def summarize(text: str) -> str:async fn summarize(_ctx: &Ctx, text: &str) -> Result<String> { /* ... */ }```-In Rust, `deps = <expr>` takes one expression that implements `MemoInput`; a tuple groups several values.+`deps = <expr>` takes one expression whose type implements `MemoInput`; a tuple groups several values.</Fragment></LangTabs>+<Lang only="python">+The value is canonicalized through the [memoization-key pipeline](../advanced_topics/memoization_keys), which honors `__coco_memo_key__()`, registered memo key functions, and the standard handling for primitives, dataclasses, and Pydantic models.:::caution[Snapshotted at decoration time]`deps` is evaluated **once** when the decorator is applied (typically at module import), not re-evaluated per call. For per-call or per-instance values (instance attributes in a bound method, request-scoped config, anything that changes at runtime) pass them as regular function arguments instead, so the memoization layer observes each new value.:::-In Rust, `deps = <expr>` is fingerprinted once per process, the first time the function's logic is read. A later change to the value is not observed. Pass per-call values as arguments, as in Python.-`deps` requires `logic_tracking` to be enabled; combining `deps=<value>` with `logic_tracking=None` raises `ValueError`.+</Lang>++<Lang only="rust">++The value is fingerprinted through its [`MemoInput`](../advanced_topics/memoization_keys) implementation, as an argument is.++:::caution[Fingerprinted once per process]+`deps = <expr>` is evaluated **once** per process, the first time the function's logic is read, not per call. A later change to the value within the process is not observed. Pass per-call values (request-scoped config, anything that changes at runtime) as regular function arguments instead, so the memoization layer observes each new value.+:::++`deps` requires `logic_tracking` to be enabled; combining `deps = <expr>` with `logic_tracking = "none"` is a compile error.++</Lang>+#### Per-call dependencies: `LogicDep` and `use_logic_dep`+<Lang only="python">+`deps` describes the whole function: every call depends on the value. Some dependencies are decided per call. A tree walk's `visit_file` depends on the parser of *that file's* language, and a change to one parser should re-run the files it parsed, not every file the walk saw. `coco.LogicDep` declares such a value once, at module import; `coco.use_logic_dep` records it as part of the current call's logic:+</Lang>++<Lang only="rust">++`deps` describes the whole function: every call depends on the value. Some dependencies are decided per call. A tree walk's `visit_file` depends on the parser of *that file's* language, and a change to one parser should re-run the files it parsed, not every file the walk saw. `LogicDep::new` declares such a value once, before the app runs; `ctx.use_logic_dep` records it as part of the current call's logic:++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md "Declare dependencies beyond the arguments", verified against rust/sdk/cocoindex/tests/memo_deps.rs (`LogicDep::new`, `ctx.use_logic_dep`) */}<LangTabs><Fragment slot="python">@@ -352,17 +448,33 @@ async fn visit_file(ctx: &Ctx, file: FileEntry) -> Result<Vec<Symbol>> {}```-In Rust, construct a `LogicDep` in a `static LazyLock` so it exists before the app runs, and record it per call with `ctx.use_logic_dep(&DEP)?`. `LogicDep::new` takes any `MemoInput` value.+`LogicDep::new` takes any `MemoInput` value. Record the dependency per call with `ctx.use_logic_dep(&DEP)?`.</Fragment></LangTabs>A recorded dependency travels exactly like the function's own fingerprint: into the entry of a memoized caller, onward through `"full"` callers, hidden by a `"self"` caller above unless the call is carried by [`logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers), and from a [mounted component](./processing_component) into every ancestor component's entry. (A memoized callee that hits re-offers its stored entry to the caller whole, and that rides to the enclosing component regardless of modes, so a `"self"` caller may record more after a hit than after a miss, never less.) When a later release constructs the `LogicDep` with a new value, only the entries that recorded the old one are invalidated: in the example, a parser's new version re-runs its files and the directories above them, and every other subtree is reused. It is recorded whatever the function's own `logic_tracking` is: it describes the call, not the function's code.+<Lang only="python">+:::caution[Construct at import, never lazily]A memo entry is validated against the dependencies registered in the process at that moment. A `LogicDep` constructed on first use registers too late, so entries recorded with it are evicted when probed before that first use; one constructed per call is released too early, so they are evicted every pass. Neither is stale data, only memoization that silently stops working. Build every `LogicDep` before any component runs, at module import; constructing one inside a component context raises.:::+</Lang>++<Lang only="rust">++:::caution[Construct before the app runs, never per call]+A memo entry is validated against the dependencies registered in the process at that moment. A `LogicDep` is registered while it (or a clone) lives. One constructed on first use registers too late, so entries recorded with it are evicted when probed before that first use; one constructed per call is dropped too early, so they are evicted every pass. Neither is stale data, only memoization that silently stops working. A `static` behind `LazyLock` registers on its first use, so force it before the app runs, in `main` or a lifespan (`LazyLock::force(&RUST_PARSER)`). Never build one inside a function body.+:::++<RustNote>+Python raises when a `LogicDep` is constructed inside a component context. `LogicDep::new` has no such check: it is up to you to construct every dependency before the app runs.+</RustNote>++</Lang>+Adopting `use_logic_dep` in a function that memoized callers already stored entries for does not re-store those entries (the caution under [`logic_tracking`](#logic_tracking) applies): ship the adoption with a `version` bump or a memoization-key change on those callers.#### Data dependencies: `DataDep` and `use_data_dep`@@ -371,8 +483,18 @@ Adopting `use_logic_dep` in a function that memoized callers already stored entr`DataDep` and `use_data_dep` are experimental. Experimental APIs are outside CocoIndex's compatibility promise: a later release, including a minor one, may change their API or semantics, or remove them.:::+<Lang only="python">+Logic, arguments and context values are all known before a body runs. Some bodies read things decided only while they run: an agent session opens the files the model chose, a test runner touches the files the tests import. `coco.DataDep` declares a *kind* of such a read once, at module import, with a validator; `coco.use_data_dep` records one read into the current call, as a key and the state observed. The next probe validates each record from the stored key and state alone, through the kind's validator, so the entry can be reused even though nothing in its arguments covers the read.+</Lang>++<Lang only="rust">++Logic, arguments and context values are all known before a body runs. Some bodies read things decided only while they run: an agent session opens the files the model chose, a test runner touches the files the tests import. `DataDep::new` declares a *kind* of such a read once, before the app runs, with a validator; `ctx.use_data_dep` records one read into the current call, as a key and the state observed. The next probe validates each record from the stored key and state alone, through the kind's validator, so the entry can be reused even though nothing in its arguments covers the read.++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md "Declare dependencies beyond the arguments", verified against rust/sdk/cocoindex/tests/memo_deps.rs (`DataDep::new`, `MemoStateDecision::new`, `ctx.use_data_dep`) */}<LangTabs><Fragment slot="python">@@ -429,29 +551,53 @@ async fn agent_session(ctx: &Ctx, task: &str) -> Result<String> {}```-In Rust, `DataDep<K, S>` is typed by its key and state, so the validator takes them already deserialized and returns a `MemoStateDecision` (`cocoindex::memo::MemoStateDecision`). Build the kind in a `static LazyLock` before the app runs.+`DataDep<K, S>` is typed by its key and state, so the validator takes them already deserialized and returns a `MemoStateDecision` (`cocoindex::memo::MemoStateDecision`). As with `LogicDep`, force the `static` before the app runs.</Fragment></LangTabs>+<Lang only="python">+The validator takes the recorded key and the stored state and returns a [`MemoStateOutcome`](../advanced_topics/memoization_keys#memo-state-validation), sync or awaitable; its parameter annotations drive typed deserialization of the stored key and state, so annotate both. It never receives `NON_EXISTENCE`. Renaming a kind invalidates every entry that recorded it, which doubles as its version bump.Key and state are any serializable values and are **snapshotted at the call**: identity and equality are fingerprints of the serialized bytes, and `__coco_memo_key__` is not consulted, so use plain values (the resolved path string, a tuple of mtime and digest). Recording the same kind and key again with an equal state records once; recording it with a **different** state makes the run store no entry, because output that used two states of one key has no single state to validate against. A body that writes what it then reads back should not record the read-back.+</Lang>++<Lang only="rust">++The validator takes the recorded key and the stored state and returns a future of `Result<MemoStateDecision>`: the state now observed (stored in place of the old one when it differs) and whether the entry is still valid. Renaming a kind invalidates every entry that recorded it, which doubles as its version bump. A second live kind with the same name replaces the registration and logs a warning.++Key and state are any `Serialize` values and are **snapshotted at the call**: identity and equality are fingerprints of the serialized bytes, and `MemoInput` is not consulted, so use plain values (the resolved path string, a tuple of mtime and digest). Recording the same kind and key again with an equal state records once; recording it with a **different** state makes the run store no entry, because output that used two states of one key has no single state to validate against. A body that writes what it then reads back should not record the read-back.++</Lang>+The rules for an entry that recorded data dependencies:-- The entry is reused only when its arguments, logic and context match **and** every record validates. A record whose kind is no longer registered, or whose stored key or state no longer deserializes, is a logged miss; a validator's exception propagates. A changed-but-valid state is refreshed without a run. On a miss the body's new records replace the stored set.+- The entry is reused only when its arguments, logic and context match **and** every record validates. A record whose kind is no longer registered, or whose stored key or state no longer deserializes, is a logged miss; a validator's <Lang only="python">exception propagates</Lang><Lang only="rust">error propagates</Lang>. A changed-but-valid state is refreshed without a run. On a miss the body's new records replace the stored set.- A record rides up through every enclosing function frame regardless of `logic_tracking`, into every enclosing memoized function's entry and the component's entry, where it stops. Records are **not** copied into ancestor components' entries. A component reports one bit upward instead, and its parent's entry lists the children that reported it: **a component is skipped only if its own entry validates and every descendant that recorded data dependencies validates too**, which the parent's probe checks from those descendants' own stored entries, by path, without mounting them. A changed-but-valid descendant record is refreshed in place. The probe stops, and the body re-runs, at a listed descendant with no entry (a non-memoized one, whose records are dropped, or one whose last run observed a key in two states), a record that no longer decodes, a kind no longer registered, or a validator answering invalid. Closed descendants are carried over by the reuse unvalidated, as they always were. A component that records nothing is unaffected.- Because a parent's probe may validate a record while the component that recorded it is not mounted, a validator runs with no component context and must depend on its key and stored state alone.-- `use_data_dep` raises outside a component context, and when the current frame has already closed. The check covers the current frame only: a `@coco.fn` reader started as a task that outlives the decorated function which started it keeps its own open frame, so its records merge into an already-joined frame and are lost, as its logic deps are today. Await readers inside the function that started them.+- <Lang only="python">`use_data_dep` raises outside a component context, and when the current frame has already closed. The check covers the current frame only: a `@coco.fn` reader started as a task that outlives the decorated function which started it keeps its own open frame, so its records merge into an already-joined frame and are lost, as its logic deps are today. Await readers inside the function that started them.</Lang><Lang only="rust">`ctx.use_data_dep` returns an error outside a pipeline context, and when the function that owns the current frame has already returned (a spawned task recording after it). Await readers inside the function that started them.</Lang>#### Callbacks: `logic_propagated_to_callers`+<Lang only="python">+`logic_tracking` is per function, so `"self"` hides the logic of *everything* a function calls β including callbacks it received as arguments. A library whose `accept` is `logic_tracking="self"` therefore hides the user's `visit_file`: an edit to `visit_file` invalidates nothing, even though it is the user's input, not the library's implementation detail.`coco.logic_propagated_to_callers(fn)` closes this gap. It is library-side; the user only puts `@coco.fn` on the callback. It does not make `fn` tracked: `fn`'s own `@coco.fn` and `logic_tracking` decide what it offers, exactly as for any function. The wrapper only carries that up to the frame that called it, through layers that would otherwise drop it. (`coco.logic_tracked` is the former name; it still works and emits a `DeprecationWarning`.)-Call it at the entry point that hands a callback down. The function that calls `logic_propagated_to_callers` is the callback's **owner**. The returned wrapper runs `fn` as usual; afterwards the logic `fn` offered (by `fn`'s own `logic_tracking`) is recorded in **every** memo entry between the call site and the owner's frame (the owner's own entry included) whatever their `logic_tracking`. The owner's mode only decides what goes further up: with `"full"` (the default) the owner offers the callback's logic to its callers like any other dependency; with `"self"` or `None` it stops there.+</Lang>++<Lang only="rust">++`logic_tracking` is per function, so `"self"` hides the logic of *everything* a function calls β including callbacks it received as arguments. A library whose `traverse` is `logic_tracking = "self"` therefore hides the user's `visit`: an edit to `visit` invalidates nothing, even though it is the user's input, not the library's implementation detail.++`ctx.logic_propagated_to_callers(f)` closes this gap. It is library-side; the user only puts `#[cocoindex::function]` on the callback. It does not make `f` tracked: the `#[cocoindex::function]` it calls and that function's `logic_tracking` decide what it offers, exactly as for any function. The wrapper only carries that up to the frame that called it, through layers that would otherwise drop it.++</Lang>++Call it at the entry point that hands a callback down. The function that calls `logic_propagated_to_callers` is the callback's **owner**. The returned wrapper runs <Lang only="python">`fn`</Lang><Lang only="rust">`f`</Lang> as usual; afterwards the logic <Lang only="python">`fn`</Lang><Lang only="rust">`f`</Lang> offered (by its own `logic_tracking`) is recorded in **every** memo entry between the call site and the owner's frame (the owner's own entry included) whatever their `logic_tracking`. The owner's mode only decides what goes further up: with `"full"` (the default) the owner offers the callback's logic to its callers like any other dependency; with `"self"` or <Lang only="python">`None`</Lang><Lang only="rust">`"none"`</Lang> it stops there.{/* Rust: rust/sdk/cocoindex/tests/memo_deps.rs (`traverse`, `logic_propagated_to_callers`) */}<LangTabs>@@ -515,11 +661,13 @@ let wrapped = Arc::new(ctx.logic_propagated_to_callers(callback)?);traverse(&ctx, "a.rs", &wrapped).await?;```-In Rust, `ctx.logic_propagated_to_callers(f)` returns a `PropagatedCallback<F>`. The library function takes it as an argument, skips it in the memo key, and calls it with `callback.call(ctx, ..)`. A call after the owner returned is an error, as in Python.+`ctx.logic_propagated_to_callers(f)` returns a `PropagatedCallback<F>`. The library function takes it as an argument, skips it in the memo key, and calls it with `callback.call(ctx, ..)`.</Fragment></LangTabs>+<Lang only="python">+The user edits `visit_file`; every `accept` memo entry misses and runs again. The user never sees `logic_propagated_to_callers`. `accept` needs no code of its own: the wrapper it receives already carries its owner.**When a library does not do this**, wrap the callback in your own code. Your function becomes the owner:@@ -537,15 +685,46 @@ Rules, for whoever calls `logic_propagated_to_callers`:- The wrapper keys by `fn`: two wrappers of the same `fn` key alike. It does not key as the bare `fn`, so passing `logic_propagated_to_callers(fn)` where `fn` was passed before moves that memo key once, when the wrapper is adopted.- Adopting the wrapper does not re-store existing memo entries (see the caution under [`logic_tracking`](#logic_tracking)): entries stored before the wrap recorded no callback logic and stay valid until their key or the memoized caller's `version` moves. Ship the adoption with one such change.+</Lang>++<Lang only="rust">++The user edits `visit`; every `traverse` memo entry misses and runs again. The user never sees `logic_propagated_to_callers`. `traverse` needs no code of its own: the wrapper it receives already carries its owner.++**When a library does not do this**, wrap the callback in your own code before you hand it to the library: call `ctx.logic_propagated_to_callers` in your own function, which becomes the owner.++Rules, for whoever calls `logic_propagated_to_callers`:++- Mark the function the callback calls with `#[cocoindex::function]` for its code to be tracked. A closure that calls no marked function contributes nothing.+- The wrapper is valid only while the owner's call is running. A call after the owner has returned returns an error instead of silently running untracked. Mount the components that call it with `use_mount!`, or wait for their handles' `ready()` inside the owner.+- `PropagatedCallback` does not implement `MemoInput`, so a memoized function that takes one skips it with `memo_key(callback = skip)`, as `traverse` does.+- Adopting the wrapper does not re-store existing memo entries (see the caution under [`logic_tracking`](#logic_tracking)): entries stored before the wrap recorded no callback logic and stay valid until their key or the memoized caller's `version` moves. Ship the adoption with one such change.++</Lang>+#### Common patterns+<Lang only="python">+:::tip[`@coco.fn` on non-memoized helpers]You can (and often should) decorate helpers with `@coco.fn` even without `memo=True`. The decorator's job is to make the function's logic *visible* to the change detection system. A bare helper is invisible: editing it will not invalidate any memoized caller, leading to silently stale results. Add `@coco.fn` so its fingerprint propagates; only add `memo=True` if caching its return value is worth it.:::These parameters can be set on any `@coco.fn` function β not just memoized ones.-**Fully automatic (default)** β use `logic_tracking="full"` (or omit it) without setting `version`. Any logic change in the function or its callees invalidates dependent memos.+</Lang>++<Lang only="rust">++:::tip[`#[cocoindex::function]` on non-memoized helpers]+You can (and often should) mark helpers with `#[cocoindex::function]` even without `memo`. The attribute's job is to make the function's logic *visible* to the change detection system. A bare helper is invisible: editing it will not invalidate any memoized caller, leading to silently stale results. Add `#[cocoindex::function]` so its fingerprint propagates; only add `memo` if caching its return value is worth it.+:::++These arguments can be set on any `#[cocoindex::function]` β not just memoized ones.++</Lang>++**Fully automatic (default)** β use <Lang only="python">`logic_tracking="full"`</Lang><Lang only="rust">`logic_tracking = "full"`</Lang> (or omit it) without setting `version`. Any logic change in the function or its callees invalidates dependent memos.{/* Rust: rust/sdk/cocoindex/tests/logic_tracking.rs */}<LangTabs>@@ -573,7 +752,7 @@ async fn full_explicit(_ctx: &Ctx, x: &i64) -> Result<i64> { /* ... */ }</Fragment></LangTabs>-**Manual, precise control** β use `logic_tracking="self"` with `version`. You decide what counts as a behavior change by bumping `version`, without being affected by implementation detail changes (performance optimizations, logging tweaks, refactoring, etc.).+**Manual, precise control** β use <Lang only="python">`logic_tracking="self"`</Lang><Lang only="rust">`logic_tracking = "self"`</Lang> with `version`. You decide what counts as a behavior change by bumping `version`, without being affected by implementation detail changes (performance optimizations, logging tweaks, refactoring, etc.).{/* Rust: rust/sdk/cocoindex/tests/memo_deps.rs (`caller_self`) */}<LangTabs>@@ -600,7 +779,7 @@ async fn caller_self(ctx: &Ctx, test: &str, value: &str) -> Result<String> {</Fragment></LangTabs>-**Opt out of tracking** β use `logic_tracking=None` for functions with a stable contract (where logic changes don't affect output), or functions whose changes don't affect behavior (e.g., logging, performance hints). This prevents unnecessary reprocessing when only internals change.+**Opt out of tracking** β use <Lang only="python">`logic_tracking=None`</Lang><Lang only="rust">`logic_tracking = "none"`</Lang> for functions with a stable contract (where logic changes don't affect output), or functions whose changes don't affect behavior (e.g., logging, performance hints). This prevents unnecessary reprocessing when only internals change.{/* Rust: rust/sdk/cocoindex/tests/logic_tracking.rs */}<LangTabs>@@ -622,39 +801,58 @@ def embed(text: str) -> list[float]:async fn untracked(_ctx: &Ctx, x: &i64) -> Result<i64> { /* ... */ }```-The Rust spelling of Python's `logic_tracking=None` is the string `"none"`.-</Fragment></LangTabs>:::note-[Context changes](./context#change-detection) are independent of `@coco.fn` and `logic_tracking`. Even with `logic_tracking=None`, a change in a change-detected context value still invalidates dependent memos, because context tracking is done by `use_context()`, not by the decorator.+<Lang only="python">[Context changes](./context#change-detection) are independent of `@coco.fn` and `logic_tracking`. Even with `logic_tracking=None`, a change in a change-detected context value still invalidates dependent memos, because context tracking is done by `use_context()`, not by the decorator.</Lang><Lang only="rust">[Context changes](./context#change-detection) are independent of `#[cocoindex::function]` and `logic_tracking`. Even with `logic_tracking = "none"`, a change in a change-detected context value still invalidates dependent memos, because context tracking is done by `ctx.get_key()`, not by the attribute.</Lang>:::### Debugging unexpected re-runsIf a memoized function is re-running when you expect a cache hit, walk through the inputs in order:-1. **Logic** β did the function's source code change? Did any `@coco.fn` it transitively calls change? Was a `version` bumped? Was a `deps` value edited?+1. **Logic** β did the function's source code change? Did any <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> it transitively calls change? Was a `version` bumped? Was a `deps` value edited?2. **Inputs** β are the arguments byte-identical to the previous call (after canonicalization)? Custom types with unstable equality are a common source of spurious invalidation β see [Memoization Keys & States](../advanced_topics/memoization_keys).-3. **Context** β did any [`detect_change=True`](./context#change-detection) context value read during the previous invocation change? Remember this propagates transitively through nested `@coco.fn` calls.+3. **Context** β did any <Lang only="python">[`detect_change=True`](./context#change-detection)</Lang><Lang only="rust">[`detect_change`](./context#change-detection)</Lang> context value read during the previous invocation change? Remember this propagates transitively through nested <Lang only="python">`@coco.fn`</Lang><Lang only="rust">`#[cocoindex::function]`</Lang> calls.-If none of those changed and the function still re-runs, the most common cause is a non-stable fingerprint on a custom-typed argument or context value β define `__coco_memo_key__` to make it deterministic.+If none of those changed and the function still re-runs, the most common cause is a non-stable fingerprint on a custom-typed argument or context value β <Lang only="python">define `__coco_memo_key__` to make it deterministic</Lang><Lang only="rust">derive `MemoInput`, or implement it by hand over the fields that identify the value, to make it deterministic</Lang>.Conversely, if a memo is hitting when you expect invalidation, common causes are:+<Lang only="python">+- A logic change in a helper that is **not** decorated with `@coco.fn`. Add `@coco.fn` to it (no `memo=` needed) so its logic participates in propagation β see [Common patterns](#common-patterns).- A `deps` value that you changed at runtime: `deps` is [snapshotted at decoration time](#deps), so per-instance or per-request values must be passed as regular arguments instead.- The function uses [`logic_tracking=None`](#logic_tracking), which opts it out of code-change detection entirely.- The change is in a callback that passes through a `logic_tracking="self"` function and nobody wrapped it with [`coco.logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers).+</Lang>++<Lang only="rust">++- A logic change in a helper that is **not** marked with `#[cocoindex::function]`. Add the attribute to it (no `memo` needed) so its logic participates in propagation β see [Common patterns](#common-patterns).+- A `deps` value that you changed at runtime: `deps` is [fingerprinted once per process](#deps), so per-request values must be passed as regular arguments instead.+- The function uses [`logic_tracking = "none"`](#logic_tracking), which opts it out of code-change detection entirely.+- The change is in a callback that passes through a `logic_tracking = "self"` function and nobody wrapped it with [`ctx.logic_propagated_to_callers`](#callbacks-logic_propagated_to_callers).++</Lang>+### Customizing data fingerprinting+<Lang only="python">+By default, CocoIndex fingerprints function arguments, `deps` values, and context values automatically for most types β primitives, containers, dataclasses, Pydantic models, and picklable objects. For custom types, or when you need multi-level validation (e.g., check mtime first, then content hash), see [Memoization Keys & States](../advanced_topics/memoization_keys).For per-function overrides (excluding an argument from the memo key, or transforming it just for this function) pass `memo_key={...}` on `@coco.fn` / `@coco.fn.as_async`; see [Override at the call site with `memo_key=`](../advanced_topics/memoization_keys#override-at-the-call-site-with-memo_key).-In Rust, arguments are fingerprinted through the `MemoInput` trait (`#[derive(MemoInput)]` for your own types). The per-function override is `memo_key(..)` on the attribute: a transform function replaces one argument's identity, and `skip` leaves it out. A target handle is `Clone` but not `MemoInput`, so a memoized function that declares rows takes it with `memo_key(table = skip)`:+</Lang>++<Lang only="rust">++Arguments, `deps` values and change-detected context values are fingerprinted through the `MemoInput` trait: primitives, `String`, containers, tuples and `Option` implement it, and `#[derive(MemoInput)]` covers your own types. For custom types, or when you need multi-level validation (e.g., check mtime first, then content hash), see [Memoization Keys & States](../advanced_topics/memoization_keys).++The per-function override is `memo_key(..)` on the attribute: a transform function replaces one argument's identity, and `skip` leaves it out. A target handle is keyed by its serialized stable key, or left out with `memo_key(table = skip)`; a client that is neither `MemoInput` nor `Serialize` must be skipped:{/* Rust: examples/rust/text_embedding/src/main.rs, rust/sdk/SHOWCASE.md "Define functions" (verified against rust/sdk/cocoindex_macros/src/lib.rs) */}```rust@@ -665,10 +863,20 @@ async fn process_file(ctx: &Ctx, file: &FileEntry, table: &postgres::TableTargetasync fn fetch(_ctx: &Ctx, entry: &Entry, client: &ApiClient) -> Result<String> { /* ... */ }```+See [Override at the call site with `memo_key=`](../advanced_topics/memoization_keys#override-at-the-call-site-with-memo_key).++</Lang>+## Execution capabilitiesThe following capabilities control *how* the function executes, independent of change detection and memoization.+<RustNote>+There is no async adapter: a `#[cocoindex::function]` is an `async fn`, and `batching` and `runner` are attribute arguments on it. Move blocking work to `tokio::task::spawn_blocking` inside the body when it must not hold a runtime worker.+</RustNote>++<Lang only="python">+### Async adapterUse `@coco.fn.as_async` when you need an **async** interface for a function that has a sync underlying implementation. This is useful for compute-intensive leaf functions. The decorator also accepts an `async def` body as-is, and [batching](#batching) and [runner](#runner) (which need an async interface) are always enabled through it.@@ -684,8 +892,6 @@ embedding = await embed("hello world")`@coco.fn.as_async` is equivalent to wrapping the function in `asyncio.to_thread()` β the sync function runs on a thread pool and doesn't block the event loop.-The Rust SDK has no equivalent of `as_async`: a `#[cocoindex::function]` is an `async fn`, and `batching` and `runner` are attribute arguments on it. Move blocking work to `tokio::task::spawn_blocking` inside the body when it must not hold a runtime worker.-You can also call any `@coco.fn`-decorated function asynchronously via the `.as_async()` method, without changing its primary signature:```python@@ -700,9 +906,13 @@ result = expensive_fn(data)result = await expensive_fn.as_async(data)```+</Lang>+### Batching-With `batching=True`, multiple concurrent calls to the function are automatically batched together. This is useful for operations that are more efficient when processing multiple inputs at once, such as embedding models.+With <Lang only="python">`batching=True`</Lang><Lang only="rust">`batching`</Lang>, multiple concurrent calls to the function are automatically batched together. This is useful for operations that are more efficient when processing multiple inputs at once, such as embedding models.++<Lang only="python">Batching requires an async interface, so it is always enabled with `@coco.fn.as_async(batching=True)`, whether the body is a plain `def` or an `async def`. `@coco.fn(batching=True)` is not supported: it raises `ValueError` when the decorator is applied, whichever kind of body it is given.@@ -713,6 +923,19 @@ When batching is enabled:- Concurrent calls are collected and processed together- The implementation runs outside the calling components β see [Context values in a batched body](#context-values-in-a-batched-body)+</Lang>++<Lang only="rust">++When batching is enabled:++- The function body receives a `Vec<T>` and returns a `Vec<R>`+- The generated function takes one `T` and returns one `R` (single input, single output)+- Concurrent calls are collected and processed together+- With `memo`, a cache hit is served per item and only misses enter a batch++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md "Batch item-shaped calls", verified against rust/sdk/cocoindex_macros/src/lib.rs and rust/sdk/cocoindex/tests/batching_runner.rs */}<LangTabs><Fragment slot="python">@@ -763,12 +986,22 @@ let embeddings = ctx.await?;```-In Rust, `batching` is an attribute argument. The body takes `Vec<T>` and returns `Vec<R>`; the generated wrapper takes one `T` and returns one `R`. With `memo`, a cache hit is served per item and only misses enter a batch.-</Fragment></LangTabs>-The `max_batch_size` parameter limits how many inputs can be processed in a single batch.+The `max_batch_size` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> limits how many inputs can be processed in a single batch.++<Lang only="rust">++A batching function must not call itself from its own body: that waits on the batcher which is already running the body.++</Lang>++<RustNote>+The attribute has no `max_in_flight` or `rate_limiter` argument. Its batching arguments are `batching`, `max_batch_size` and `runner`.+</RustNote>++<Lang only="python">The `max_in_flight` parameter bounds how many batches run at once. By default (`None`), a full batch starts as soon as it fills, and the next partial batch starts only once every running batch has finished. With `max_in_flight=n`, at most `n` batches run concurrently, and whenever one finishes the next pending batch (full or partial) starts, so a slow batch no longer holds back the rest:@@ -778,10 +1011,18 @@ async def embed(texts: list[str]) -> list[list[float]]:return await client.embed(texts)```-The Rust `#[cocoindex::function]` attribute has no `max_in_flight` or `rate_limiter` argument. Its batching arguments are `batching`, `max_batch_size` and `runner`.+</Lang>#### Pacing batches with a rate limiter+<Lang only="rust">++When each batch is one request against a quota, take a token from a shared [`RateLimiter`](../common_resources/rate_limiting) at the top of the batching body, with `limiter.acquire(1).await?`. One token then pays for one batch rather than one call.++</Lang>++<Lang only="python">+When each batch is one request against a quota, pass the quota's [`RateLimiter`](../common_resources/rate_limiting) as `rate_limiter`. Every batch takes one token before it runs, so a token pays for one batch rather than one call, and the batch boundary becomes the moment a request can be sent:- No call runs on its own: calls join the open batch, and a pump runs the oldest pending batch once a `max_in_flight` slot and a token are available. Under a scarce quota, every call that arrives while the pump waits for the token rides the next batch.@@ -802,6 +1043,10 @@ class Client:return await self._api.fetch_many(ids) # one request, one token```+</Lang>++<Lang only="python">+#### Context values in a batched bodyOne batch merges calls from many components, so the body runs outside any of them: `coco.use_context(...)` inside a `batching=True` body raises `RuntimeError: No ComponentContext available`. Resolve context values in the caller β a `@coco.fn` function or method running inside the component β and pass them to the batched function as extra arguments:@@ -821,11 +1066,21 @@ async def embed(text: str) -> list[float]:Only the first parameter is batched. Every other argument is passed through to the body unchanged and is part of the key that selects the batcher (so is `self`, for methods): calls share a batcher only when these arguments compare equal, which also means they must be hashable. Pass them the same way on every call. An explicit value and the default, or the same value given positionally and by keyword, select different batchers, and the calls are never batched together.-Rust differs here: a batching body receives a `Ctx`, so `ctx.get_key(&KEY)?` works inside it, as in the `embed_batch` example above. The engine joins the dependencies the body reads into every caller's memo entry. The parameter after the `&Ctx` is the batched one; each other parameter must implement `Serialize`, because its serialized value selects the batcher, and `MemoInput` when the function is `memo` (unless `memo_key(..)` transforms or skips it).+</Lang>++<Lang only="rust">++#### Context values and extra parameters in a batched body++A batching body receives a `Ctx`, so `ctx.get_key(&KEY)?` works inside it, as in the `embed_batch` example above. The engine joins the dependencies the body reads into every caller's memo entry.++The parameter after the `&Ctx` is the batched one. Every other parameter is passed through to the body unchanged and must implement `Serialize`: its serialized value selects the batcher, so calls share a batch only when these values are equal. With `memo`, each must also implement `MemoInput`, unless `memo_key(..)` transforms or skips it.++</Lang>#### Retrying a failed batch as smaller batches-Some batch failures depend on the batch's composition rather than any single input β e.g. a provider's per-request token or payload limit, or one input the provider rejects. No fixed `max_batch_size` can rule these out. When the function body hits such a failure, raise `coco.RetryWithSmallerBatch` from it: CocoIndex halves the batch and retries each half, recursing down to single items. At size 1, the wrapped original error is raised as that item's own failure β so one bad input fails only its own caller, while the rest of the batch still succeeds. There is no need to check the batch size before raising: at size 1 the engine simply unwraps the signal and raises the original error.+Some batch failures depend on the batch's composition rather than any single input β e.g. a provider's per-request token or payload limit, or one input the provider rejects. No fixed `max_batch_size` can rule these out. <Lang only="python">When the function body hits such a failure, raise `coco.RetryWithSmallerBatch` from it: CocoIndex halves the batch and retries each half, recursing down to single items. At size 1, the wrapped original error is raised as that item's own failure β so one bad input fails only its own caller, while the rest of the batch still succeeds. There is no need to check the batch size before raising: at size 1 the engine simply unwraps the signal and raises the original error.</Lang><Lang only="rust">When the function body hits such a failure, return `Error::retry_with_smaller_batch(cause)` from it: CocoIndex halves the batch and retries each half, recursing down to single items. At size 1, `cause` becomes that item's own failure β so one bad input fails only its own caller, while the rest of the batch still succeeds. There is no need to check the batch size before returning it: at size 1 the engine simply unwraps the signal and fails that caller with `cause`.</Lang>{/* Rust: rust/sdk/SHOWCASE.md "Batch item-shaped calls", verified against rust/sdk/cocoindex/tests/batching_runner.rs (`Error::retry_with_smaller_batch`) */}<LangTabs>@@ -856,12 +1111,10 @@ async fn embed_batch(ctx: &Ctx, texts: Vec<String>) -> Result<Vec<Vec<f32>>> {}```-In Rust, return `Error::retry_with_smaller_batch(cause)` from the body. At batch size one, the engine unwraps the signal and fails that caller with `cause`.-</Fragment></LangTabs>-Raising it is safe for *any* deterministic batch failure, even when you can't tell whether the batch size was the cause: if the error was actually global (it would fail at any size), the recursion terminates at single items and every caller receives the underlying error, at the bounded cost of extra attempts. Only propagate directly for errors where splitting provably can't help β global errors like invalid credentials, and transient errors (rate limits, network blips) that haven't yet been retried at the same size. Once same-size retries are exhausted, splitting is a reasonable last resort: a smaller request may pass where the large one timed out.+<Lang only="python">Raising it</Lang><Lang only="rust">Returning it</Lang> is safe for *any* deterministic batch failure, even when you can't tell whether the batch size was the cause: if the error was actually global (it would fail at any size), the recursion terminates at single items and every caller receives the underlying error, at the bounded cost of extra attempts. Only propagate directly for errors where splitting provably can't help β global errors like invalid credentials, and transient errors (rate limits, network blips) that haven't yet been retried at the same size. Once same-size retries are exhausted, splitting is a reasonable last resort: a smaller request may pass where the large one timed out.:::tip[When to use batching]@@ -869,7 +1122,7 @@ Batching is beneficial when:- The underlying operation has significant per-call overhead (e.g., GPU kernel launch)- The operation can process multiple inputs more efficiently than one at a time-- You have concurrent calls from multiple coroutines+- You have concurrent calls from multiple <Lang only="python">coroutines</Lang><Lang only="rust">tasks</Lang>Common use cases:@@ -881,10 +1134,14 @@ Common use cases:### Runner-The `runner` parameter allows functions to execute in a specific context, such as a dedicated GPU runner that serializes GPU workloads.+The `runner` <Lang only="python">parameter</Lang><Lang only="rust">argument</Lang> allows functions to execute in a specific context, such as a dedicated GPU runner that serializes GPU workloads.++<Lang only="python">Like batching, a runner requires an async interface, so it is always set with `@coco.fn.as_async(runner=...)`, on a plain `def` or an `async def` body. `@coco.fn(runner=...)` raises `ValueError` when applied.+</Lang>+{/* Rust: rust/sdk/cocoindex/tests/batching_runner.rs (`runner = GPU`, `GPURunner::fraction`) */}<LangTabs><Fragment slot="python">@@ -920,18 +1177,51 @@ async fn half_gpu(_ctx: &Ctx, item: i64) -> Result<i64> {let result = whole_gpu(&ctx, item).await?;```-In Rust, `runner` is a `const` expression of type `GPURunner`. `cocoindex::GPU` takes a whole GPU per call; `GPURunner::fraction(f)` takes a share, so several calls run at once on one GPU. Inside the body, `current_gpu()`, `current_gpus()` and `current_gpu_fraction()` report the assignment. The pool size comes from `COCOINDEX_NUM_GPUS`, `CUDA_VISIBLE_DEVICES` or `nvidia-smi` (one GPU by default); `configure_gpu_pool(n)` overrides it before the first GPU function runs.-</Fragment></LangTabs>+<Lang only="python">+The `coco.GPU` runner:- By default, runs in-process with all functions sharing a queue for serial execution- Sync functions run on a dedicated GPU thread to avoid blocking the event loop- Set the environment variable `COCOINDEX_RUN_GPU_IN_SUBPROCESS=1` to run in a subprocess for GPU memory isolation-Python's subprocess mode and dedicated GPU thread exist for the GIL and CUDA's fork rules. A Rust body has neither, so the Rust SDK has no equivalent.+</Lang>++<Lang only="rust">++`runner = <expr>` takes a value of any type that implements `cocoindex::Runner`; it is built on the function's first call and shared by every call. The GPU runners draw from a process-wide GPU pool:++- `cocoindex::GPU` takes a whole GPU per call (or per physical batch, with `batching`), so bodies on one GPU run one at a time+- `GPURunner::fraction(f)` takes a share, so several calls run at once on one GPU+- Inside the body, `current_gpu()`, `current_gpus()` and `current_gpu_fraction()` report the assignment+- The pool size comes from `COCOINDEX_NUM_GPUS`, `CUDA_VISIBLE_DEVICES` or `nvidia-smi` (one GPU by default); `configure_gpu_pool(n)` overrides it before the first GPU function runs++A runner of your own implements `cocoindex::Runner`: it receives each body as a future and decides when to run it.++{/* Rust: rust/sdk/SHOWCASE.md "Run on a GPU" (`AtMostTwo`), verified against rust/sdk/cocoindex/src/runner.rs */}+```rust+struct AtMostTwo(tokio::sync::Semaphore);++#[async_trait::async_trait]+impl cocoindex::Runner for AtMostTwo {+ async fn run(&self, body: cocoindex::RunnerBody<'_>) -> Result<cocoindex::RunnerOutput> {+ let _permit = self.0.acquire().await.map_err(|e| Error::engine(e.to_string()))?;+ body.await+ }+}++#[cocoindex::function(memo, runner = AtMostTwo(tokio::sync::Semaphore::new(2)))]+async fn summarize(_ctx: &Ctx, text: String) -> Result<String> { /* ... */ }+```++</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 there is no equivalent.+</RustNote>You can combine batching with a runner:@@ -977,6 +1267,10 @@ let outputs = futures::future::join_all(calls)</Fragment></LangTabs>+<Lang only="python">+:::noteBy default, `coco.GPU` runs functions in-process, so no pickling is required. When using subprocess mode (`COCOINDEX_RUN_GPU_IN_SUBPROCESS=1`), the function and all its arguments must be picklable since they are serialized for subprocess execution.:::++</Lang>diff --git a/docs/src/content/docs/programming_guide/serialization.mdx b/docs/src/content/docs/programming_guide/serialization.mdxindex a9598f71..b406a353 100644--- a/docs/src/content/docs/programming_guide/serialization.mdx+++ b/docs/src/content/docs/programming_guide/serialization.mdx@@ -4,12 +4,16 @@ description: >How CocoIndex serializes memoized function returns with msgspec β supportedtypes (primitives, collections, dataclasses, Pydantic, NumPy), required typeannotations, custom type registration, and troubleshooting tips.+rust_description: >+ How CocoIndex serializes memoized function returns with serde β the+ Serialize and Deserialize bounds, MemoInput for memo keys, and SchemaFields+ for connector rows.---import LangTabs from '../../../components/LangTabs.astro';## Overview-CocoIndex serializes and caches the return values of [memoized functions](./function#memoization) so that unchanged work can be skipped on subsequent runs. Most Python types work automatically β the key thing to get right is the **return type annotation**, which tells CocoIndex how to reconstruct your objects:+CocoIndex serializes and caches the return values of [memoized functions](./function#memoization) so that unchanged work can be skipped on subsequent runs. <Lang only="python">Most Python types work automatically β the key thing to get right is the **return type annotation**, which tells CocoIndex how to reconstruct your objects:</Lang><Lang only="rust">The return type of a memoized function is static, so there is nothing to annotate: it must implement `serde::Serialize` and `serde::Deserialize`, which is how CocoIndex stores the value and reads it back:</Lang>{/* Rust: rust/sdk/SHOWCASE.md "Define functions", verified against rust/sdk/cocoindex/src/memo.rs (`cached` bounds) */}<LangTabs>@@ -31,14 +35,14 @@ async fn parse_file(_ctx: &Ctx, file: FileEntry) -> Result<Vec<Section>> {}```-In Rust, the return type `T` of a memoized function must implement `serde::Serialize` and `serde::Deserialize`. The type is static, so there is nothing to annotate: derive both on `Section`.+Derive both on `Section`: `#[derive(Serialize, Deserialize)]`.</Fragment></LangTabs>-Without annotations, values may deserialize as basic Python types (`dict`, `list`, `str`, etc.) instead of their original types.+<Lang only="python">-The rest of this page describes the Python types. The Rust SDK stores a value through `serde`; any type with a `Serialize` and `Deserialize` implementation works, including every `serde` container and derived struct. See [Rust rows and schemas](#rust-rows-and-schemas) for the Rust side of memo keys and connector rows.+Without annotations, values may deserialize as basic Python types (`dict`, `list`, `str`, etc.) instead of their original types.:::info[Advanced: other places where serialization and type annotations matter]Serialization also applies to [memo states](../advanced_topics/memoization_keys#memo-state-validation) and [tracking records](../advanced_topics/custom_target_connector#targethandler-you-implement). If you're implementing these, add type annotations to:@@ -159,13 +163,25 @@ If you see this error after upgrading, previously cached data may reference type- If the type is already a dataclass or NamedTuple, add `@coco.unpickle_safe` to allow reading the old cached data. Once the cache is rebuilt, the decorator can be removed.:::-## Rust rows and schemas+</Lang>++<Lang only="rust">++Three traits cover every value CocoIndex serializes or fingerprints; there is no registration step.++## Return values-The Rust SDK has no pickle path and no registration: three traits cover what this page describes for Python.+A memoized return value is stored through `serde::Serialize` and read back through `serde::Deserialize`. Any type with both implementations works: primitives, `String`, every `serde` container, `Option`, tuples, and structs and enums with `#[derive(Serialize, Deserialize)]`, nested to any depth.-- **Memoized return values** are stored through `serde::Serialize` and read back through `serde::Deserialize`.-- **Memo keys** (function arguments, `deps` values, change-detected context values) are fingerprinted through the `MemoInput` trait. Derive it with `#[derive(cocoindex::MemoInput)]`; every field is handled recursively, so the type needs no `Serialize`. It composes through `Option`, sequences, tuples, maps, sets, `Box` and `Arc`. `uuid::Uuid` and `serde_json::Value` are always available; the `chrono` and `rust_decimal` features add those leaf types, and a connector feature enables the leaf features it needs. Wrap another third-party type in a newtype when it appears inside derived data. A type with only `Serialize` is keyed by its serialized value; a target handle that is `Serialize` is keyed that way, by its stable key. A memoized function skips any other handle with `memo_key(table = skip)` (see [Function](./function#customizing-data-fingerprinting) and [target handles](../advanced_topics/memoization_keys)).-- **Connector rows** are `serde::Serialize` structs with `#[derive(SchemaFields)]`. The connector's `TableSchema::from_row::<Row>(primary_key)` derives the columns from the struct, the Rust form of Python's `TableSchema.from_class`: an `Option<T>` field is a nullable column, every other field is `NOT NULL`.+A cache hit deserializes the stored value into the function's return type. If you change that type's shape (rename or retype a field) without changing the function, a stored value that no longer deserializes fails the call with an error. Bump the function's [`version`](./function#version), or rebuild the cache with `UpdateOptions { full_reprocess: true, .. }` or [`cocoindex update --full-reprocess`](../cli_rust).++## Memo keys++Memo keys (function arguments, `deps` values, change-detected context values) are fingerprinted through the `MemoInput` trait. Derive it with `#[derive(cocoindex::MemoInput)]`; every field is handled recursively, so the type needs no `Serialize`. It composes through `Option`, sequences, tuples, maps, sets, `Box` and `Arc`. `uuid::Uuid` and `serde_json::Value` are always available; the `chrono` and `rust_decimal` features add those leaf types, and a connector feature enables the leaf features it needs. Wrap another third-party type in a newtype when it appears inside derived data. A type with only `Serialize` is keyed by its serialized value; a target handle that is `Serialize` is keyed that way, by its stable key. A memoized function skips any other handle with `memo_key(table = skip)` (see [Function](./function#customizing-data-fingerprinting) and [target handles](../advanced_topics/memoization_keys)).++## Connector rows++Connector rows are `serde::Serialize` structs with `#[derive(SchemaFields)]`. The connector's `TableSchema::from_row::<Row>(primary_key)` derives the columns from the struct: an `Option<T>` field is a nullable column, every other field is `NOT NULL`.{/* Rust: rust/sdk/cocoindex/tests/schema_from_row.rs (`postgres_from_row_matches_explicit_schema`), rust/sdk/SHOWCASE.md "Derive connector schemas from row types" (verified) */}```rust@@ -205,4 +221,6 @@ The field attributes are:| `#[coco(type = "...")]` | A raw connector column type, used as written || `#[coco(rename = "...")]` | A different column name |-`with_column_type(field, type)` replaces one column's type for this schema only; use it when one row struct feeds two connectors. Python's `from_class(column_overrides=...)` also carries a value encoder; in Rust the row is encoded by its `Serialize` implementation, so put `#[serde(serialize_with = "...")]` on the field.+`with_column_type(field, type)` replaces one column's type for this schema only; use it when one row struct feeds two connectors. To encode one field's value differently, put `#[serde(serialize_with = "...")]` on it: the row is encoded by its `Serialize` implementation.++</Lang>diff --git a/docs/src/content/docs/programming_guide/target_state.mdx b/docs/src/content/docs/programming_guide/target_state.mdxindex 57b921a4..1cac42d4 100644--- a/docs/src/content/docs/programming_guide/target_state.mdx+++ b/docs/src/content/docs/programming_guide/target_state.mdx@@ -186,7 +186,7 @@ let target_table = postgres::mount_table_target(target_table.declare_row(ctx, &DocEmbedding { /* ... */ })?;```-The row type derives `SchemaFields`, and `TableSchema::from_row::<Row>(keys)` builds the schema from it. See [Serialization](./serialization#rust-rows-and-schemas).+The row type derives `SchemaFields`, and `TableSchema::from_row::<Row>(keys)` builds the schema from it. See Connector rows in [Serialization](./serialization).</Fragment></LangTabs>