Skip to content

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

feat: sliced execution with App.update(component_selector=...) (#2799)

LJ πŸ₯₯🌴027ca645bce8
diff --git a/docs/src/content/docs/cli.mdx b/docs/src/content/docs/cli.mdx
index 3fa653d6..d1779e6d 100644
--- a/docs/src/content/docs/cli.mdx
+++ b/docs/src/content/docs/cli.mdx
@@ -298,6 +298,7 @@ cocoindex update [OPTIONS] APP_TARGET
| `--full-reprocess` | Reprocess everything, bypassing all memoization caches: every component and memoized function executes again (external calls such as embeddings included). To force just one function's work to run again, bump its version= instead. |
| `-L, --live` | Run in live mode (live components continue processing after initial update). |
| `--preview` | Compute target actions without applying them. Prints planned actions. |
+| `--select PATH` | Run only the component at PATH and the components below it; repeat to run several. Write PATH as `cocoindex show` prints it, such as '/@process_file/"docs/a.md"'. Other components are not run and not treated as gone. |
| `--help` | Show this message and exit. |
---
diff --git a/docs/src/content/docs/cli_rust.mdx b/docs/src/content/docs/cli_rust.mdx
index 5908ed0a..59963a9b 100644
--- a/docs/src/content/docs/cli_rust.mdx
+++ b/docs/src/content/docs/cli_rust.mdx
@@ -166,6 +166,7 @@ Run an app in catch-up mode. With `--live`, run in live mode.
cocoindex update [APP_TARGET]
cocoindex update -L [APP_TARGET]
cocoindex update --preview [APP_TARGET]
+cocoindex update --select PATH [--select PATH ...] [APP_TARGET]
```
Progress renders on stderr; the final `[Stats] ...` line prints on stdout.
@@ -178,6 +179,7 @@ Progress renders on stderr; the final `[Stats] ...` line prints on stdout.
* `--full-reprocess`: Reprocess everything, bypassing all memoization caches.
* `-L, --live`: Run in live mode (live components continue processing after initial update).
* `--preview`: Compute target actions without applying them. Prints planned actions, and writes nothing to the state database. It cannot be combined with `--reset` or `--live`.
+* `--select PATH`: Run only the component at `PATH` and the components below it; repeat to run several. Write `PATH` as `cocoindex show` prints it, such as `'/"process_file"/"docs/a.md"'`. Other components are not run and not treated as gone. It cannot be combined with `--reset`. See [Updating part of an app](./programming_guide/app#updating-part-of-an-app).
Ctrl-C stops the run: the CLI prints `Stopping...` and forwards the interrupt to the child; a second Ctrl-C kills it.
diff --git a/docs/src/content/docs/connectors/localfs.mdx b/docs/src/content/docs/connectors/localfs.mdx
index 46aab8a9..65fe0e49 100644
--- a/docs/src/content/docs/connectors/localfs.mdx
+++ b/docs/src/content/docs/connectors/localfs.mdx
@@ -338,6 +338,8 @@ The key is `FileEntry::key()`: the relative path with forward slashes.
</Fragment>
</LangTabs>
+<Lang only="python">In an update that runs only some components (see [Updating part of an app](../programming_guide/app#updating-part-of-an-app)), `mount_each()` reads only the selected keys from `items()`: it checks those files instead of walking the directory, and applies the same `recursive` and `path_matcher` rules as the walk.</Lang>
+
### Filtering files
Use `PatternFilePathMatcher` to filter which files and directories are included:
diff --git a/docs/src/content/docs/programming_guide/app.mdx b/docs/src/content/docs/programming_guide/app.mdx
index 0abfbcbc..7af49df5 100644
--- a/docs/src/content/docs/programming_guide/app.mdx
+++ b/docs/src/content/docs/programming_guide/app.mdx
@@ -175,6 +175,7 @@ let result = app.update_blocking(app_main)?;
- `live` option keeps the app running after the initial scan so live components can continue watching for changes. See [Live Mode](./live_mode).
- `report_to_stdout` option prints periodic progress updates during execution. Pass `True` for the default refresh interval, or a `timedelta` to set it.
- `full_reprocess` option reprocesses everything, bypassing all memoization: every component **and** every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost β€” this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function's work, bump its [`version`](./function#version) instead.
+- `component_selector` option runs only the components you name. See [Updating part of an app](#updating-part-of-an-app).
</Lang>
@@ -187,6 +188,7 @@ let result = app.update_blocking(app_main)?;
- `full_reprocess` reprocesses everything, bypassing all memoization: every component **and** every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost β€” this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function's work, bump its [`version`](./function#version) instead.
- `preview` computes the target actions without applying them.
- `timeout` bounds how long the update may run.
+- `component_selector` runs only the components you name. See [Updating part of an app](#updating-part-of-an-app).
</Lang>
@@ -229,6 +231,84 @@ Given the same logic and inputs, updates are repeatable. When logic or inputs ch
<Lang only="python">To watch progress beyond the `report_to_stdout` flag, the `UpdateHandle` returned by `app.update()` also exposes stats programmatically β€” poll with `handle.stats()` or stream with `handle.watch()`. For those structured APIs, and for splitting a run into separately-reported scopes with `coco.stats_group()`, see [Progress monitoring](../advanced_topics/progress_monitoring).</Lang><Lang only="rust">To watch progress beyond the `report_to_stdout` option, `app.start_update(app_main)` returns an `UpdateHandle` that exposes stats programmatically: poll with `handle.stats_snapshot()`, wait for a change with `handle.changed().await`, and take the value with `handle.result().await`. See [Progress monitoring](../advanced_topics/progress_monitoring).</Lang>
+### Updating part of an app
+
+Pass `component_selector` to run a slice of the app: the components at the given paths and what it takes to reach them. Every other component stays exactly as it is. This is what you want to inspect or debug a few components without processing the rest, for example the rows on one page of an observability UI.
+
+{/* Rust: rust/sdk/cocoindex/tests/pipeline.rs */}
+<LangTabs>
+<Fragment slot="python">
+
+```python
+paths = [coco.ROOT_PATH / coco.Symbol("process_file") / name for name in page_of_files]
+await app.update(component_selector=paths)
+
+# Preview what they would declare, without applying it.
+actions = await app.update(component_selector=paths, preview=True)
+```
+
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+let selector = ComponentSelector::new([
+ StablePath::root()
+ .concat_part(StableKey::Str("process_file".into()))
+ .concat_part(StableKey::Str("a.md".into())),
+]);
+app.update_with_options(
+ UpdateOptions {
+ component_selector: Some(selector),
+ ..UpdateOptions::default()
+ },
+ app_main,
+)
+.await?;
+```
+
+</Fragment>
+</LangTabs>
+
+A selector is a set of component paths, each a `StablePath` built from the keys of the mount calls: in Python, a mount without a subpath adds the `Symbol` of the function's name (in Rust, a `Str` key), `coco.component_subpath("process", key)` adds its keys, and a key keeps its type (`1` is not `"1"`). A path names one component and everything below it, so `coco.ROOT_PATH / "process"` selects everything mounted under it. Selecting a path that does not exist is not an error: it selects nothing, so check that a path you built is one the app has.
+
+To get the paths of an app, call `await cocoindex.inspect.list_stable_paths(app)` (or `list_stable_paths_sync(app)`): it returns `StablePath` values that you can pass to `component_selector` as they are. [`cocoindex show`](#managing-apps-with-cli) prints the same paths for reading: `@name` is a `Symbol` (`@"name"` when the name is not a plain word, such as `@"cocoindex/mount_target"`), a quoted part is a string, and a bare number is an int. `cocoindex show PATH` and `cocoindex update --select PATH` read that text back.
+
+From the command line, pass the paths as `cocoindex show` prints them to `cocoindex update --select`, once per path. Quote each one for the shell:
+
+```sh
+cocoindex update main.py --select '/@process_file/"docs/a.md"' --select '/@process_file/"docs/b.md"'
+```
+
+For a Rust app, the [`cocoindex` CLI for Rust](../cli_rust) takes the same flag; a Rust mount key is a string, so write `'/"process_file"/"docs/a.md"'`. `--select` works with `--preview`, `--live` and `--full-reprocess`, but not with `--reset`. A path that is not written as `cocoindex show` prints it, such as `/process_file/docs/a.md`, is an error.
+
+What each component does in such an update:
+
+| Component | What happens |
+|---|---|
+| Selected, or under a selected path | Runs as in a plain update: memoization applies, its target states sync, and if its source item is gone, it is deleted. |
+| An ancestor of a selected path | Runs, to reach the selected path. Its own target states sync. |
+| The root, and a `use_mount` child | Always run, since a value they return may be needed. Their own target states sync. What they `mount` is filtered in turn. |
+| Anything else | Not run, and not treated as gone: no target state changes and nothing about it changes in CocoIndex's records, even if its source item changed or was deleted. A live component does not start. |
+
+A selector skips components, not target states. A pipeline that runs each item with `use_mount` (to collect the results), or whose parent declares the rows of its items, runs every item and syncs every row under any selector. Only what is mounted with `mount` or `mount_each` can be left out.
+
+Details to rely on:
+
+- **The next plain update catches up.** An unselected component is processed by the next update that covers it, including its deletion if its source item is still gone. To make that possible, a component with a child that the selector left out, and each of its ancestors, stores no [memo](./function#memoization) and drops the one it had, so it runs again next time. What it mounted hits its own memo as usual.
+- **A container change needs a plain update when it affects left-out rows.** A change to a container target state (a table, a dict) that rebuilds it, converts its data or removes it also affects the rows of its children. If a selective update would apply one while a component it does not run owns a row of that container, the component that declares the container fails before it applies anything, because the update would not declare that row again, and the update fails with the same error when it ends, even if that component runs in the background. Other selected components may already have applied their changes. The error names the container target state and asks for a full update: run one without `component_selector`. A preview with the same selector fails with the same error, so it never shows what the update would refuse. When the update runs every component that owns a row of the container, for example `--select '/@process_file'` in a pipeline whose rows all come from `process_file`, the change applies as in a plain update.
+ - A change that keeps the data, such as a new nullable column or an index change, is not refused. It applies, and the rows of unselected components show it (a new column reads `NULL`) until they run again.
+ - A connector that cannot trust the previous state, as under `full_reprocess`, may report a lossy change for a container that did not change. That is not refused.
+ - A selected component that is gone still removes its containers, rows of unselected components included, since nothing can declare under them any more. The next plain update cleans up their records.
+- **A memo hit stands in for the subtree.** As in a plain update, a memoized ancestor whose inputs did not change is not run, and neither is anything below it. Add `full_reprocess=True` to force the selected components to run: it applies only to them and to the ancestors that reach them.
+- **An ancestor component that is no longer mounted stays whole.** If an ancestor component of a selected path is gone from the source, nothing below it is deleted, selected or not, because deleting it would delete unselected components too. The next update that covers it does. A directory (a `component_subpath` prefix) is not a component: a selected path below a directory that is gone is deleted.
+- **Live mode:** the selector holds for the whole update, including `operator.update` and `operator.delete` calls from later live events. A live component already running in another update keeps running if this update is a preview or a one-shot update, or if the component is unselected or only an ancestor of a selected path. A one-shot update that selects the component runs its own instance beside the running one, as a plain one-shot update does (see [A catch-up update beside a running live update](../advanced_topics/live_component#a-catch-up-update-beside-a-running-live-update)). A live update that selects the component replaces it, as any second live update does. A source that allows one watcher at a time can fail the second run. Values that a live component writes with `write_committed_state` under a selector are not persisted unless the component is selected, because a partial run has not earned a marker such as "full scan done".
+- **State of the components that run.** `coco.use_state` values of the components that run, ancestors included, are persisted as usual. Don't store a marker that claims the whole subtree ran (such as "full scan done") with `use_state` in a component that a selector can run partly.
+- **Preview** returns the actions of the components that ran: the selected ones, plus any changes to the own target states of the ancestors and `use_mount` children that ran. As in any preview, the deletion of a component that is no longer mounted is not previewed, and a failure that happens only when a sink applies its actions shows up only in the update.
+- **Taking over a target state.** A selected component that declares a target state another component owns takes it over, as it would in a plain update. If the update leaves the other component out, it and its ancestors lose their memos, so that the next update that covers them runs them. The rest of the other component is left alone.
+- **Empty selector.** `component_selector=[]` selects nothing: the root and its `use_mount` children run, and no other component does. `None`, the default, is a plain update.
+- **A source is read only as far as needed.** A `mount_each()` that the selector leaves out does not read its items at all. One that is only an ancestor of selected paths reads just the selected keys from a source that can read by key, such as `localfs.walk_dir(...).items()` outside live mode, which checks the selected files instead of walking the directory. A selected key that the source no longer has is deleted, as in a plain update. Any other source is listed in full, and `mount_each()` skips the unselected items. A `mount_each()` that is not read cannot report a duplicate key, so a key used twice may only show up in a plain update.
+- In Rust, the selector filters `ctx.mount`, `ctx.mount_each` and live components. `ctx.scope`, `use_mount!` and `use_mount_each!` return values, so they always run.
+
## How an app runs
An App is the top-level runner and entry point. A **processing component** is the unit of incremental execution *within* an app.
diff --git a/python/cocoindex/_internal/api.py b/python/cocoindex/_internal/api.py
index 4bf828af..240de6b4 100644
--- a/python/cocoindex/_internal/api.py
+++ b/python/cocoindex/_internal/api.py
@@ -10,9 +10,11 @@ from typing import (
Generic,
Iterable,
ParamSpec,
+ Protocol,
TypeVar,
cast,
overload,
+ runtime_checkable,
)
from . import core, environment
@@ -312,6 +314,12 @@ async def use_mount(*pos_args: Any, **kwargs: Any) -> Any:
return pyvalue.get(fn_ret_deserializer(processor_fn))
+def _skips_mount(parent_ctx: ComponentContext, child_path: core.StablePath) -> bool:
+ return core.skips_mount(
+ child_path, parent_ctx._core_processor_ctx, parent_ctx._core_fn_call_ctx
+ )
+
+
async def _mount_live_component(
parent_ctx: ComponentContext,
child_path: core.StablePath,
@@ -327,12 +335,16 @@ async def _mount_live_component(
"""
from .live_component import _process_live_wrapper
- controller, readiness_handle = await core.mount_live_async(
+ mounted = await core.mount_live_async(
child_path,
parent_ctx._core_processor_ctx,
parent_ctx._core_fn_call_ctx,
parent_ctx._core_processor_ctx.live,
)
+ if mounted is None:
+ # The update's component selector leaves this component out.
+ return ComponentMountHandle([])
+ controller, readiness_handle = mounted
operator = LiveComponentOperator(controller, instance, parent_ctx._env, child_path)
@@ -402,6 +414,11 @@ async def mount(*pos_args: Any, **kwargs: Any) -> ComponentMountHandle:
parent_ctx = get_context_from_ctx()
child_path = build_child_path(parent_ctx, subpath)
+ # Asked before anything is prepared: a live component's constructor and a
+ # memo key are user code, which an unselected component must not run.
+ if _skips_mount(parent_ctx, child_path):
+ return ComponentMountHandle([])
+
if is_live_component_class(processor_fn):
instance = processor_fn(*args, **kwargs)
return await _mount_live_component(parent_ctx, child_path, instance)
@@ -503,6 +520,8 @@ async def mount_each(*pos_args: Any, **kwargs: Any) -> ComponentMountHandle:
child_path = build_child_path(parent_ctx, subpath)
if isinstance(items, LiveMapFeed):
+ if _skips_mount(parent_ctx, child_path):
+ return ComponentMountHandle([])
# Live data source: the per-item `fn` (whether a plain function or a
# LiveComponent class) is dispatched through `mount()` / `operator.update()`
# inside `_MountEachLiveComponent`, both of which already handle live
@@ -520,6 +539,8 @@ async def mount_each(*pos_args: Any, **kwargs: Any) -> ComponentMountHandle:
async def _mount_one(key: StableKey, item: Any) -> None:
item_path = child_path.concat(key)
+ if _skips_mount(parent_ctx, item_path):
+ return
if fn_is_live:
instance = fn(item, *extra_args, **kwargs)
handle = await _mount_live_component(parent_ctx, item_path, instance)
@@ -542,7 +563,16 @@ async def mount_each(*pos_args: Any, **kwargs: Any) -> ComponentMountHandle:
)
core_handles.append(core_handle)
- if isinstance(items, AsyncIterable):
+ # Under a selector that leaves out some keys, read only the ones it may
+ # run: none at all, or, from a source that reads by key, just those.
+ keys = core.mount_each_keys(
+ child_path, parent_ctx._core_processor_ctx, parent_ctx._core_fn_call_ctx
+ )
+ if keys is not None and (not keys or isinstance(items, _ReadableByKey)):
+ if keys:
+ async for key, item in items.__coco_items_for_keys__(keys):
+ await _mount_one(key, item)
+ elif isinstance(items, AsyncIterable):
async for key, item in items:
await _mount_one(key, item)
else:
@@ -551,6 +581,19 @@ async def mount_each(*pos_args: Any, **kwargs: Any) -> ComponentMountHandle:
return ComponentMountHandle(core_handles)
+@runtime_checkable
+class _ReadableByKey(Protocol):
+ """Items of a source that can read single keys, as well as list them all.
+ An update that runs only some components (``component_selector``) reads
+ just the keys it may run instead of listing everything."""
+
+ def __coco_items_for_keys__(
+ self, keys: list[StableKey], /
+ ) -> AsyncIterable[tuple[StableKey, Any]]:
+ """The items with these keys that the source holds, in any order."""
+ ...
+
+
# Keep map task failures wrapped so a user function can return an Exception
# object as a normal value without being confused with a failed task.
@dataclass(frozen=True, slots=True)
diff --git a/python/cocoindex/_internal/app.py b/python/cocoindex/_internal/app.py
index d7dca0b9..6ed8ec7f 100644
--- a/python/cocoindex/_internal/app.py
+++ b/python/cocoindex/_internal/app.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import contextlib
import os
import threading
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Iterable
from dataclasses import dataclass
from datetime import timedelta
from typing import (
@@ -25,6 +25,7 @@ from .function import (
create_core_component_processor,
fn_ret_deserializer,
)
+from .stable_path import StablePath
from .update_stats import (
UpdateSnapshot,
UpdateStats,
@@ -177,6 +178,28 @@ async def show_progress(
return pyvalue.get(fn_ret_deserializer(handle._main_fn)) # type: ignore[no-any-return]
+def _core_component_selector(
+ component_selector: Iterable[StablePath] | None,
+) -> list[core.StablePath] | None:
+ if component_selector is None:
+ return None
+ if isinstance(component_selector, (StablePath, str, bytes)):
+ raise TypeError(
+ "component_selector takes an iterable of StablePath values, got "
+ f"{component_selector!r}. Pass a list, e.g. "
+ '[coco.ROOT_PATH / "process" / key].'
+ )
+ paths: list[core.StablePath] = []
+ for path in component_selector:
+ if not isinstance(path, StablePath):
+ raise TypeError(
+ f"component_selector takes StablePath values, got {path!r}. "
+ 'Build one from coco.ROOT_PATH, e.g. coco.ROOT_PATH / "process" / key.'
+ )
+ paths.append(path._core)
+ return paths
+
+
@dataclass(frozen=True)
class AppConfig:
name: str
@@ -284,6 +307,7 @@ class App(Generic[P, R]):
full_reprocess: bool = False,
live: bool = False,
preview: bool = False,
+ component_selector: Iterable[StablePath] | None = None,
) -> UpdateHandle[R]:
"""
Start an update and return a handle for tracking progress and awaiting the result.
@@ -297,11 +321,17 @@ class App(Generic[P, R]):
after mark_ready).
preview: If True, compute target actions without applying them.
The handle's result will be a list of raw action objects.
+ component_selector: If given, run only these components and what is
+ needed to reach them, leaving every other component as it is: not
+ run, and its target states kept even if its source item is gone.
+ A path selects its whole subtree. See the "Updating part of an
+ app" section of the App docs.
Returns:
An UpdateHandle that provides access to stats(), watch(), and result().
"""
deadline_context = _deadline_for_engine()
+ core_selector = _core_component_selector(component_selector)
async def _init() -> core.UpdateHandle:
env, core_app = await self._get_core_env_app()
@@ -321,6 +351,7 @@ class App(Generic[P, R]):
preview=preview,
host_ctx=env._context_provider,
deadline=deadline_context,
+ component_selector=core_selector,
)
return UpdateHandle(
@@ -336,6 +367,7 @@ class App(Generic[P, R]):
full_reprocess: bool = False,
live: bool = False,
preview: bool = False,
+ component_selector: Iterable[StablePath] | None = None,
) -> R | list[Any]:
"""
Update the app synchronously (run the app once to process all pending changes).
@@ -349,10 +381,16 @@ class App(Generic[P, R]):
after mark_ready).
preview: If True, compute target actions without applying them.
Returns a list of raw action objects instead of the main function result.
+ component_selector: If given, run only these components and what is
+ needed to reach them, leaving every other component as it is: not
+ run, and its target states kept even if its source item is gone.
+ A path selects its whole subtree. See the "Updating part of an
+ app" section of the App docs.
Returns:
The result of the main function, or a list of actions in preview mode.
"""
+ core_selector = _core_component_selector(component_selector)
env, core_app = self._get_core_env_app_sync()
root_path = core.StablePath()
deadline_context = _deadline_for_engine()
@@ -375,6 +413,7 @@ class App(Generic[P, R]):
live=live,
preview=preview,
deadline=deadline_context,
+ component_selector=core_selector,
)
if preview:
return pyvalue # type: ignore[no-any-return]
diff --git a/python/cocoindex/_internal/core.pyi b/python/cocoindex/_internal/core.pyi
index 69279ba3..eb0863b8 100644
--- a/python/cocoindex/_internal/core.pyi
+++ b/python/cocoindex/_internal/core.pyi
@@ -55,6 +55,8 @@ R_co = TypeVar("R_co", covariant=True)
class StablePath:
def __new__(cls) -> StablePath: ...
def concat(self, part: StableKey) -> StablePath: ...
+ @staticmethod
+ def parse(text: str) -> StablePath: ...
def to_string(self) -> str: ...
def parts(self) -> list[StableKey]: ...
def __eq__(self, other: object) -> bool: ...
@@ -343,6 +345,7 @@ class App:
preview: bool = False,
*,
deadline: DeadlineContext,
+ component_selector: list[StablePath] | None = None,
) -> StoredValue | list[Any]: ...
def update_async(
self,
@@ -353,6 +356,7 @@ class App:
host_ctx: Any = None,
*,
deadline: DeadlineContext,
+ component_selector: list[StablePath] | None = None,
) -> UpdateHandle: ...
def drop(
self,
@@ -388,18 +392,33 @@ class LiveComponentController:
self, key: StableKey, value: bytes
) -> Coroutine[Any, Any, None]: ...
def start(self, process_live_fut: Any) -> None: ...
+ def skips_subpath(self, stable_path: StablePath) -> bool: ...
def mount_inner_live_async(
self, stable_path: StablePath
- ) -> Coroutine[Any, Any, tuple[LiveComponentController, ComponentMountHandle]]: ...
+ ) -> Coroutine[
+ Any, Any, tuple[LiveComponentController, ComponentMountHandle] | None
+ ]: ...
@property
def is_live(self) -> bool: ...
+def skips_mount(
+ stable_path: StablePath,
+ comp_ctx: ComponentProcessorContext,
+ fn_ctx: FnCallContext,
+) -> bool: ...
+def mount_each_keys(
+ stable_path: StablePath,
+ comp_ctx: ComponentProcessorContext,
+ fn_ctx: FnCallContext,
+) -> list[StableKey] | None: ...
def mount_live_async(
stable_path: StablePath,
comp_ctx: ComponentProcessorContext,
fn_ctx: FnCallContext,
live: bool,
-) -> Coroutine[Any, Any, tuple[LiveComponentController, ComponentMountHandle]]: ...
+) -> Coroutine[
+ Any, Any, tuple[LiveComponentController, ComponentMountHandle] | None
+]: ...
# --- TargetActionSink ---
class TargetActionSink:
diff --git a/python/cocoindex/_internal/live_component.py b/python/cocoindex/_internal/live_component.py
index 23403286..07c047f3 100644
--- a/python/cocoindex/_internal/live_component.py
+++ b/python/cocoindex/_internal/live_component.py
@@ -333,6 +333,9 @@ class LiveComponentOperator:
child_path = child_path.concat(part)
controller = self._require_controller()
+ # Asked before anything is prepared, as in `coco.mount`.
+ if controller.skips_subpath(child_path):
+ return ComponentMountHandle([])
# Slice F: branch on processor type. A LiveComponent class triggers
# the nested-mount path β€” we install a fresh inner controller at the
# child path under the parent's `update_full_lock`, then spawn the
@@ -340,10 +343,11 @@ class LiveComponentOperator:
# queued/coalesced dispatch path on the existing controller.
if is_live_component_class(processor_fn):
instance: Any = processor_fn(*args, **kwargs)
- (
- inner_controller,
- readiness_handle,
- ) = await controller.mount_inner_live_async(child_path)
+ mounted = await controller.mount_inner_live_async(child_path)
+ if mounted is None:
+ # The update's component selector leaves this component out.
+ return ComponentMountHandle([])
+ inner_controller, readiness_handle = mounted
inner_operator = LiveComponentOperator(
inner_controller, instance, self._env, child_path
)
diff --git a/python/cocoindex/cli.py b/python/cocoindex/cli.py
index f94c3f9f..fe123ac4 100644
--- a/python/cocoindex/cli.py
+++ b/python/cocoindex/cli.py
@@ -834,13 +834,25 @@ def show(
)
+def _parse_selected_path(text: str) -> StablePath:
+ try:
+ return StablePath(_core.StablePath.parse(text))
+ except ValueError as e:
+ raise click.BadParameter(str(e), param_hint="'--select'") from e
+
+
def _parse_stable_path(path_str: str) -> StablePath:
"""Parse a CLI stable path string into a StablePath.
- Accepts formats like:
- /"files"/"file1.txt" (quoted parts, as displayed by StablePath.__str__)
- /files/file1.txt (unquoted parts)
+ Reads the path as `cocoindex show` prints it, as `--select` does:
+ /@process_file/"docs/a.md" (a Symbol, then a string)
+ Text that is not in that form is read the older way, every part a string:
+ /files/file1.txt
"""
+ try:
+ return StablePath(_core.StablePath.parse(path_str))
+ except ValueError:
+ pass
path = StablePath()
# Strip leading slash
stripped = path_str.strip("/")
@@ -1139,6 +1151,19 @@ async def _stop_all_environments() -> None:
default=False,
help="Compute target actions without applying them. Prints planned actions.",
)
+ "--select",
+ "select",
+ multiple=True,
+ metavar="PATH",
+ callback=lambda _ctx, _param, value: [_parse_selected_path(v) for v in value],
+ help=(
+ "Run only the component at PATH and the components below it; repeat "
+ "to run several. Write PATH as `cocoindex show` prints it, such as "
+ "'/@process_file/\"docs/a.md\"'. Other components are not run and "
+ "not treated as gone."
+ ),
+)
def update(
app_target: str,
force: bool,
@@ -1147,6 +1172,7 @@ def update(
full_reprocess: bool,
live: bool,
preview: bool,
+ select: list[StablePath],
) -> None:
"""
Run an app in catch-up mode. With --live, run in live mode.
@@ -1157,6 +1183,9 @@ def update(
raise click.UsageError("--preview and --reset cannot be used together.")
if preview and live:
raise click.UsageError("--preview and --live cannot be used together.")
+ if select and reset:
+ raise click.UsageError("--select and --reset cannot be used together.")
+ component_selector = select or None
app = _load_app(app_target)
@@ -1173,6 +1202,7 @@ def update(
handle = app.update(
full_reprocess=full_reprocess,
preview=True,
+ component_selector=component_selector,
)
started = time.monotonic()
actions: list[Any] = await handle.result()
@@ -1205,6 +1235,7 @@ def update(
handle = app.update(
full_reprocess=full_reprocess,
live=live,
+ component_selector=component_selector,
)
if not quiet:
await show_progress(handle)
diff --git a/python/cocoindex/connectors/localfs/_source.py b/python/cocoindex/connectors/localfs/_source.py
index 653ac59a..2bb89557 100644
--- a/python/cocoindex/connectors/localfs/_source.py
+++ b/python/cocoindex/connectors/localfs/_source.py
@@ -169,7 +169,7 @@ class DirWalker:
"""
if self._live:
return _LiveDirItems(self)
- return self._items_iter()
+ return _DirItems(self)
async def _items_iter(self) -> AsyncIterator[tuple[str, File]]:
"""Async iterate over (key, file) pairs (catch-up path)."""
@@ -177,6 +177,81 @@ class DirWalker:
async for file in self:
yield (file.file_path.path.relative_to(root_path).as_posix(), file)
+ def _read_keys_sync(self, keys: list[object]) -> list[tuple[str, File]]:
+ """The files the walk would yield under these keys, found without
+ walking: each key is a path relative to the root, as the walk writes
+ it. A key the walk would not yield is left out."""
+ root_resolved = self._root_path.resolve()
+ if not root_resolved.is_dir():
+ raise ValueError(f"Path is not a directory: {root_resolved}")
+ root_stat = root_resolved.stat()
+ # The entry names of each directory read so far: a part must name an
+ # entry exactly, as the walk would list it. A case-insensitive file
+ # system would otherwise find `a.md` under the key `A.md`.
+ names: dict[Path, set[str]] = {}
+ out: list[tuple[str, File]] = []
+ for key in keys:
+ if not isinstance(key, str):
+ continue
+ relative_path = pathlib.PurePosixPath(key)
+ parts = relative_path.parts
+ if (
+ not parts
+ or relative_path.is_absolute()
+ or relative_path.as_posix() != key
+ or ".." in parts
+ or (len(parts) > 1 and not self._recursive)
+ ):
+ continue
+ file = self._read_one_sync(root_resolved, root_stat, parts, names)
+ if file is not None:
+ out.append((key, file))
+ return out
+
+ def _read_one_sync(
+ self,
+ root_resolved: Path,
+ root_stat: os.stat_result,
+ parts: tuple[str, ...],
+ names: dict[Path, set[str]],
+ ) -> File | None:
+ # Paths are built as the walk builds them (`relative_to` the resolved
+ # root), so that a file's memo key is the walk's: a Path pickles its
+ # raw segments on Python 3.13+, and `Path("a", "b")` differs there
+ # from `Path("a/b")`.
+ relative_path = root_resolved.joinpath(*parts).relative_to(root_resolved)
+ # Each directory on the way must be one the walk enters: included, and
+ # not one of its own ancestors (a symlink cycle).
+ ancestor_ids = {(root_stat.st_dev, root_stat.st_ino)}
+ current = root_resolved
+ try:
+ for i, part in enumerate(parts):
+ if current not in names:
+ names[current] = set(os.listdir(current))
+ if part not in names[current]:
+ return None
+ if i == len(parts) - 1:
+ break
+ current = current / part
+ if not current.is_dir() or not self._path_matcher.is_dir_included(
+ current.relative_to(root_resolved)
+ ):
+ return None
+ stat = current.stat()
+ entry_id = (stat.st_dev, stat.st_ino)
+ if entry_id in ancestor_ids:
+ return None
+ ancestor_ids.add(entry_id)
+ entry = root_resolved / relative_path
+ if not entry.is_file() or not self._path_matcher.is_file_included(
+ relative_path
+ ):
+ return None
+ stat = entry.stat()
+ except OSError:
+ return None
+ return File(self._root_path / relative_path, _stat=stat)
+
async def __aiter__(self) -> AsyncIterator[File]:
"""Asynchronously iterate over files, yielding File objects."""
from cocoindex.connectorkits.async_adapters import sync_to_async_iter
@@ -185,6 +260,23 @@ class DirWalker:
yield file
+class _DirItems(_AsyncIterable[tuple[str, File]]):
+ """The ``(relative_path, File)`` pairs of a walk. An update that runs only
+ some components reads just their files instead of walking the tree."""
+
+ def __init__(self, walker: DirWalker) -> None:
+ self._walker = walker
+
+ def __aiter__(self) -> AsyncIterator[tuple[str, File]]:
+ return self._walker._items_iter()
+
+ async def __coco_items_for_keys__(
+ self, keys: list[object]
+ ) -> AsyncIterator[tuple[str, File]]:
+ for item in await asyncio.to_thread(self._walker._read_keys_sync, keys):
+ yield item
+
+
def _stop_observer(observer: object, *, join_timeout: float = 5.0) -> None:
"""Stop and join a watchdog observer.
diff --git a/python/tests/cli/select_app.py b/python/tests/cli/select_app.py
new file mode 100644
index 00000000..79a542be
--- /dev/null
+++ b/python/tests/cli/select_app.py
@@ -0,0 +1,36 @@
+"""Test module for `cocoindex update --select`: one output file per input file."""
+
+from __future__ import annotations
+
+import pathlib
+from typing import Iterator
+
+import cocoindex as coco
+from cocoindex.connectors import localfs
+
+
+def coco_lifespan(builder: coco.EnvironmentBuilder) -> Iterator[None]:
+ builder.settings.db_path = pathlib.Path("./cocoindex_select.db")
+ yield
+
+
+async def process(file: localfs.File, target: localfs.DirTarget) -> None:
+ name = file.file_path.path.name
+ target.declare_file(name, (await file.read_text()).upper())
+
+
+async def app_main() -> None:
+ target = await coco.use_mount(
+ coco.component_subpath("setup"),
+ localfs.declare_dir_target,
+ pathlib.Path("./out_select"),
+ )
+ files = localfs.walk_dir(pathlib.Path("./in_select"))
+ # No subpath: the items mount under the Symbol `process`.
+ await coco.mount_each(process, files.items(), target)
+
+
+app = coco.App(coco.AppConfig(name="SelectApp"), app_main)
diff --git a/python/tests/cli/test_cli.py b/python/tests/cli/test_cli.py
index 273fbbed..fdba66cf 100644
--- a/python/tests/cli/test_cli.py
+++ b/python/tests/cli/test_cli.py
@@ -638,6 +638,101 @@ class TestUpdateFlags:
)
+class TestSelect:
+ """Tests for `cocoindex update --select`."""
+
+ def _setup(self, tmp_path: Path) -> tuple[Path, Path]:
+ (tmp_path / "select_app.py").write_text(
+ (TEST_DIR / "select_app.py").read_text()
+ )
+ src, out = tmp_path / "in_select", tmp_path / "out_select"
+ src.mkdir()
+ (src / "a.txt").write_text("a1")
+ (src / "b.txt").write_text("b1")
+ run_cli("update", "./select_app.py", cwd=tmp_path)
+ assert (out / "a.txt").read_text() == "A1"
+ (src / "a.txt").write_text("a2")
+ (src / "b.txt").write_text("b2")
+ return src, out
+
+ def test_select_runs_only_the_selected_component(self, tmp_path: Path) -> None:
+ src, out = self._setup(tmp_path)
+ # The path as `cocoindex show` prints it.
+ shown = run_cli("show", "./select_app.py", cwd=tmp_path).stdout
+ assert '/@process/"a.txt"' in shown
+ # `show PATH` reads the same form; the older unquoted form still works.
+ detail = run_cli(
+ "show", "./select_app.py", '/@process/"a.txt"', cwd=tmp_path
+ ).stdout
+ assert "processor:process" in detail
+ legacy = run_cli("show", "./select_app.py", "/setup", cwd=tmp_path).stdout
+ assert "processor:declare_dir_target" in legacy
+
+ run_cli(
+ "update", "./select_app.py", "--select", '/@process/"a.txt"', cwd=tmp_path
+ )
+ assert (out / "a.txt").read_text() == "A2"
+ assert (out / "b.txt").read_text() == "B1"
+
+ (src / "a.txt").unlink()
+ run_cli(
+ "update",
+ "./select_app.py",
+ "--select",
+ '/@process/"a.txt"',
+ "--select",
+ '/@process/"b.txt"',
+ cwd=tmp_path,
+ )
+ assert not (out / "a.txt").exists()
+ assert (out / "b.txt").read_text() == "B2"
+
+ def test_select_with_preview_plans_only_the_selected_component(
+ self, tmp_path: Path
+ ) -> None:
+ _, out = self._setup(tmp_path)
+ result = run_cli(
+ "update",
+ "./select_app.py",
+ "--preview",
+ "--select",
+ '/@process/"b.txt"',
+ cwd=tmp_path,
+ )
+ assert "b.txt" in result.stdout
+ assert "a.txt" not in result.stdout
+ assert (out / "b.txt").read_text() == "B1"
+
+ def test_select_rejects_a_path_it_cannot_parse(self, tmp_path: Path) -> None:
+ self._setup(tmp_path)
+ result = run_cli(
+ "update",
+ "./select_app.py",
+ "--select",
+ "/process/a.txt",
+ cwd=tmp_path,
+ check=False,
+ )
+ assert result.returncode != 0
+ assert "--select" in result.stderr
+ assert "`@process`" in result.stderr
+
+ def test_select_and_reset_cannot_be_combined(self, tmp_path: Path) -> None:
+ self._setup(tmp_path)
+ result = run_cli(
+ "update",
+ "./select_app.py",
+ "--reset",
+ "-f",
+ "--select",
+ "/",
+ cwd=tmp_path,
+ check=False,
+ )
+ assert result.returncode != 0
+ assert "--select and --reset cannot be used together" in result.stderr
+
+
class TestFullReprocess:
"""Tests for --full-reprocess flag behavior."""
diff --git a/python/tests/core/test_component_selector.py b/python/tests/core/test_component_selector.py
new file mode 100644
index 00000000..217cca2e
--- /dev/null
+++ b/python/tests/core/test_component_selector.py
@@ -0,0 +1,1204 @@
+"""Tests for sliced execution: ``App.update(component_selector=...)``.
+
+An unselected component is neither run nor treated as gone. The root, ``use_mount``
+children and the ancestors of a selected path still run, and a run that may have
+left children unrun stores no memo.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex._internal.inspect_api import list_stable_paths_sync
+from cocoindex.resources.live_map import LiveMap
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+coco_env = common.create_test_env(__file__)
+
+_source: dict[Any, Any] = {}
+_runs: list[str] = []
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ GlobalDictTarget.store.sink_exception = False
+ _source.clear()
+ _runs.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _planned(actions: Any) -> dict[str, Any]:
+ return {key: value.data for key, value in actions}
+
+
+def _declare(key: Any, value: Any) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(str(key), value))
+
+
+def _entries() -> list[tuple[Any, tuple[Any, Any]]]:
+ return [(k, (k, v)) for k, v in _source.items()]
+
+
+async def _item(entry: tuple[Any, Any]) -> None:
+ key, value = entry
+ _runs.append(str(key))
+ _declare(key, value)
+
+
+async def _memo_item(entry: tuple[Any, Any]) -> None:
+ key, value = entry
+ _runs.append(str(key))
+ _declare(key, value)
+
+
+def _items_path(key: Any) -> coco.StablePath:
+ path: coco.StablePath = coco.ROOT_PATH / "items" / key
+ return path
+
+
+async def _mount_each_main() -> None:
+ _runs.append("root")
+ await coco.mount_each(coco.component_subpath("items"), _item, _entries())
+
+
+def _app(name: str, main: Any = _mount_each_main, *args: Any) -> coco.App[Any, Any]:
+ return coco.App(
+ coco.AppConfig(name=f"test_selector_{name}", environment=coco_env), main, *args
+ )
+
+
+def _run_all_then_clear_log(app: coco.App[Any, Any]) -> None:
+ app.update_blocking()
+ _runs.clear()
+
+
+# ---------------------------------------------------------------------------
+# The acceptance scenarios
+# ---------------------------------------------------------------------------
+
+
+def test_unselected_source_changed_is_not_run_and_keeps_its_output() -> None:
+ _source.update(a=1, b=1)
+ app = _app("unselected_changed")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[_items_path("a")])
+
+ assert _runs == ["root", "a"]
+ assert _stored() == {"a": 2, "b": 1}
+
+
+def test_unselected_source_deleted_is_not_run_and_keeps_its_target_states() -> None:
+ _source.update(a=1, b=1)
+ app = _app("unselected_deleted")
+ _run_all_then_clear_log(app)
+ paths_before = {str(p) for p in list_stable_paths_sync(app)}
+
+ del _source["b"]
+ app.update_blocking(component_selector=[_items_path("a")])
+
+ assert _runs == ["root", "a"]
+ assert _stored() == {"a": 1, "b": 1}
+ assert {str(p) for p in list_stable_paths_sync(app)} == paths_before
+
+ # A later update that covers it sees it gone.
+ app.update_blocking()
+ assert _stored() == {"a": 1}
+
+
+def test_unselected_new_item_leaves_no_trace() -> None:
+ _source.update(a=1)
+ app = _app("unselected_new")
+ _run_all_then_clear_log(app)
+ paths_before = {str(p) for p in list_stable_paths_sync(app)}
+
+ _source["new"] = 1
+ app.update_blocking(component_selector=[_items_path("a")])
+
+ assert _runs == ["root", "a"]
+ assert _stored() == {"a": 1}
+ assert {str(p) for p in list_stable_paths_sync(app)} == paths_before
+
+
+def test_selected_new_item_runs() -> None:
+ _source.update(a=1)
+ app = _app("selected_new")
+ _run_all_then_clear_log(app)
+
+ _source["new"] = 1
+ app.update_blocking(component_selector=[_items_path("new")])
+
+ assert _runs == ["root", "new"]
+ assert _stored() == {"a": 1, "new": 1}
+
+
+def test_selected_changed_updates_and_selected_unchanged_memo_hits() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("items"), _memo_item, _entries())
+
+ _source.update(a=1, b=1, c=1)
+ app = _app("selected_memo", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, c=2)
+ handle = app.update(component_selector=[_items_path("a"), _items_path("b")])
+ asyncio.run(_finish(handle))
+
+ assert _runs == ["a"]
+ assert _stored() == {"a": 2, "b": 1, "c": 1}
+ stats = handle.stats()
+ assert stats is not None
+ assert stats.total.num_unchanged == 1
+
+
+async def _finish(handle: coco.UpdateHandle[Any]) -> None:
+ await handle.result()
+
+
+def test_selected_source_deleted_is_deleted() -> None:
+ _source.update(a=1, b=1)
+ app = _app("selected_deleted")
+ _run_all_then_clear_log(app)
+
+ del _source["a"]
+ del _source["b"]
+ app.update_blocking(component_selector=[_items_path("a")])
+
+ assert _stored() == {"b": 1}
+
+
+def test_select_by_several_paths() -> None:
+ _source.update(a=1, b=1, c=1)
+ app = _app("several")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2, c=2)
+ app.update_blocking(component_selector=[_items_path("a"), _items_path("c")])
+
+ assert sorted(_runs) == ["a", "c", "root"]
+ assert _stored() == {"a": 2, "b": 1, "c": 2}
+
+
+def test_select_by_subtree_prefix() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("items"), _item, _entries())
+ await coco.mount(
+ coco.component_subpath("other"), _item, ("other", _source["a"])
+ )
+
+ _source.update(a=1, b=1)
+ app = _app("prefix", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items"])
+
+ assert sorted(_runs) == ["a", "b"]
+ assert _stored() == {"a": 2, "b": 2, "other": 1}
+
+
+def test_selector_takes_any_iterable_of_paths() -> None:
+ _source.update(a=1, b=1)
+ app = _app("iterable")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=(_items_path(k) for k in ["a"]))
+ assert _stored() == {"a": 2, "b": 1}
+
+
+def test_paths_from_inspection_select_the_components_they_name() -> None:
+ _source.update(a=1, b=1)
+ app = _app("inspection")
+ _run_all_then_clear_log(app)
+
+ listed = [p for p in list_stable_paths_sync(app) if str(p).endswith('"a"')]
+ assert len(listed) == 1
+
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=listed)
+ assert _stored() == {"a": 2, "b": 1}
+
+
+ "key",
+ [7, True, ("tuple", 1), b"bytes", None],
+ ids=["int", "bool", "tuple", "bytes", "none"],
+)
+def test_keys_of_any_type_select_by_value(key: Any) -> None:
+ other = "other"
+ _source.update({key: 1, other: 1})
+ app = _app(f"key_{type(key).__name__}")
+ _run_all_then_clear_log(app)
+
+ _source.update({key: 2, other: 2})
+ app.update_blocking(component_selector=[_items_path(key)])
+
+ assert _stored() == {str(key): 2, other: 1}
+
+
+def test_a_key_that_prints_the_same_is_not_selected() -> None:
+ _source.update({1: 1, "1x": 1})
+ app = _app("key_type_distinct")
+ _run_all_then_clear_log(app)
+
+ _source.update({1: 2})
+ app.update_blocking(component_selector=[_items_path("1")])
+
+ assert _stored() == {"1": 1, "1x": 1}
+
+
+def test_default_subpath_is_a_symbol_key() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(_item, _entries())
+
+ _source.update(a=1, b=1)
+ app = _app("symbol", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / coco.Symbol("_item") / "a"]
+ )
+ assert _stored() == {"a": 2, "b": 1}
+
+
+def test_rejects_anything_but_paths_early() -> None:
+ app = _app("reject")
+ with pytest.raises(TypeError, match="takes an iterable of StablePath values"):
+ app.update_blocking(component_selector="items/a") # type: ignore[arg-type]
+ with pytest.raises(TypeError, match="takes StablePath values"):
+ app.update(component_selector=["items/a"]) # type: ignore[list-item]
+ with pytest.raises(TypeError, match="takes an iterable of StablePath values"):
+ app.update(component_selector=_items_path("a")) # type: ignore[arg-type]
+
+
+# ---------------------------------------------------------------------------
+# mount() and nesting
+# ---------------------------------------------------------------------------
+
+
+async def _parent() -> None:
+ _runs.append("parent")
+ await coco.mount_each(coco.component_subpath("kids"), _item, _entries())
+
+
+async def _nested_main() -> None:
+ _runs.append("root")
+ await coco.mount(coco.component_subpath("parent"), _parent)
+ await coco.mount(
+ coco.component_subpath("sibling"), _item, ("sibling", _source["a"])
+ )
+
+
+def test_plain_mount_honours_the_selector() -> None:
+ _source.update(a=1)
+ app = _app("plain_mount", _nested_main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "sibling"])
+
+ assert sorted(_runs) == ["root", "sibling"]
+ assert _stored() == {"a": 1, "sibling": 2}
+
+
+def test_selected_child_under_unselected_parent_runs_the_parent_to_reach_it() -> None:
+ _source.update(a=1, b=1)
+ app = _app("nested", _nested_main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],
+ )
+
+ assert sorted(_runs) == ["a", "parent", "root"]
+ assert _stored() == {"a": 2, "b": 1, "sibling": 1}
+
+
+def test_selecting_a_parent_selects_its_subtree() -> None:
+ _source.update(a=1, b=1)
+ app = _app("parent_subtree", _nested_main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "parent"])
+
+ assert sorted(_runs) == ["a", "b", "parent", "root"]
+ assert _stored() == {"a": 2, "b": 2, "sibling": 1}
+
+
+def test_ancestor_no_longer_mounted_keeps_its_whole_subtree() -> None:
+ mounted = [True]
+
+ @coco.fn
+ async def main() -> None:
+ if mounted[0]:
+ await coco.mount(coco.component_subpath("parent"), _parent)
+
+ _source.update(a=1, b=1)
+ app = _app("ancestor_gone", main)
+ _run_all_then_clear_log(app)
+
+ mounted[0] = False
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],
+ )
+ assert _runs == []
+ assert _stored() == {"a": 1, "b": 1}
+
+ app.update_blocking()
+ assert _stored() == {}
+
+
+def test_selected_gone_under_a_directory_is_deleted_and_its_sibling_kept() -> None:
+ @coco.fn
+ async def main() -> None:
+ with coco.component_subpath("dir", "deep"):
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath(key), _item, (key, value))
+
+ _source.update(a=1, b=1)
+ app = _app("directory", main)
+ _run_all_then_clear_log(app)
+
+ _source.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "dir" / "deep" / "a"])
+
+ assert _stored() == {"b": 1}
+
+ app.update_blocking()
+ assert _stored() == {}
+
+
+def test_unselected_component_replaced_by_a_directory_stays_until_covered() -> None:
+ @coco.fn
+ async def as_component() -> None:
+ _declare("x", 1)
+
+ use_directory = [False]
+
+ @coco.fn
+ async def main() -> None:
+ if use_directory[0]:
+ await coco.mount(coco.component_subpath("x", "y"), _item, ("y", 1))
+ else:
+ await coco.mount(coco.component_subpath("x"), as_component)
+
+ app = _app("demote", main)
+ _run_all_then_clear_log(app)
+ assert _stored() == {"x": 1}
+
+ use_directory[0] = True
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x" / "y"])
+ assert _stored() == {"x": 1, "y": 1}
+
+ app.update_blocking()
+ assert _stored() == {"y": 1}
+
+
+# ---------------------------------------------------------------------------
+# use_mount and the root always run
+# ---------------------------------------------------------------------------
+
+
+async def _helper() -> int:
+ _runs.append("helper")
+ await coco.mount_each(coco.component_subpath("kids"), _item, _entries())
+ return 7
+
+
+def test_use_mount_runs_for_its_value_and_its_mounted_children_stay_filtered() -> None:
+ received: list[int] = []
+
+ @coco.fn
+ async def main() -> None:
+ received.append(await coco.use_mount(coco.component_subpath("helper"), _helper))
+ await coco.mount(coco.component_subpath("sibling"), _item, ("sibling", 1))
+
+ _source.update(a=1)
+ app = _app("use_mount", main)
+ _run_all_then_clear_log(app)
+ received.clear()
+
+ _source.update(a=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "sibling"])
+
+ assert received == [7]
+ assert sorted(_runs) == ["helper", "sibling"]
+ assert _stored() == {"a": 1, "sibling": 1}
+
+
+def test_selected_under_use_mount_child_runs() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.use_mount(coco.component_subpath("helper"), _helper)
+
+ _source.update(a=1, b=1)
+ app = _app("use_mount_selected", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "helper" / "kids" / "a"],
+ )
+
+ assert sorted(_runs) == ["a", "helper"]
+ assert _stored() == {"a": 2, "b": 1}
+
+
+def test_memoized_use_mount_child_without_children_stays_reusable_when_unchanged() -> (
+ None
+):
+ @coco.fn(memo=True)
+ async def memo_helper() -> int:
+ _runs.append("memo_helper")
+ return 7
+
+ @coco.fn
+ async def main() -> None:
+ await coco.use_mount(coco.component_subpath("helper"), memo_helper)
+ await coco.mount_each(coco.component_subpath("items"), _item, _entries())
+
+ _source.update(a=1)
+ app = _app("memo_use_mount_hit", main)
+ _run_all_then_clear_log(app)
+
+ app.update_blocking(component_selector=[_items_path("a")])
+ assert _runs == ["a"]
+
+
+def test_fan_in_after_a_skipped_mount_gets_a_ready_handle() -> None:
+ collected: list[str] = []
+
+ @coco.fn
+ async def fan_in(values: list[Any]) -> None:
+ collected.append(f"fan_in:{values}")
+
+ @coco.fn
+ async def main() -> None:
+ handle = await coco.mount_each(
+ coco.component_subpath("items"), _item, _entries()
+ )
+ await handle.ready()
+ await coco.use_mount(coco.component_subpath("fan_in"), fan_in, sorted(_source))
+
+ _source.update(a=1, b=1)
+ app = _app("fan_in", main)
+ _run_all_then_clear_log(app)
+ collected.clear()
+
+ app.update_blocking(component_selector=[_items_path("a")])
+
+ assert _runs == ["a"]
+ assert collected == ["fan_in:['a', 'b']"]
+
+
+def test_root_path_selects_everything_like_no_selector() -> None:
+ _source.update(a=1, b=1)
+ app = _app("root_selected")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2)
+ del _source["b"]
+ app.update_blocking(component_selector=[coco.ROOT_PATH])
+
+ assert sorted(_runs) == ["a", "root"]
+ assert _stored() == {"a": 2}
+
+
+def test_empty_selector_runs_only_the_root_and_touches_nothing() -> None:
+ _source.update(a=1, b=1)
+ app = _app("empty")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2)
+ del _source["b"]
+ app.update_blocking(component_selector=[])
+
+ assert _runs == ["root"]
+ assert _stored() == {"a": 1, "b": 1}
+
+
+def test_path_that_does_not_exist_selects_nothing_and_is_no_error() -> None:
+ _source.update(a=1, b=1)
+ app = _app("no_such_path")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2)
+ app.update_blocking(
+ component_selector=[_items_path("nope"), coco.ROOT_PATH / "nope" / "x"],
+ )
+
+ assert _runs == ["root"]
+ assert _stored() == {"a": 1, "b": 1}
+
+
+def test_none_selector_is_a_plain_update() -> None:
+ _source.update(a=1, b=1)
+ app = _app("none")
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2)
+ del _source["b"]
+ app.update_blocking(component_selector=None)
+
+ assert sorted(_runs) == ["a", "root"]
+ assert _stored() == {"a": 2}
+
+
+# ---------------------------------------------------------------------------
+# Memo: a run that may have left children unrun must not claim its subtree
+# ---------------------------------------------------------------------------
+
+
+_version = [1]
+
+
+async def _memo_parent(version: int) -> None:
+ _runs.append("memo_parent")
+ await coco.mount_each(coco.component_subpath("kids"), _item, _entries())
+
+
+async def _memo_parent_main() -> None:
+ await coco.mount(coco.component_subpath("parent"), _memo_parent, _version[0])
+
+
+def test_partial_run_of_a_memoized_parent_stores_no_memo() -> None:
+ _version[0] = 1
+ _source.update(a=1, b=1)
+ app = _app("memo_parent_no_store", _memo_parent_main)
+ _run_all_then_clear_log(app)
+
+ _version[0] = 2
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],
+ )
+ assert _stored() == {"a": 2, "b": 1}
+
+ # Same input as the partial run. A memo from it would hide "b" for good.
+ _runs.clear()
+ app.update_blocking()
+ assert "memo_parent" in _runs
+ assert _stored() == {"a": 2, "b": 2}
+
+ # The full update stored a memo again.
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == []
+
+
+def test_partial_run_drops_the_memo_of_an_unchanged_input() -> None:
+ _version[0] = 1
+ _source.update(a=1, b=1)
+ app = _app("memo_parent_drop", _memo_parent_main)
+ _run_all_then_clear_log(app)
+
+ # `full_reprocess` runs the parent under its stored memo key, so only the
+ # partial run itself can retire that memo.
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ full_reprocess=True,
+ component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],
+ )
+ assert _stored() == {"a": 2, "b": 1}
+
+ _runs.clear()
+ app.update_blocking()
+ assert "memo_parent" in _runs
+ assert _stored() == {"a": 2, "b": 2}
+
+
+def test_memo_hit_on_an_ancestor_stands_in_for_its_selected_descendants() -> None:
+ _version[0] = 1
+ _source.update(a=1, b=1)
+ app = _app("memo_parent_hit", _memo_parent_main)
+ _run_all_then_clear_log(app)
+
+ # As in a plain update: the memo says the subtree is up to date.
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],
+ )
+ assert _runs == []
+
+
+def test_selected_subtree_of_a_memoized_parent_stores_its_memo() -> None:
+ _version[0] = 1
+ _source.update(a=1, b=1)
+ app = _app("memo_parent_selected", _memo_parent_main)
+ _run_all_then_clear_log(app)
+
+ _version[0] = 2
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "parent"])
+ assert _stored() == {"a": 2, "b": 2}
+
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == []
+
+
+def test_memoized_function_that_mounts_is_rejected_even_if_its_mounts_are_skipped() -> (
+ None
+):
+ @coco.fn(memo=True)
+ async def mounting_fn() -> None:
+ await coco.mount_each(coco.component_subpath("items"), _item, _entries())
+
+ @coco.fn
+ async def main() -> None:
+ await mounting_fn()
+
+ _source.update(a=1)
+ app = _app("memo_fn", main)
+ with pytest.raises(ValueError, match="mounted child components"):
+ app.update_blocking(component_selector=[_items_path("nope")])
+
+
+def test_full_reprocess_covers_only_what_is_selected() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("items"), _memo_item, _entries())
+
+ _source.update(a=1, b=1)
+ app = _app("full_reprocess", main)
+ _run_all_then_clear_log(app)
+
+ app.update_blocking(full_reprocess=True, component_selector=[_items_path("a")])
+ assert _runs == ["a"]
+
+ # "b" was not reprocessed, so its memo still holds.
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == []
+
+
+# ---------------------------------------------------------------------------
+# Preview
+# ---------------------------------------------------------------------------
+
+
+def test_preview_returns_actions_of_selected_paths_and_applies_nothing() -> None:
+ _source.update(a=1, b=1, c=1)
+ app = _app("preview")
+ _run_all_then_clear_log(app)
+ paths_before = {str(p) for p in list_stable_paths_sync(app)}
+
+ _source.update(a=2, b=2, c=2)
+ actions = app.update_blocking(
+ preview=True,
+ component_selector=[_items_path("a"), _items_path("c")],
+ )
+
+ assert _planned(actions) == {"a": 2, "c": 2}
+ assert sorted(_runs) == ["a", "c", "root"]
+ assert _stored() == {"a": 1, "b": 1, "c": 1}
+ assert {str(p) for p in list_stable_paths_sync(app)} == paths_before
+
+ # A preview leaves nothing behind: the real update still sees the changes.
+ app.update_blocking()
+ assert _stored() == {"a": 2, "b": 2, "c": 2}
+
+
+async def test_preview_async_composes_with_the_selector() -> None:
+ _source.update(a=1, b=1)
+ app = _app("preview_async")
+ await app.update()
+
+ _source.update(a=2, b=2)
+ actions = await app.update(preview=True, component_selector=[_items_path("b")])
+
+ assert _planned(actions) == {"b": 2}
+ assert _stored() == {"a": 1, "b": 1}
+
+
+def test_preview_of_an_unselected_deleted_item_plans_nothing() -> None:
+ _source.update(a=1, b=1)
+ app = _app("preview_unselected_deleted")
+ _run_all_then_clear_log(app)
+
+ del _source["b"]
+ actions = app.update_blocking(preview=True, component_selector=[_items_path("a")])
+
+ assert actions == []
+ assert _stored() == {"a": 1, "b": 1}
+
+
+def test_preview_does_not_plan_deletes_of_selected_gone_components() -> None:
+ # As in a preview without a selector: the deletes of the components a run
+ # no longer mounts are not previewed.
+ _source.update(a=1)
+ app = _app("preview_selected_deleted")
+ _run_all_then_clear_log(app)
+
+ del _source["a"]
+ actions = app.update_blocking(preview=True, component_selector=[_items_path("a")])
+
+ assert actions == []
+ assert _stored() == {"a": 1}
+
+
+def test_preview_includes_the_own_changes_of_the_ancestors_that_run() -> None:
+ @coco.fn
+ async def main() -> None:
+ _declare("root_own", _source["a"])
+ await coco.mount_each(coco.component_subpath("items"), _item, _entries())
+
+ _source.update(a=1, b=1)
+ app = _app("preview_ancestor", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ actions = app.update_blocking(preview=True, component_selector=[_items_path("a")])
+
+ assert _planned(actions) == {"a": 2, "root_own": 2}
+
+
+# ---------------------------------------------------------------------------
+# Stats groups, failures, concurrent updates, shared target states
+# ---------------------------------------------------------------------------
+
+
+async def test_stats_groups_split_and_skip_cleanly() -> None:
+ group_stats: dict[str, Any] = {}
+
+ @coco.fn
+ async def main() -> None:
+ with coco.stats_group("first") as first:
+ await coco.mount_each(coco.component_subpath("first"), _item, _entries())
+ with coco.stats_group("second") as second:
+ await coco.mount_each(
+ coco.component_subpath("second"), _item, [("b", ("second_b", 1))]
+ )
+ group_stats["first"] = first
+ group_stats["second"] = second
+
+ _source.update(a=1)
+ app = _app("stats_groups", main)
+ await app.update()
+ _runs.clear()
+
+ await app.update(component_selector=[coco.ROOT_PATH / "second" / "b"])
+
+ assert _runs == ["second_b"]
+ first_stats = group_stats["first"].stats()
+ second_stats = group_stats["second"].stats()
+ assert first_stats is None or first_stats.total.num_execution_starts == 0
+ assert second_stats is not None
+ assert second_stats.total.num_execution_starts == 1
+
+
+def test_failing_selected_component_leaves_the_rest_and_recovers() -> None:
+ failing = [True]
+
+ @coco.fn
+ async def flaky(entry: tuple[str, int]) -> None:
+ key, value = entry
+ _runs.append(key)
+ if key == "a" and failing[0]:
+ raise ValueError("injected")
+ _declare(key, value)
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("items"), flaky, _entries())
+
+ failing[0] = False
+ _source.update(a=1, b=1)
+ app = _app("failure", main)
+ _run_all_then_clear_log(app)
+
+ failing[0] = True
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[_items_path("a")])
+ assert _runs == ["a"]
+ assert _stored() == {"a": 1, "b": 1}
+
+ failing[0] = False
+ app.update_blocking()
+ assert _stored() == {"a": 2, "b": 2}
+
+
+def test_interrupted_selected_commit_is_finished_by_the_next_run() -> None:
+ _source.update(a=1, b=1)
+ app = _app("interrupted")
+ _run_all_then_clear_log(app)
+
+ # The sink fails after pre-commit: "a" keeps its staged, uncommitted state.
+ _source.update(a=2, b=2)
+ GlobalDictTarget.store.sink_exception = True
+ app.update_blocking(component_selector=[_items_path("a")])
+ GlobalDictTarget.store.sink_exception = False
+ assert _stored() == {"a": 1, "b": 1}
+
+ app.update_blocking(component_selector=[_items_path("a")])
+ assert _stored() == {"a": 2, "b": 1}
+
+
+def test_tombstone_left_by_a_failed_delete_waits_for_a_run_that_covers_it() -> None:
+ _source.update(a=1, b=1)
+ app = _app("tombstone")
+ _run_all_then_clear_log(app)
+
+ # A plain update tombstones "b", and its delete fails.
+ del _source["b"]
+ GlobalDictTarget.store.sink_exception = True
+ app.update_blocking()
+ GlobalDictTarget.store.sink_exception = False
+ assert _stored() == {"a": 1, "b": 1}
+
+ # This run's GC sweep leaves the tombstone: "b" is not selected.
+ app.update_blocking(component_selector=[_items_path("a")])
+ assert _stored() == {"a": 1, "b": 1}
+
+ app.update_blocking(component_selector=[_items_path("b")])
+ assert _stored() == {"a": 1}
+
+
+async def test_parallel_updates_keep_their_own_selectors() -> None:
+ _source.update(a=1, b=1, c=1)
+ app = _app("parallel")
+ await app.update()
+ _runs.clear()
+
+ _source.update(a=2, b=2, c=2)
+ await asyncio.gather(
+ app.update(component_selector=[_items_path("a")]).result(),
+ app.update(component_selector=[_items_path("b")]).result(),
+ )
+
+ assert _stored() == {"a": 2, "b": 2, "c": 1}
+
+
+def test_selected_component_takes_over_a_target_state_of_an_unselected_one() -> None:
+ owned: dict[str, dict[str, int]] = {"c1": {"x": 1, "c1_own": 1}, "c2": {}}
+
+ @coco.fn
+ async def declare_owned(name: str) -> None:
+ _runs.append(name)
+ for key, value in owned[name].items():
+ _declare(key, value)
+
+ @coco.fn
+ async def main() -> None:
+ for name in owned:
+ await coco.mount(coco.component_subpath(name), declare_owned, name)
+
+ app = _app("takeover", main)
+ _run_all_then_clear_log(app)
+
+ # The declaration of the selected component wins, as it would in a plain
+ # update. The rest of the unselected component stays.
+ owned["c2"] = {"x": 2}
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "c2"])
+ assert _runs == ["c2"]
+ assert _stored() == {"x": 2, "c1_own": 1}
+ assert common.list_target_state_owners_sync(app)[
+ '/@test_target_state/global_dict/"x"'
+ ] == (coco.ROOT_PATH / "c2")
+
+ owned["c1"] = {"c1_own": 1}
+ app.update_blocking()
+ assert _stored() == {"x": 2, "c1_own": 1}
+
+
+# ---------------------------------------------------------------------------
+# Live components
+# ---------------------------------------------------------------------------
+
+
+async def _live_item(key: str, value: int) -> None:
+ _runs.append(key)
+ _declare(key, value)
+
+
+_live_starts: list[str] = []
+
+
+class _LiveWithEvents:
+ """Scans `_source` in `process`, then replays `events` as live updates."""
+
+ events: list[tuple[str, str, int]] = []
+
+ async def process(self) -> None:
+ _runs.append("live_process")
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath(key), _live_item, key, value)
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ _live_starts.append("live")
+ await operator.update_full()
+ await operator.mark_ready()
+ for kind, key, value in self.events:
+ subpath = coco.component_subpath(key)
+ if kind == "update":
+ handle = await operator.update(subpath, _live_item, key, value)
+ else:
+ handle = await operator.delete(subpath)
+ await handle.ready()
+
+
+async def _live_main() -> None:
+ await coco.mount(coco.component_subpath("live"), _LiveWithEvents)
+
+
+def test_live_update_full_and_events_honour_the_selector() -> None:
+ _LiveWithEvents.events = []
+ _source.update(a=1, b=1, c=1, d=1)
+ app = _app("live_events", _live_main)
+ _run_all_then_clear_log(app)
+
+ _LiveWithEvents.events = [
+ ("update", "a", 3),
+ ("update", "b", 3),
+ ("delete", "c", 0),
+ ("delete", "d", 0),
+ ]
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ live=True,
+ component_selector=[
+ coco.ROOT_PATH / "live" / "a",
+ coco.ROOT_PATH / "live" / "c",
+ ],
+ )
+
+ assert sorted(_runs) == ["a", "a", "c", "live_process"]
+ assert _stored() == {"a": 3, "b": 1, "d": 1}
+
+ _LiveWithEvents.events = []
+ app.update_blocking()
+ assert _stored() == {"a": 2, "b": 2, "c": 1, "d": 1}
+
+
+def test_live_delete_of_an_ancestor_of_a_selected_path_is_skipped() -> None:
+ class Live:
+ async def process(self) -> None:
+ await coco.mount(
+ coco.component_subpath("group", "a"), _live_item, "a", _source["a"]
+ )
+ await coco.mount(
+ coco.component_subpath("group", "b"), _live_item, "b", _source["b"]
+ )
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+ handle = await operator.delete(coco.component_subpath("group"))
+ await handle.ready()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), Live)
+
+ _source.update(a=1, b=1)
+ app = _app("live_delete_ancestor", main)
+ _run_all_then_clear_log(app)
+
+ app.update_blocking(
+ live=True,
+ component_selector=[coco.ROOT_PATH / "live" / "group" / "a"],
+ )
+ assert _stored() == {"a": 1, "b": 1}
+
+
+def test_unselected_live_component_does_not_start() -> None:
+ _LiveWithEvents.events = []
+ _source.update(a=1)
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), _LiveWithEvents)
+ await coco.mount(coco.component_subpath("other"), _item, ("other", 1))
+
+ app = _app("live_not_started", main)
+ _run_all_then_clear_log(app)
+ _live_starts.clear()
+
+ _source.update(a=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "other"])
+
+ assert _live_starts == []
+ assert _stored() == {"a": 1, "other": 1}
+
+
+async def test_unselected_live_component_of_a_running_update_keeps_running(
+ request: pytest.FixtureRequest,
+) -> None:
+ # An environment on this test's loop, which the events below belong to.
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ release = asyncio.Event()
+ started = asyncio.Event()
+
+ class Live:
+ async def process(self) -> None:
+ pass
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.mark_ready()
+ started.set()
+ await release.wait()
+ handle = await operator.update(
+ coco.component_subpath("late"), _live_item, "late", 1
+ )
+ await handle.ready()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), Live)
+ await coco.mount(
+ coco.component_subpath("other"), _item, ("other", _source["a"])
+ )
+
+ _source.update(a=1)
+ app = coco.App(
+ coco.AppConfig(name="test_selector_live_keeps_running", environment=env), main
+ )
+ running = asyncio.ensure_future(app.update(live=True).result())
+ await asyncio.wait_for(started.wait(), timeout=10)
+
+ _source.update(a=2)
+ await app.update(component_selector=[coco.ROOT_PATH / "other"])
+ assert _stored() == {"other": 2}
+
+ release.set()
+ await asyncio.wait_for(running, timeout=10)
+ assert _stored() == {"other": 2, "late": 1}
+
+
+def test_selected_live_component_runs_as_without_a_selector() -> None:
+ _LiveWithEvents.events = []
+ _source.update(a=1, b=1)
+ app = _app("live_selected", _live_main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ del _source["b"]
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "live"])
+
+ assert _stored() == {"a": 2}
+
+
+def test_nested_live_component_honours_the_selector() -> None:
+ nested_starts: list[str] = []
+
+ def nested(name: str) -> type:
+ class Nested:
+ async def process(self) -> None:
+ _runs.append(name)
+ _declare(name, _source["a"])
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ nested_starts.append(name)
+ await operator.update_full()
+ await operator.mark_ready()
+
+ return Nested
+
+ class Outer:
+ async def process(self) -> None:
+ pass
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ for name in ["one", "two"]:
+ handle = await operator.update(
+ coco.component_subpath(name), nested(name)
+ )
+ await handle.ready()
+ await operator.mark_ready()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("outer"), Outer)
+
+ _source.update(a=1)
+ app = _app("live_nested", main)
+ _run_all_then_clear_log(app)
+ nested_starts.clear()
+
+ _source.update(a=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "outer" / "one"])
+
+ assert nested_starts == ["one"]
+ assert _stored() == {"one": 2, "two": 1}
+
+
+def test_mount_each_over_a_live_map_honours_the_selector() -> None:
+ @coco.fn
+ async def declare_entry(value: tuple[str, int]) -> None:
+ _runs.append(value[0])
+ _declare(*value)
+
+ @coco.fn
+ async def produce(live_map: LiveMap[str, tuple[str, int]]) -> None:
+ for key, value in _source.items():
+ live_map.declare_entry(key, (key, value))
+
+ @coco.fn
+ async def main() -> None:
+ live_map: LiveMap[str, tuple[str, int]] = await LiveMap.create()
+ producer = await coco.mount(
+ coco.component_subpath("producer"), produce, live_map
+ )
+ await producer.ready()
+ await coco.mount_each(coco.component_subpath("items"), declare_entry, live_map)
+
+ _source.update(a=1, b=1, c=1)
+ app = _app("live_map", main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ del _source["c"]
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "producer", _items_path("a")],
+ )
+
+ assert _runs == ["a"]
+ assert _stored() == {"a": 2, "b": 1, "c": 1}
+
+
+def test_preview_of_live_component_composes_with_the_selector() -> None:
+ _LiveWithEvents.events = []
+ _source.update(a=1, b=1)
+ app = _app("live_preview", _live_main)
+ _run_all_then_clear_log(app)
+
+ _source.update(a=2, b=2)
+ actions = app.update_blocking(
+ preview=True,
+ component_selector=[coco.ROOT_PATH / "live" / "a"],
+ )
+
+ assert _planned(actions) == {"a": 2}
+ assert _stored() == {"a": 1, "b": 1}
diff --git a/python/tests/core/test_component_selector_concurrency.py b/python/tests/core/test_component_selector_concurrency.py
new file mode 100644
index 00000000..9d04b8a5
--- /dev/null
+++ b/python/tests/core/test_component_selector_concurrency.py
@@ -0,0 +1,286 @@
+"""Sliced execution: parallel selective, plain and preview updates."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import random
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+ITERS = int(os.environ.get("SELECTOR_STRESS_ITERS", "40"))
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ GlobalDictTarget.store.sink_exception = False
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+class _Model:
+ """Source: app -> group -> key -> value. Target key "<app>|<group>|<key>"."""
+
+ def __init__(self, app_name: str, rng: random.Random) -> None:
+ self.app_name = app_name
+ self.rng = rng
+ self.src: dict[str, dict[str, int]] = {
+ f"g{g}": {f"k{k}": 0 for k in range(6)} for g in range(4)
+ }
+ self.flat: dict[str, int] = {f"k{k}": 0 for k in range(10)}
+
+ def expected(self) -> dict[str, Any]:
+ out: dict[str, Any] = {}
+ for g, items in self.src.items():
+ for k, v in items.items():
+ out[f"{self.app_name}|{g}|{k}"] = v
+ for k, v in self.flat.items():
+ out[f"{self.app_name}|flat|{k}"] = v
+ return out
+
+ def mutate(self) -> None:
+ rng = self.rng
+ for _ in range(rng.randint(1, 6)):
+ r = rng.random()
+ if r < 0.15 and self.src:
+ del self.src[rng.choice(sorted(self.src))]
+ elif r < 0.25:
+ self.src[f"g{rng.randint(0, 6)}"] = {
+ f"k{rng.randint(0, 3)}": rng.randint(0, 99)
+ }
+ elif r < 0.6 and self.src:
+ g = rng.choice(sorted(self.src))
+ k = f"k{rng.randint(0, 8)}"
+ if k in self.src[g] and rng.random() < 0.3:
+ del self.src[g][k]
+ else:
+ self.src[g][k] = rng.randint(0, 99)
+ else:
+ k = f"k{rng.randint(0, 14)}"
+ if k in self.flat and rng.random() < 0.3:
+ del self.flat[k]
+ else:
+ self.flat[k] = rng.randint(0, 99)
+
+ def random_selector(self) -> tuple[list[coco.StablePath], list[tuple[str, ...]]]:
+ rng = self.rng
+ paths: list[coco.StablePath] = []
+ raw: list[tuple[str, ...]] = []
+ for _ in range(rng.randint(0, 4)):
+ r = rng.random()
+ if r < 0.3:
+ g = f"g{rng.randint(0, 6)}"
+ raw.append(("groups", g))
+ elif r < 0.7:
+ raw.append(("groups", f"g{rng.randint(0, 6)}", f"k{rng.randint(0, 8)}"))
+ elif r < 0.95:
+ raw.append(("flat", f"k{rng.randint(0, 14)}"))
+ else:
+ raw.append(("groups",))
+ for parts in raw:
+ p = coco.ROOT_PATH
+ for part in parts:
+ p = p / part
+ paths.append(p)
+ return paths, raw
+
+
+def _covered(raw: list[tuple[str, ...]], key: str) -> bool:
+ _, group, item = key.split("|")
+ parts = ("flat", item) if group == "flat" else ("groups", group, item)
+ return any(parts[: len(sel)] == sel for sel in raw)
+
+
+def _make_app(
+ env: coco.Environment, model: _Model, max_inflight: int | None
+) -> coco.App[Any, Any]:
+ name = model.app_name
+
+ @coco.fn
+ async def item(group: str, key: str, value: int) -> None:
+ if value % 7 == 3:
+ await asyncio.sleep(0.001 * (value % 5))
+ coco.declare_target_state(
+ GlobalDictTarget.target_state(f"{name}|{group}|{key}", value)
+ )
+
+ @coco.fn(memo=True)
+ async def memo_item(group: str, key: str, value: int) -> None:
+ coco.declare_target_state(
+ GlobalDictTarget.target_state(f"{name}|{group}|{key}", value)
+ )
+
+ @coco.fn
+ async def group_fn(group: str, items: dict[str, int]) -> None:
+ for key, value in sorted(items.items()):
+ await coco.mount(coco.component_subpath(key), item, group, key, value)
+
+ @coco.fn
+ async def main() -> None:
+ snapshot = {g: dict(items) for g, items in model.src.items()}
+ flat = dict(model.flat)
+ with coco.component_subpath("groups"):
+ for g, items in sorted(snapshot.items()):
+ await coco.mount(coco.component_subpath(g), group_fn, g, items)
+ with coco.component_subpath("flat"):
+ for k, v in sorted(flat.items()):
+ await coco.mount(coco.component_subpath(k), memo_item, "flat", k, v)
+
+ return coco.App(
+ coco.AppConfig(
+ name=f"selector_conc_{name}",
+ environment=env,
+ max_inflight_components=max_inflight,
+ ),
+ main,
+ )
+
+
+async def _batch(
+ app: coco.App[Any, Any], model: _Model, allow_plain: bool
+) -> list[list[tuple[str, ...]]]:
+ """Run a random parallel batch; returns raw selectors of non-preview selective runs
+ (or [[()]] meaning a plain run happened)."""
+ rng = model.rng
+ coros = []
+ applied: list[list[tuple[str, ...]]] = []
+ for _ in range(rng.randint(2, 5)):
+ r = rng.random()
+ if r < 0.55:
+ paths, raw = model.random_selector()
+ coros.append(app.update(component_selector=paths).result())
+ applied.append(raw)
+ elif r < 0.7 and allow_plain:
+ coros.append(app.update().result())
+ applied.append([()])
+ elif r < 0.85:
+ paths, raw = model.random_selector()
+ coros.append(app.update(preview=True, component_selector=paths).result())
+ else:
+ coros.append(app.update(preview=True).result())
+ if rng.random() < 0.2:
+ fpaths, fraw = model.random_selector()
+ coros.append(
+ app.update(full_reprocess=True, component_selector=fpaths).result()
+ )
+ applied.append(fraw)
+ results = await asyncio.wait_for(asyncio.gather(*coros, return_exceptions=True), 60)
+ errors = [r for r in results if isinstance(r, BaseException)]
+ assert not errors, errors
+ return applied
+
+
+def _check_batch(
+ before: dict[str, Any],
+ model: _Model,
+ applied: list[list[tuple[str, ...]]],
+ app_name: str,
+) -> None:
+ after = {k: v for k, v in _stored().items() if k.startswith(app_name + "|")}
+ exp = model.expected()
+ if any(raw == [()] for raw in applied):
+ assert after == exp, "plain run in batch must converge"
+ return
+ sels = [s for raw in applied for s in raw]
+ for key in set(before) | set(exp) | set(after):
+ _, group, _item = key.split("|")
+ group_gone_uncovered = (
+ group != "flat"
+ and group not in model.src
+ and not any(("groups", group)[: len(sel)] == sel for sel in sels)
+ )
+ if _covered(sels, key) and not group_gone_uncovered:
+ assert after.get(key) == exp.get(key), (
+ key,
+ before.get(key),
+ exp.get(key),
+ after.get(key),
+ sels,
+ )
+ else:
+ assert after.get(key) == before.get(key), (
+ "unselected changed",
+ key,
+ before.get(key),
+ after.get(key),
+ sels,
+ )
+
+
[email protected]("max_inflight", [None, 1, 2])
+async def test_stress_parallel_selective_plain_preview_one_app(
+ request: pytest.FixtureRequest, max_inflight: int | None
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ rng = random.Random(
+ int(os.environ.get("SELECTOR_STRESS_SEED", "0")) * 1000
+ + 1234
+ + (max_inflight or 0)
+ )
+ model = _Model("a1", rng)
+ app = _make_app(env, model, max_inflight)
+ await app.update()
+ assert _stored() == model.expected()
+ for it in range(ITERS):
+ model.mutate()
+ before = dict(_stored())
+ allow_plain = it % 3 == 0
+ applied = await _batch(app, model, allow_plain)
+ _check_batch(before, model, applied, "a1")
+ if it % 5 == 4:
+ await app.update()
+ assert _stored() == model.expected(), (
+ f"iter {it}: plain run did not converge"
+ )
+ await app.update()
+ assert _stored() == model.expected()
+
+
+async def test_stress_two_apps_one_env(request: pytest.FixtureRequest) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ seed = int(os.environ.get("SELECTOR_STRESS_SEED", "0")) * 1000
+ m1, m2 = (
+ _Model("x1", random.Random(seed + 7)),
+ _Model("x2", random.Random(seed + 8)),
+ )
+ a1, a2 = _make_app(env, m1, None), _make_app(env, m2, 1)
+ await asyncio.gather(a1.update().result(), a2.update().result())
+ for it in range(ITERS):
+ m1.mutate()
+ m2.mutate()
+ b1 = {k: v for k, v in _stored().items() if k.startswith("x1|")}
+ b2 = {k: v for k, v in _stored().items() if k.startswith("x2|")}
+ r1, r2 = await asyncio.gather(
+ _batch(a1, m1, it % 4 == 0), _batch(a2, m2, it % 4 == 1)
+ )
+ _check_batch(b1, m1, r1, "x1")
+ _check_batch(b2, m2, r2, "x2")
+ await asyncio.gather(a1.update().result(), a2.update().result())
+ exp = {**m1.expected(), **m2.expected()}
+ assert _stored() == exp
+
+
+async def test_drop_after_selective_runs_removes_everything(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ model = _Model("d2", random.Random(5))
+ app = _make_app(env, model, None)
+ await app.update()
+ for _ in range(10):
+ model.mutate()
+ await app.update(component_selector=model.random_selector()[0])
+ await app.drop()
+ assert _stored() == {}
diff --git a/python/tests/core/test_component_selector_container.py b/python/tests/core/test_component_selector_container.py
new file mode 100644
index 00000000..52f9f514
--- /dev/null
+++ b/python/tests/core/test_component_selector_container.py
@@ -0,0 +1,182 @@
+"""Sliced execution: a container target change would take unselected rows with it."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+
+from tests import common
+from tests.common.target_states import DictsTarget
+
+coco_env = common.create_test_env(__file__)
+_rows: dict[str, int] = {}
+
+
+async def _row(provider: Any, key: str, value: int) -> None:
+ coco.declare_target_state(provider.target_state(key, value))
+
+
+async def _memo_row(provider: Any, key: str, value: int) -> None:
+ coco.declare_target_state(provider.target_state(key, value))
+
+
+def _main_for(fn: Any) -> Any:
+ @coco.fn
+ async def main() -> None:
+ provider = await coco.use_mount(
+ coco.component_subpath("setup"), DictsTarget.declare_dict_target, "D"
+ )
+ with coco.component_subpath("rows"):
+ for key, value in sorted(_rows.items()):
+ await coco.mount(coco.component_subpath(key), fn, provider, key, value)
+
+ return main
+
+
+def _data() -> dict[str, Any]:
+ return {k: v.data for k, v in DictsTarget.store.data.get("D", {}).items()}
+
+
[email protected]("invalidation", ["destructive"])
[email protected]("memo", [False, True])
+def test_container_change_under_a_selector_is_refused(
+ invalidation: Any, memo: bool
+) -> None:
+ DictsTarget.store.clear()
+ _rows.clear()
+ _rows.update(a=1, b=1, c=1)
+ app = coco.App(
+ coco.AppConfig(
+ name=f"selector_container_{invalidation}_{memo}", environment=coco_env
+ ),
+ _main_for(_memo_row if memo else _row),
+ )
+ app.update_blocking()
+ assert _data() == {"a": 1, "b": 1, "c": 1}
+
+ DictsTarget.store.child_invalidation = invalidation
+ selector = [coco.ROOT_PATH / "rows" / "a"]
+ try:
+ # The preview of a page and its update agree: both refuse, alike.
+ with pytest.raises(Exception) as preview_refusal:
+ app.update_blocking(preview=True, component_selector=selector)
+ with pytest.raises(Exception) as update_refusal:
+ app.update_blocking(component_selector=selector)
+ assert type(preview_refusal.value) is type(update_refusal.value)
+ assert str(preview_refusal.value) == str(update_refusal.value)
+ message = str(update_refusal.value)
+ assert "container target state" in message
+ assert '"D"' in message # The container's path.
+ assert "A full update is needed" in message
+ assert _data() == {"a": 1, "b": 1, "c": 1}
+
+ # A plain update declares every row again.
+ app.update_blocking()
+ finally:
+ DictsTarget.store.child_invalidation = None
+ assert _data() == {"a": 1, "b": 1, "c": 1}
+
+
+def test_container_removal_under_a_selector_is_refused_alike_in_preview() -> None:
+ declares = {"on": True}
+
+ @coco.fn
+ async def setup() -> Any:
+ if declares["on"]:
+ return DictsTarget.declare_dict_target("D")
+ return None
+
+ @coco.fn
+ async def main() -> None:
+ provider = await coco.use_mount(coco.component_subpath("setup"), setup)
+ if provider is None:
+ return
+ with coco.component_subpath("rows"):
+ for key, value in sorted(_rows.items()):
+ await coco.mount(
+ coco.component_subpath(key), _row, provider, key, value
+ )
+
+ DictsTarget.store.clear()
+ _rows.clear()
+ _rows.update(a=1, b=1)
+ app = coco.App(
+ coco.AppConfig(name="selector_container_removal", environment=coco_env), main
+ )
+ app.update_blocking()
+ assert _data() == {"a": 1, "b": 1}
+
+ # The setup component still runs (a use_mount child) and no longer
+ # declares the container, which would take row "b" with it.
+ declares["on"] = False
+ selector = [coco.ROOT_PATH / "rows" / "a"]
+ with pytest.raises(Exception) as preview_refusal:
+ app.update_blocking(preview=True, component_selector=selector)
+ with pytest.raises(Exception) as update_refusal:
+ app.update_blocking(component_selector=selector)
+ assert type(preview_refusal.value) is type(update_refusal.value)
+ assert str(preview_refusal.value) == str(update_refusal.value)
+ assert "needs a removal" in str(update_refusal.value)
+ assert "A full update is needed" in str(update_refusal.value)
+ assert _data() == {"a": 1, "b": 1}
+
+ app.update_blocking()
+ assert DictsTarget.store.data == {}
+
+
+def test_lossy_report_for_an_unchanged_container_is_not_refused() -> None:
+ # A reconcile that cannot trust the previous state (as under
+ # full_reprocess) may report a lossy change for a container whose record
+ # did not change. That converts nothing, so the selective update runs.
+ DictsTarget.store.clear()
+ _rows.clear()
+ _rows.update(a=1, b=1)
+ app = coco.App(
+ coco.AppConfig(name="selector_container_lossy_same", environment=coco_env),
+ _main_for(_row),
+ )
+ app.update_blocking()
+
+ _rows.update(a=2, b=2)
+ DictsTarget.store.child_invalidation = "lossy"
+ try:
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "rows" / "a"])
+ finally:
+ DictsTarget.store.child_invalidation = None
+ assert _data() == {"a": 2, "b": 1}
+
+
[email protected]("memo", [False, True])
+def test_container_change_is_applied_when_every_row_owner_runs(memo: bool) -> None:
+ """The refusal is per container: when the update runs every component that
+ owns a row under it, a rebuild goes through as in a plain update."""
+ DictsTarget.store.clear()
+ _rows.clear()
+ _rows.update(a=1, b=1)
+ app = coco.App(
+ coco.AppConfig(name=f"selector_container_all_run_{memo}", environment=coco_env),
+ _main_for(_memo_row if memo else _row),
+ )
+ app.update_blocking()
+
+ DictsTarget.store.child_invalidation = "destructive"
+ _rows.update(a=2, b=2)
+ try:
+ selector = [coco.ROOT_PATH / "rows"]
+ app.update_blocking(component_selector=selector)
+ finally:
+ DictsTarget.store.child_invalidation = None
+ assert _data() == {"a": 2, "b": 2}
+
+ # A selector that leaves a row owner out still refuses.
+ DictsTarget.store.child_invalidation = "destructive"
+ try:
+ with pytest.raises(Exception, match="A full update is needed"):
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "rows" / "a"])
+ finally:
+ DictsTarget.store.child_invalidation = None
diff --git a/python/tests/core/test_component_selector_failure.py b/python/tests/core/test_component_selector_failure.py
new file mode 100644
index 00000000..71ac3905
--- /dev/null
+++ b/python/tests/core/test_component_selector_failure.py
@@ -0,0 +1,361 @@
+"""Sliced execution: failure, interruption and API surface."""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import timedelta
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+_source: dict[str, int] = {}
+_runs: list[str] = []
+_fail: set[str] = set()
+_slow: dict[str, float] = {}
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ GlobalDictTarget.store.sink_exception = False
+ _source.clear()
+ _runs.clear()
+ _fail.clear()
+ _slow.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+async def _item(key: str, value: int) -> None:
+ _runs.append(key)
+ if key in _slow:
+ await asyncio.sleep(_slow[key])
+ if key in _fail:
+ raise ValueError(f"boom {key}")
+ coco.declare_target_state(GlobalDictTarget.target_state(key, value))
+
+
+async def _group(name: str) -> None:
+ _runs.append(f"group:{name}")
+ for key, value in sorted(_source.items()):
+ if key.startswith(name):
+ await coco.mount(coco.component_subpath(key), _item, key, value)
+
+
+async def _main() -> None:
+ for name in ["g1", "g2"]:
+ await coco.mount(coco.component_subpath(name), _group, name)
+
+
+def _app(env: coco.Environment, name: str, main: Any = _main) -> coco.App[Any, Any]:
+ return coco.App(coco.AppConfig(name=f"selector_fail_{name}", environment=env), main)
+
+
+def _seed() -> None:
+ _source.update({"g1a": 1, "g1b": 1, "g1c": 1, "g2a": 1, "g2b": 1})
+
+
+def _expected() -> dict[str, int]:
+ return dict(_source)
+
+
+async def test_deadline_during_selective_run_then_recovers(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "deadline")
+ await app.update()
+ for k in list(_source):
+ _source[k] = 2
+ _slow["g1b"] = 1.0
+ with coco.timeout(timedelta(seconds=0.2)):
+ with pytest.raises(Exception) as ei:
+ await app.update(component_selector=[coco.ROOT_PATH / "g1"])
+ print("deadline error:", type(ei.value).__name__, ei.value)
+ # unselected g2 untouched; g1b not updated.
+ assert _stored()["g2a"] == 1 and _stored()["g2b"] == 1
+ _slow.clear()
+ await app.update(component_selector=[coco.ROOT_PATH / "g1"])
+ assert {k: v for k, v in _stored().items() if k.startswith("g1")} == {
+ "g1a": 2,
+ "g1b": 2,
+ "g1c": 2,
+ }
+ assert _stored()["g2a"] == 1
+ await app.update()
+ assert _stored() == _expected()
+
+
+async def test_cancel_a_selective_update_task_then_recovers(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "cancel")
+ await app.update()
+ for k in list(_source):
+ _source[k] = 3
+ del _source["g1c"]
+ for delay in [0.0, 0.01, 0.05, 0.1, 0.3]:
+ _slow["g1b"] = 0.2
+ task = asyncio.ensure_future(
+ app.update(component_selector=[coco.ROOT_PATH / "g1"]).result()
+ )
+ await asyncio.sleep(delay)
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+ assert _stored()["g2a"] == 1, f"delay {delay}: unselected changed"
+ _slow.clear()
+ # Let any background work drain.
+ await asyncio.sleep(0.5)
+ await app.update(component_selector=[coco.ROOT_PATH / "g1"])
+ assert {k: v for k, v in _stored().items() if k.startswith("g1")} == {
+ "g1a": 3,
+ "g1b": 3,
+ }
+ await app.update()
+ assert _stored() == _expected()
+
+
+async def test_exception_handler_sees_only_selected_failures(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ seen: list[str] = []
+
+ async def handler(exc: BaseException, ctx: Any) -> None:
+ seen.append(ctx.stable_path)
+
+ @coco.fn
+ async def main() -> None:
+ async with coco.exception_handler(handler):
+ for key, value in sorted(_source.items()):
+ await coco.mount(coco.component_subpath(key), _item, key, value)
+
+ _source.update(a=1, b=1, c=1)
+ app = _app(env, "handler", main)
+ await app.update()
+ _fail.update({"a", "b"})
+ _source.update(a=2, b=2, c=2)
+ await app.update(component_selector=[coco.ROOT_PATH / "b", coco.ROOT_PATH / "c"])
+ assert len(seen) == 1 and seen[0].endswith('"b"'), seen
+ # A failed selected component keeps its previous target state.
+ assert _stored() == {"a": 1, "b": 1, "c": 2}
+ _fail.clear()
+ await app.update(component_selector=[coco.ROOT_PATH / "b"])
+ assert _stored() == {"a": 1, "b": 2, "c": 2}
+
+
+async def test_failing_selected_child_does_not_delete_unselected_siblings(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "failing_child")
+ await app.update()
+ _fail.add("g1b")
+ del _source["g1c"] # unselected deletion: must stay
+ _source["g1b"] = 5
+ _source["g1a"] = 5
+ try:
+ await app.update(
+ component_selector=[
+ coco.ROOT_PATH / "g1" / "g1b",
+ coco.ROOT_PATH / "g1" / "g1a",
+ ]
+ )
+ except Exception as e: # noqa: BLE001
+ print("selective with failing child raised:", type(e).__name__)
+ assert _stored() == {"g1a": 5, "g1b": 1, "g1c": 1, "g2a": 1, "g2b": 1}
+ _fail.clear()
+ await app.update()
+ assert _stored() == _expected()
+
+
+async def test_failing_ancestor_use_mount_under_selector(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ fail_parent = [False]
+
+ @coco.fn
+ async def setup() -> int:
+ if fail_parent[0]:
+ raise ValueError("parent fails")
+ return 10
+
+ @coco.fn
+ async def main() -> None:
+ base = await coco.use_mount(coco.component_subpath("setup"), setup)
+ for key, value in sorted(_source.items()):
+ await coco.mount(coco.component_subpath(key), _item, key, value + base)
+
+ _source.update(a=1, b=1)
+ app = _app(env, "failing_use_mount", main)
+ await app.update()
+ fail_parent[0] = True
+ _source.update(a=2, b=2)
+ with pytest.raises(Exception):
+ await app.update(component_selector=[coco.ROOT_PATH / "a"])
+ assert _stored() == {"a": 11, "b": 11}
+ fail_parent[0] = False
+ await app.update(component_selector=[coco.ROOT_PATH / "a"])
+ assert _stored() == {"a": 12, "b": 11}
+
+
+async def test_sink_failure_on_selected_then_retry(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "sink_fail")
+ await app.update()
+ for k in list(_source):
+ _source[k] = 4
+ GlobalDictTarget.store.sink_exception = True
+ try:
+ await app.update(component_selector=[coco.ROOT_PATH / "g2"])
+ except Exception as e: # noqa: BLE001
+ print("sink failure raised:", type(e).__name__)
+ GlobalDictTarget.store.sink_exception = False
+ await app.update(component_selector=[coco.ROOT_PATH / "g2"])
+ assert _stored() == {"g1a": 1, "g1b": 1, "g1c": 1, "g2a": 4, "g2b": 4}
+ await app.update()
+ assert _stored() == _expected()
+
+
+def test_update_blocking_with_report_to_stdout_and_show_progress(
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ env = common.create_test_env(__file__, suffix="stdout")
+ _seed()
+ app = _app(env, "stdout")
+ app.update_blocking()
+ _runs.clear()
+ for k in list(_source):
+ _source[k] = 6
+ app.update_blocking(
+ report_to_stdout=True, component_selector=[coco.ROOT_PATH / "g2" / "g2a"]
+ )
+ out = capsys.readouterr().out
+ print(out)
+ assert _stored()["g2a"] == 6 and _stored()["g1a"] == 1
+ assert sorted(_runs) == ["g2a", "group:g2"], _runs
+
+
+async def test_show_progress_and_duplicates(request: pytest.FixtureRequest) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "progress")
+ await app.update()
+ _runs.clear()
+ for k in list(_source):
+ _source[k] = 7
+ p = coco.ROOT_PATH / "g1" / "g1a"
+ handle = app.update(
+ component_selector=[p, p, coco.ROOT_PATH / "g1" / "g1a" / "deeper", p]
+ )
+ await coco.show_progress(handle)
+ assert _runs.count("g1a") == 1, _runs
+ assert _stored()["g1a"] == 7 and _stored()["g1b"] == 1
+
+
+async def test_selector_iterable_consumed_lazily_or_eagerly(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ _seed()
+ app = _app(env, "lazy")
+ await app.update()
+ for k in list(_source):
+ _source[k] = 8
+ paths = [coco.ROOT_PATH / "g1" / "g1a"]
+ handle = app.update(component_selector=paths)
+ paths.append(coco.ROOT_PATH / "g2") # mutation after the call must not matter
+ await handle
+ assert _stored()["g2a"] == 1 and _stored()["g1a"] == 8
+
+
+async def test_memoized_use_mount_leaf_keeps_its_memo_under_a_selector(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ loads: list[int] = []
+
+ @coco.fn(memo=True)
+ async def load_model(version: int) -> int:
+ loads.append(version)
+ return version * 10
+
+ @coco.fn
+ async def main() -> None:
+ base = await coco.use_mount(
+ coco.component_subpath("model"), load_model, _source["v"]
+ )
+ for key in ["a", "b"]:
+ await coco.mount(coco.component_subpath(key), _item, key, base)
+
+ _source["v"] = 1
+ app = _app(env, "use_mount_memo", main)
+ await app.update()
+ _source["v"] = 2
+ await app.update(component_selector=[coco.ROOT_PATH / "a"])
+ assert loads == [1, 2]
+ await app.update()
+ # Nothing changed since the selective run: the expensive leaf should not rerun.
+ assert loads == [1, 2], f"memoized use_mount leaf recomputed: {loads}"
+
+
+async def test_full_reprocess_under_a_selector_does_not_rerun_unselected_use_mount(
+ request: pytest.FixtureRequest,
+) -> None:
+ env = common.create_test_env(__file__, suffix=request.node.name)
+ calls: list[str] = []
+
+ @coco.fn(memo=True)
+ async def embed(key: str) -> int:
+ calls.append(f"embed:{key}")
+ return 1
+
+ @coco.fn
+ async def per_file(key: str) -> int:
+ calls.append(f"use_mount:{key}")
+ return await embed(key)
+
+ @coco.fn
+ async def main() -> None:
+ for key in ["f1", "f2"]:
+ await coco.use_mount(coco.component_subpath("files", key), per_file, key)
+ await coco.mount(coco.component_subpath("target"), _item, "target", 1)
+
+ app = _app(env, "full_reprocess_use_mount", main)
+ await app.update()
+ calls.clear()
+ await app.update(
+ full_reprocess=True, component_selector=[coco.ROOT_PATH / "target"]
+ )
+ assert [c for c in calls if c.startswith("embed")] == [], calls
diff --git a/python/tests/core/test_component_selector_features.py b/python/tests/core/test_component_selector_features.py
new file mode 100644
index 00000000..d4552bad
--- /dev/null
+++ b/python/tests/core/test_component_selector_features.py
@@ -0,0 +1,543 @@
+"""Sliced execution crossed with the features the programming guide documents.
+
+Each test names the theory claim (T1-T16, see THEORY.md) it checks. A test marked
+``GAP`` pins down a behavior the docs or the theory get wrong or leave out.
+"""
+
+from __future__ import annotations
+
+import pathlib
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex.connectors import localfs
+from cocoindex.resources.file import FileLike, PatternFilePathMatcher
+
+from tests import common
+from tests.common.target_states import DictsTarget, GlobalDictTarget
+
+coco_env = common.create_test_env(__file__)
+
+_source: dict[Any, Any] = {}
+_runs: list[str] = []
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ DictsTarget.store.clear()
+ _source.clear()
+ _runs.clear()
+
+
+def _app(name: str, main: Any, *args: Any, **config: Any) -> coco.App[Any, Any]:
+ return coco.App(
+ coco.AppConfig(
+ name=f"test_selector_features_{name}", environment=coco_env, **config
+ ),
+ main,
+ *args,
+ )
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _declare(key: Any, value: Any) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(str(key), value))
+
+
+# ---------------------------------------------------------------------------
+# The docs example, end to end on a real source and target (T1, T3, T5, T7, T9)
+# ---------------------------------------------------------------------------
+
+
+async def process_file(file: FileLike[Any], target: localfs.DirTarget) -> None:
+ _runs.append("/".join(file.file_path.path.parts[-2:]))
+ outname = "__".join(file.file_path.path.parts[-2:]) + ".out"
+ target.declare_file(filename=outname, content=(await file.read_text()).upper())
+
+
+async def _localfs_main(sourcedir: pathlib.Path, outdir: pathlib.Path) -> None:
+ target = await localfs.mount_dir_target(outdir)
+ files = localfs.walk_dir(
+ sourcedir,
+ recursive=True,
+ path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
+ )
+ await coco.mount_each(process_file, files.items(), target)
+
+
+def _outputs(outdir: pathlib.Path) -> dict[str, str]:
+ return {p.name: p.read_text() for p in sorted(outdir.iterdir())}
+
+
+def test_docs_example_on_localfs_with_nested_keys(tmp_path: pathlib.Path) -> None:
+ src, out = tmp_path / "src", tmp_path / "out"
+ (src / "sub").mkdir(parents=True)
+ (src / "a.md").write_text("a1")
+ (src / "sub" / "b.md").write_text("b1")
+ (src / "c.md").write_text("c1")
+ app = _app("localfs_docs", _localfs_main, src, out)
+ app.update_blocking()
+ assert _outputs(out) == {
+ "src__a.md.out": "A1",
+ "sub__b.md.out": "B1",
+ "src__c.md.out": "C1",
+ }
+
+ (src / "a.md").write_text("a2")
+ (src / "sub" / "b.md").write_text("b2")
+ (src / "c.md").unlink()
+ (src / "d.md").write_text("d1")
+ _runs.clear()
+
+ # The docs snippet, verbatim: a walk_dir key is one str key, "sub/b.md".
+ page_of_files = ["sub/b.md", "d.md"]
+ paths = [
+ coco.ROOT_PATH / coco.Symbol("process_file") / name for name in page_of_files
+ ]
+ actions = app.update_blocking(component_selector=paths, preview=True)
+ assert _outputs(out) == {
+ "src__a.md.out": "A1",
+ "sub__b.md.out": "B1",
+ "src__c.md.out": "C1",
+ }
+ assert actions # the selected changes are planned
+ _runs.clear()
+
+ app.update_blocking(component_selector=paths)
+ assert sorted(_runs) == ["src/d.md", "sub/b.md"]
+ # a.md changed and c.md is gone, both unselected: their outputs stay.
+ assert _outputs(out) == {
+ "src__a.md.out": "A1",
+ "sub__b.md.out": "B2",
+ "src__c.md.out": "C1",
+ "src__d.md.out": "D1",
+ }
+
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == ["src/a.md"]
+ assert _outputs(out) == {
+ "src__a.md.out": "A2",
+ "sub__b.md.out": "B2",
+ "src__d.md.out": "D1",
+ }
+
+
+def test_mount_target_runs_under_the_empty_selector_on_a_first_run(
+ tmp_path: pathlib.Path,
+) -> None:
+ """T4/T14: mount_target is a use_mount, so `[]` creates the target and no file."""
+ src, out = tmp_path / "src", tmp_path / "out"
+ src.mkdir()
+ (src / "a.md").write_text("a1")
+ app = _app("mount_target_empty", _localfs_main, src, out)
+ app.update_blocking(component_selector=[])
+ assert out.is_dir() and _outputs(out) == {}
+ assert _runs == []
+ app.update_blocking()
+ assert _outputs(out) == {"src__a.md.out": "A1"}
+
+
+# ---------------------------------------------------------------------------
+# use_mount children that the root no longer calls (T3, T4, T5)
+# ---------------------------------------------------------------------------
+
+_calls_setup = {"on": True}
+
+
+async def _setup() -> int:
+ _runs.append("setup")
+ _declare("setup", 1)
+ return 1
+
+
+async def _item(key: str, value: int) -> None:
+ _runs.append(key)
+ _declare(key, value)
+
+
+async def _setup_main() -> None:
+ if _calls_setup["on"]:
+ await coco.use_mount(coco.component_subpath("setup"), _setup)
+ for key, value in sorted(_source.items()):
+ await coco.mount(coco.component_subpath("items", key), _item, key, value)
+
+
[email protected]("selected", [False, True])
+def test_use_mount_child_no_longer_called(selected: bool) -> None:
+ _calls_setup["on"] = True
+ _source.update(a=1)
+ app = _app(f"use_mount_gone_{selected}", _setup_main)
+ app.update_blocking()
+ assert _stored() == {"setup": 1, "a": 1}
+
+ _calls_setup["on"] = False
+ selector = [coco.ROOT_PATH / "items" / "a"]
+ if selected:
+ selector.append(coco.ROOT_PATH / "setup")
+ app.update_blocking(component_selector=selector)
+ # Unselected and gone: kept, as any unselected component. Selected and
+ # gone: deleted.
+ assert _stored() == ({"a": 1} if selected else {"setup": 1, "a": 1})
+ app.update_blocking()
+ assert _stored() == {"a": 1}
+
+
+# ---------------------------------------------------------------------------
+# Logic change detection: version, LogicDep (T3, T5, T7)
+# ---------------------------------------------------------------------------
+
+
+_current_fn: dict[str, Any] = {}
+
+
+def _versioned(version: int) -> Any:
+ @coco.fn(memo=True, version=version)
+ async def versioned_item(key: str, value: int) -> None:
+ _runs.append(key)
+ _declare(key, value * 100 + version)
+
+ return versioned_item
+
+
+async def _versioned_main() -> None:
+ for key, value in sorted(_source.items()):
+ await coco.mount(
+ coco.component_subpath("items", key), _current_fn["fn"], key, value
+ )
+
+
+def test_version_bump_reaches_unselected_memos_on_the_next_plain_update() -> None:
+ _source.update(a=1, b=1)
+ _current_fn["fn"] = _versioned(1)
+ app = _app("version", _versioned_main)
+ app.update_blocking()
+ assert _stored() == {"a": 101, "b": 101}
+
+ _runs.clear()
+ _current_fn["fn"] = _versioned(2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "a"])
+ assert _runs == ["a"]
+ assert _stored() == {"a": 102, "b": 101}
+
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == ["b"]
+ assert _stored() == {"a": 102, "b": 102}
+
+
+# ---------------------------------------------------------------------------
+# DataDep (experimental): a read the arguments do not cover (T3, T5, T7)
+# ---------------------------------------------------------------------------
+
+_external: dict[str, int] = {}
+
+
+def _validate_external(key: str, prev: int) -> coco.MemoStateOutcome:
+ current = _external.get(key)
+ return coco.MemoStateOutcome(state=current, memo_valid=current == prev)
+
+
+_EXTERNAL = coco.DataDep("selector_features_external", validate=_validate_external)
+
+
+async def _reads_external(key: str) -> None:
+ _runs.append(key)
+ value = _external[key]
+ coco.use_data_dep(_EXTERNAL, key=key, state=value)
+ _declare(key, value)
+
+
+async def _data_dep_main() -> None:
+ for key in sorted(_external):
+ await coco.mount(coco.component_subpath("items", key), _reads_external, key)
+
+
+def test_data_dep_change_of_an_unselected_component_waits_for_a_covering_update() -> (
+ None
+):
+ _external.clear()
+ _external.update(a=1, b=1)
+ app = _app("data_dep", _data_dep_main)
+ app.update_blocking()
+ _external.update(a=2, b=2)
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "a"])
+ assert _runs == ["a"]
+ assert _stored() == {"a": 2, "b": 1}
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == ["b"]
+ assert _stored() == {"a": 2, "b": 2}
+
+
+# ---------------------------------------------------------------------------
+# Concurrency control: a limit of one, a deep selected path (T4)
+# ---------------------------------------------------------------------------
+
+
+async def _level(depth: int, key: str) -> None:
+ _runs.append(f"{depth}/{key}")
+ if depth == 0:
+ _declare(key, 1)
+ return
+ for child in ("x", "y"):
+ await coco.mount(
+ coco.component_subpath(child), _level, depth - 1, f"{key}{child}"
+ )
+
+
+def test_deep_selection_under_a_limit_of_one_inflight_component() -> None:
+ app = _app("limit_one", _level, 3, "", max_inflight_components=1)
+ app.update_blocking()
+ assert len(_stored()) == 8
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x" / "y" / "x"])
+ assert _runs == ["3/", "2/x", "1/xy", "0/xyx"]
+
+
+# ---------------------------------------------------------------------------
+# use_state in an ancestor that left children out (T10 by analogy)
+# ---------------------------------------------------------------------------
+
+
+def test_use_state_written_by_an_ancestor_under_a_selector_is_persisted() -> None:
+ """Unlike write_committed_state, a use_state value an ancestor writes in a run
+ that left children out is persisted. The docs say neither."""
+ observed: list[int] = []
+
+ @coco.fn
+ async def main() -> None:
+ state = coco.use_state("scan_marker", 0)
+ observed.append(state.value)
+ for key, value in sorted(_source.items()):
+ await coco.mount(coco.component_subpath("items", key), _item, key, value)
+ state.value = len(_source)
+
+ _source.update(a=1, b=1)
+ app = _app("ancestor_use_state", main)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "a"])
+ app.update_blocking(component_selector=[])
+ assert observed == [0, 2]
+
+
+# ---------------------------------------------------------------------------
+# Containers (T8)
+# ---------------------------------------------------------------------------
+
+
+async def _row(provider: Any, key: str, value: int) -> None:
+ coco.declare_target_state(provider.target_state(key, value))
+
+
+async def _sub_pipeline(name: str) -> None:
+ provider = await coco.use_mount(
+ coco.component_subpath("setup"), DictsTarget.declare_dict_target, name
+ )
+ for key, value in sorted(_source.items()):
+ await coco.mount(
+ coco.component_subpath("rows", key), _row, provider, key, value
+ )
+
+
+async def _two_pipelines_main() -> None:
+ await coco.mount(coco.component_subpath("p1"), _sub_pipeline, "D1")
+ await coco.mount(coco.component_subpath("p2"), _sub_pipeline, "D2")
+
+
+def _dicts() -> dict[str, dict[str, Any]]:
+ return {
+ name: {k: v.data for k, v in rows.items()}
+ for name, rows in DictsTarget.store.data.items()
+ }
+
+
[email protected]("preview", [False, True])
+def test_container_refusal_under_a_mounted_owner_is_raised(preview: bool) -> None:
+ """The docs: a selective update that would rebuild a container while it
+ leaves out a row owner "fails with an error", and a preview with the same
+ selector fails alike. D1's owner runs only as an ancestor of a selected
+ row, so row b is left out."""
+ _source.update(a=1, b=1)
+ app = _app(f"container_mounted_owner_one_row_{preview}", _two_pipelines_main)
+ app.update_blocking()
+ assert _dicts() == {"D1": {"a": 1, "b": 1}, "D2": {"a": 1, "b": 1}}
+
+ DictsTarget.store.child_invalidation = "destructive"
+ _source.update(a=2, b=2)
+ try:
+ with pytest.raises(Exception, match="A full update is needed"):
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "p1" / "rows" / "a"],
+ preview=preview,
+ )
+ finally:
+ DictsTarget.store.child_invalidation = None
+ # Whatever happens, nothing under p1 was applied.
+ assert _dicts() == {"D1": {"a": 1, "b": 1}, "D2": {"a": 1, "b": 1}}
+
+
+def test_container_change_applies_when_its_whole_owner_is_selected() -> None:
+ """Every row of D1 lies in the selected subtree, so the rebuild goes
+ through as in a plain update; D2 is left alone."""
+ _source.update(a=1, b=1)
+ app = _app("container_mounted_owner_whole", _two_pipelines_main)
+ app.update_blocking()
+
+ DictsTarget.store.child_invalidation = "destructive"
+ _source.update(a=2, b=2)
+ try:
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "p1"])
+ finally:
+ DictsTarget.store.child_invalidation = None
+ assert _dicts() == {"D1": {"a": 2, "b": 2}, "D2": {"a": 1, "b": 1}}
+
+
+_declares_container = {"on": True}
+
+
+async def _optional_setup() -> Any:
+ if _declares_container["on"]:
+ return DictsTarget.declare_dict_target("D")
+ return None
+
+
+async def _optional_container_main() -> None:
+ if not _declares_container["on"]:
+ return
+ provider = await coco.use_mount(coco.component_subpath("setup"), _optional_setup)
+ for key, value in sorted(_source.items()):
+ await coco.mount(
+ coco.component_subpath("rows", key), _row, provider, key, value
+ )
+
+
+def test_gone_selected_container_owner_with_gone_unselected_rows_converges() -> None:
+ """T8 exception + T7: the container goes with its selected, gone owner; its
+ unselected (also gone) row owners keep their records, and a plain update
+ then converges without error."""
+ _declares_container["on"] = True
+ _source.update(a=1, b=1)
+ app = _app("container_owner_gone", _optional_container_main)
+ app.update_blocking()
+ assert _dicts() == {"D": {"a": 1, "b": 1}}
+
+ _declares_container["on"] = False
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "setup"])
+ assert "D" not in DictsTarget.store.data
+ owners_after_selective = common.list_target_state_owners_sync(app)
+
+ app.update_blocking()
+ assert DictsTarget.store.data == {}
+ assert common.list_target_state_owners_sync(app) == {}
+ # The unselected row owners kept their records through the selective run.
+ assert owners_after_selective
+
+
+# ---------------------------------------------------------------------------
+# Taking over a target state in plain updates (T11, T7)
+# ---------------------------------------------------------------------------
+
+
+async def _memo_declares(name: str, key: str) -> None:
+ _runs.append(name)
+ _declare(key, "same value")
+
+
+async def _two_declarers_main() -> None:
+ for name in sorted(_source):
+ await coco.mount(
+ coco.component_subpath("items", name), _memo_declares, name, _source[name]
+ )
+
+
+def test_two_memoized_owners_of_one_target_state_settle_in_plain_updates() -> None:
+ """T11 drops the old owner's memo on a takeover, in plain updates too. Two
+ unchanged components that declare one target state must still settle."""
+ _source.update(a="shared", b="shared")
+ app = _app("two_owners", _two_declarers_main)
+ app.update_blocking()
+ runs_per_update = []
+ for _ in range(3):
+ _runs.clear()
+ app.update_blocking()
+ runs_per_update.append(sorted(_runs))
+ assert runs_per_update == [[], [], []]
+
+
+# ---------------------------------------------------------------------------
+# T6: "each ancestor stores no memo", when only a grandchild left something out
+# ---------------------------------------------------------------------------
+
+
+async def _leaf(key: str, value: int) -> None:
+ _runs.append(key)
+ _declare(key, value)
+
+
+async def _inner(items: tuple[tuple[str, int], ...]) -> None:
+ _runs.append("inner")
+ for key, value in items:
+ await coco.mount(coco.component_subpath("rows", key), _leaf, key, value)
+
+
+async def _memo_middle(items: tuple[tuple[str, int], ...]) -> None:
+ _runs.append("middle")
+ # Mounts one child only, and runs it: the middle leaves nothing out itself.
+ await coco.mount(coco.component_subpath("inner"), _inner, items)
+
+
+async def _grandchild_main() -> None:
+ await coco.mount(
+ coco.component_subpath("middle"), _memo_middle, tuple(sorted(_source.items()))
+ )
+
+
[email protected]("data_changes", [False, True])
+def test_memoized_grandparent_of_a_left_out_child_stores_no_memo(
+ data_changes: bool,
+) -> None:
+ _source.update(a=1, b=1)
+ app = _app(f"grandchild_left_out_{data_changes}", _grandchild_main)
+ app.update_blocking()
+ if data_changes:
+ _source.update(a=2, b=2)
+ _runs.clear()
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "middle" / "inner" / "rows" / "a"],
+ full_reprocess=True,
+ )
+ assert _runs == ["middle", "inner", "a"]
+ expected_after_selective = {"a": 2, "b": 1} if data_changes else {"a": 1, "b": 1}
+ assert _stored() == expected_after_selective
+
+ # The middle's memo must not stand in for "inner", which left "b" out.
+ _runs.clear()
+ app.update_blocking()
+ assert "b" in _runs
diff --git a/python/tests/core/test_component_selector_fuzz.py b/python/tests/core/test_component_selector_fuzz.py
new file mode 100644
index 00000000..33663604
--- /dev/null
+++ b/python/tests/core/test_component_selector_fuzz.py
@@ -0,0 +1,1354 @@
+"""Model-based fuzzing of sliced execution: ``App.update(component_selector=...)``.
+
+Each seed generates a random app shape (mount_each, directory subpaths, nested
+components, two-level nesting, use_mount, container targets with child rows;
+memoized or not) and a random sequence of steps: source edits, adds, deletes and
+key-type changes, memo version and logic changes, shape changes (a component
+turning into a directory and back, a group moving under a directory prefix),
+selective updates with random selectors (exact, prefix, ancestor, missing,
+empty, root, ancestor-and-descendant), previews, plain updates, full reprocess,
+container schema changes, and injected sink and body failures.
+
+Apps run the same program side by side:
+
+- ``sut`` runs the steps as generated.
+- ``replay`` runs every update as a plain one (the selector dropped), and skips
+ previews and the updates a failure was injected into.
+- ``fresh``, at the end only, is a new app that runs one plain update.
+
+Checked after each step of ``sut``:
+
+- A selective update, failing or not, changes nothing the store holds for an
+ unselected path: every LMDB row whose subject (the component a path entry is
+ for, the child an existence row or a tombstone names) is unselected stays byte
+ for byte, and so do the external target states such a component owns.
+- A preview changes no LMDB row and no external target state.
+- After a plain update that succeeded, the external target states, their owners,
+ the stable paths and the shape of the LMDB rows equal ``replay``'s.
+
+After the last step, one plain update must bring ``sut`` to ``replay``'s and
+``fresh``'s target states and owners.
+
+The byte comparison reads LMDB from a helper process, since it needs the
+``lmdb`` package, which the project does not depend on. Set
+``COCO_FUZZ_LMDB_SERVER`` to a command that runs ``lmdb_dump_server.py`` to
+enable it; without it, the check uses the inspect API (node type, memo flag,
+version and target-state items per path) instead.
+
+More seeds: ``COCO_FUZZ_SEEDS=0-500 COCO_FUZZ_STEPS=40``. A failing seed is
+shrunk to a minimal step list, printed with the failure.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import collections
+import json
+import os
+import random
+import shlex
+import subprocess
+import threading
+import zlib
+from collections.abc import AsyncIterator, Iterator
+from dataclasses import dataclass, field, replace
+from typing import Any
+
+import msgspec
+import pytest
+
+import cocoindex as coco
+import cocoindex.inspect as coco_inspect
+
+from tests import common
+from tests.common.environment import get_env_db_path
+from tests.common.target_states import DictsTargetStateStore, DictTargetStateStore
+
+Key = str | int
+Path = tuple[Key, ...]
+
+KINDS = ["each", "dir", "nested", "deep", "usemount", "container"]
+SIDES = ["sut", "replay", "fresh"]
+
+# ---------------------------------------------------------------------------
+# Targets: one flat store and one container store per side
+# ---------------------------------------------------------------------------
+
+
+class _TolerantDictStore(DictTargetStateStore):
+ """Deletes a missing key as a no-op, as a real target does: after a failed
+ first insert, the engine deletes a row that may never have landed."""
+
+ def _sink(self, context_provider: Any, actions: Any, /) -> None:
+ if self.sink_exception:
+ raise ValueError("injected sink exception")
+ with self._lock:
+ for key, value in actions:
+ if coco.is_non_existence(value):
+ self.data.pop(key, None)
+ else:
+ self.data[key] = value
+
+
+class _TolerantDictsStore(DictsTargetStateStore):
+ """A container store whose deletes, its rows' included, are idempotent."""
+
+ def _child_handler(self, context_provider: Any, action: Any, /) -> Any:
+ with self._lock:
+ existing = self._stores.get(action.name)
+ if existing is not None and not action.destructive:
+ return existing
+ staged = self._staged.get(action.name)
+ if staged is None:
+ staged = _TolerantDictStore()
+ self._staged[action.name] = staged
+ return staged
+
+ def _new_store(self, name: str) -> DictTargetStateStore:
+ staged = self._staged.pop(name, None)
+ return staged if staged is not None else _TolerantDictStore()
+
+ def _sink(self, context_provider: Any, actions: Any, /) -> None:
+ if self.sink_exception:
+ raise ValueError("injected sink exception")
+ with self._lock:
+ for name, _exists, action, destructive in actions:
+ if action == "insert" or (
+ action == "upsert" and (destructive or name not in self._stores)
+ ):
+ self._stores[name] = self._new_store(name)
+ elif action == "delete":
+ self._stores.pop(name, None)
+
+
+FLAT: dict[str, DictTargetStateStore] = {}
+FLAT_PROVIDER: dict[str, Any] = {}
+CONT: dict[str, _TolerantDictsStore] = {}
+CONT_PROVIDER: dict[str, Any] = {}
+for _side in SIDES:
+ FLAT[_side] = _TolerantDictStore()
+ FLAT_PROVIDER[_side] = coco.register_root_target_states_provider(
+ f"fuzz_flat/{_side}", FLAT[_side]
+ )
+ CONT[_side] = _TolerantDictsStore()
+ CONT_PROVIDER[_side] = coco.register_root_target_states_provider(
+ f"fuzz_cont/{_side}", CONT[_side]
+ )
+
+# ---------------------------------------------------------------------------
+# The program. The root reads these globals (it always runs); every other
+# component gets its inputs as arguments, so that memos stay sound.
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Group:
+ name: str
+ kind: str
+ memo: bool
+ prefix: tuple[str, ...] = ()
+ version: int = 0
+ variant: int = 0
+
+ @property
+ def base(self) -> Path:
+ return self.prefix + (self.name,)
+
+
+@dataclass
+class Program:
+ groups: dict[str, Group] = field(default_factory=dict)
+ source: dict[str, dict[Key, int]] = field(default_factory=dict)
+
+
+PROGRAM = Program()
+# (side, path) of a component whose body raises when it runs.
+FAIL: set[tuple[str, Path]] = set()
+_lock = threading.Lock()
+# Counters for a run's report: steps by kind, rows and target states judged.
+STATS: collections.Counter[str] = collections.Counter()
+
+
+def _kr(k: Key) -> str:
+ """A key in a target-state key, typed, with no quotes to escape."""
+ return f"{type(k).__name__}:{k}"
+
+
+def _flat(side: str, key: str, value: Any) -> None:
+ coco.declare_target_state(FLAT_PROVIDER[side].target_state(key, value))
+
+
+def _check_fail(side: str, path: Path) -> None:
+ if (side, path) in FAIL:
+ raise ValueError(f"injected body failure at {path}")
+
+
+# Values the leaves of groups g1 and g3 read besides their arguments, recorded
+# as data dependencies: a change reaches a memoized leaf only through the
+# DataDep's validation. Shared by every side, like the source.
+EXT: dict[str, int] = {}
+DATADEP_GROUPS = ("g1", "g3")
+
+
+def _validate_ext(key: str, prev: int) -> coco.MemoStateOutcome:
+ current = EXT.get(key, 0)
+ return coco.MemoStateOutcome(state=current, memo_valid=current == prev)
+
+
+EXT_DEP = coco.DataDep("fuzz-ext", validate=_validate_ext)
+
+
+def _read_ext(g: str, k: Key) -> int:
+ key = f"{g.split('/')[0]}|{_kr(k)}"
+ value = EXT.get(key, 0)
+ coco.use_data_dep(EXT_DEP, key=key, state=value)
+ return value
+
+
+def _leaf_body(side: str, path: Path, g: str, k: Key, v: int, version: int) -> None:
+ _check_fail(side, path)
+ state = coco.use_state("last", None)
+ state.value = v
+ if g.split("/")[0] in DATADEP_GROUPS:
+ v = v * 100 + _read_ext(g, k)
+ _flat(side, f"{g}|{_kr(k)}", (v, version))
+ if v % 2 == 0:
+ _flat(side, f"{g}|{_kr(k)}|x", version)
+
+
+async def _leaf0(
+ entry: tuple[Key, int], side: str, base: Path, g: str, version: int
+) -> None:
+ k, v = entry
+ _leaf_body(side, base + (k,), g, k, v, version)
+
+
+async def _leaf1(
+ entry: tuple[Key, int], side: str, base: Path, g: str, version: int
+) -> None:
+ # The other logic: also declares a third target state.
+ k, v = entry
+ _leaf_body(side, base + (k,), g, k, v, version)
+ _flat(side, f"{g}|{_kr(k)}|v1", -v)
+
+
+async def _cleaf(
+ entry: tuple[Key, int], side: str, base: Path, provider: Any, version: int
+) -> None:
+ k, v = entry
+ _check_fail(side, base + (k,))
+ coco.declare_target_state(provider.target_state(_kr(k), (v, version)))
+
+
+_FNS: dict[tuple[str, bool, int], Any] = {}
+
+
+def _wrapped(name: str, body: Any, memo: bool, version: int) -> Any:
+ """One `coco.fn` per (body, memo, version), so that a memo stays valid across
+ steps and a version or body change is a logic change."""
+ key = (name, memo, version)
+ with _lock:
+ if key not in _FNS:
+ _FNS[key] = (
+ coco.fn(memo=True, version=version)(body) if memo else coco.fn(body)
+ )
+ return _FNS[key]
+
+
+def leaf_fn(g: Group) -> Any:
+ return _wrapped(
+ f"leaf{g.variant}", _leaf0 if g.variant == 0 else _leaf1, g.memo, g.version
+ )
+
+
+async def _sum_helper(values: tuple[int, ...]) -> int:
+ return sum(values)
+
+
+async def _mount_leaves(
+ side: str, g: Group, base: Path, items: dict[Key, int], relative: bool
+) -> None:
+ fn = leaf_fn(g)
+ for k, v in items.items():
+ sub = (
+ coco.component_subpath(k) if relative else coco.component_subpath(*base, k)
+ )
+ await coco.mount(sub, fn, (k, v), side, base, g.name, g.version)
+
+
+async def nested_mid(side: str, g: Group, items: dict[Key, int]) -> None:
+ await _mount_leaves(side, g, g.base, items, relative=True)
+ total = await _sum_helper(tuple(sorted(items.values())))
+ _flat(side, f"{g.name}|mid", total)
+ _check_fail(side, g.base)
+
+
+async def deep_mid2(side: str, g: Group, k: Key, v: int) -> None:
+ path = g.base + (k,)
+ fn = leaf_fn(g)
+ for j in range(v % 3 + 1):
+ await coco.mount(
+ coco.component_subpath(j),
+ fn,
+ (j, v + j),
+ side,
+ path,
+ f"{g.name}/{_kr(k)}",
+ g.version,
+ )
+ _check_fail(side, path)
+
+
+async def deep_mid(side: str, g: Group, items: dict[Key, int]) -> None:
+ for k, v in items.items():
+ await coco.mount(
+ coco.component_subpath(k),
+ _wrapped("deep_mid2", deep_mid2, g.memo, g.version),
+ side,
+ g,
+ k,
+ v,
+ )
+ _flat(side, f"{g.name}|deep", len(items))
+
+
+async def use_mount_mid(side: str, g: Group, items: dict[Key, int]) -> int:
+ await _mount_leaves(side, g, g.base, items, relative=True)
+ _check_fail(side, g.base)
+ return len(items)
+
+
+def declare_container(
+ side: str, name: str
+) -> coco.PendingTargetStateProvider[str, None]:
+ return coco.declare_target_state_with_child(
+ CONT_PROVIDER[side].target_state(name, None)
+ )
+
+
+class _KeyedItems:
+ """Items that a selective update can read by key, as `localfs` items can."""
+
+ def __init__(self, pairs: list[tuple[Any, Any]]) -> None:
+ self._pairs = pairs
+
+ def __iter__(self) -> Iterator[tuple[Any, Any]]:
+ return iter(self._pairs)
+
+ async def __coco_items_for_keys__(
+ self, keys: list[Any]
+ ) -> AsyncIterator[tuple[Any, Any]]:
+ for key in keys:
+ for k, v in self._pairs:
+ if type(k) is type(key) and k == key:
+ yield k, v
+
+
+def _items(g: Any, items: dict[Any, Any]) -> Any:
+ """Half of the groups read by key under a selector, the other half list."""
+ pairs = [(k, (k, v)) for k, v in items.items()]
+ return _KeyedItems(pairs) if zlib.crc32(g.name.encode()) % 2 else pairs
+
+
+async def app_main(side: str) -> None:
+ for g in list(PROGRAM.groups.values()):
+ items = dict(PROGRAM.source.get(g.name, {}))
+ base = g.base
+ if g.kind == "each":
+ await coco.mount_each(
+ coco.component_subpath(*base),
+ leaf_fn(g),
+ _items(g, items),
+ side,
+ base,
+ g.name,
+ g.version,
+ )
+ elif g.kind == "dir":
+ await _mount_leaves(side, g, base, items, relative=False)
+ elif g.kind == "nested":
+ await coco.mount(
+ coco.component_subpath(*base),
+ _wrapped("nested_mid", nested_mid, g.memo, g.version),
+ side,
+ g,
+ items,
+ )
+ elif g.kind == "deep":
+ await coco.mount(
+ coco.component_subpath(*base),
+ _wrapped("deep_mid", deep_mid, g.memo, g.version),
+ side,
+ g,
+ items,
+ )
+ elif g.kind == "usemount":
+ n = await coco.use_mount(
+ coco.component_subpath(*base), use_mount_mid, side, g, items
+ )
+ _flat(side, f"{g.name}|um", n)
+ elif g.kind == "container":
+ provider = await coco.use_mount(
+ coco.component_subpath(*base, "setup"), declare_container, side, g.name
+ )
+ await coco.mount_each(
+ coco.component_subpath(*base, "rows"),
+ _wrapped("cleaf", _cleaf, g.memo, g.version),
+ _items(g, items),
+ side,
+ base + ("rows",),
+ provider,
+ g.version,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Steps
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Step:
+ op: str
+ group: str = ""
+ key: Key = ""
+ value: int = 0
+ kind: str = ""
+ # For "update": "plain", "selective" or "preview".
+ mode: str = ""
+ selector: tuple[Path, ...] = ()
+ full_reprocess: bool = False
+ # For "update": None, "sink", "body:<path repr>", "schema:destructive|lossy".
+ inject: str = ""
+ fail_path: Path = ()
+
+ def __str__(self) -> str:
+ if self.op == "update":
+ parts = [f"update {self.mode}"]
+ if self.mode != "plain":
+ parts.append(f"selector={list(self.selector)}")
+ if self.full_reprocess:
+ parts.append("full_reprocess")
+ if self.inject:
+ parts.append(f"inject={self.inject}")
+ if self.fail_path:
+ parts.append(f"fail_path={self.fail_path}")
+ return " ".join(parts)
+ fields = [f"{self.op}", self.group]
+ if self.op in ("edit", "add", "delete", "retype", "ext_edit"):
+ fields.append(repr(self.key))
+ if self.op in ("edit", "add", "ext_edit"):
+ fields.append(str(self.value))
+ if self.kind:
+ fields.append(self.kind)
+ if self.op == "add_group":
+ fields.append("memo" if self.value else "no-memo")
+ return " ".join(fields)
+
+
+KEY_POOL: list[Key] = ["a", "b", "c", "d", 1, 2, 3, "1"]
+
+
+def apply_program_step(program: Program, step: Step) -> None:
+ """Apply a non-update step to the program; tolerant of steps a shrink made
+ meaningless (editing a group that is gone, deleting a key that is not there)."""
+ g = program.groups.get(step.group)
+ src = program.source.setdefault(step.group, {})
+ if step.op == "ext_edit":
+ EXT[f"{step.group}|{_kr(step.key)}"] = step.value
+ elif step.op in ("edit", "add"):
+ if g is not None:
+ src[step.key] = step.value
+ elif step.op == "delete":
+ src.pop(step.key, None)
+ elif step.op == "retype":
+ if step.key in src:
+ v = src.pop(step.key)
+ other: Key = (
+ str(step.key)
+ if isinstance(step.key, int)
+ else (int(step.key) if str(step.key).isdigit() else step.key + "_")
+ )
+ src[other] = v
+ elif g is None:
+ if step.op == "add_group":
+ program.groups[step.group] = Group(
+ step.group, step.kind, memo=bool(step.value)
+ )
+ elif step.op == "bump_version":
+ program.groups[step.group] = replace(g, version=g.version + 1)
+ elif step.op == "flip_variant":
+ program.groups[step.group] = replace(g, variant=1 - g.variant)
+ elif step.op == "toggle_memo":
+ program.groups[step.group] = replace(g, memo=not g.memo)
+ elif step.op == "reshape":
+ program.groups[step.group] = replace(g, kind=step.kind)
+ elif step.op == "move":
+ program.groups[step.group] = replace(g, prefix=() if g.prefix else ("d",))
+ elif step.op == "drop_group":
+ del program.groups[step.group]
+
+
+def model_paths(program: Program) -> list[Path]:
+ """Every component and directory path the program mounts."""
+ out: list[Path] = [()]
+ for g in program.groups.values():
+ base = g.base
+ out.extend(base[:i] for i in range(1, len(base)))
+ items = program.source.get(g.name, {})
+ out.append(base)
+ if g.kind == "container":
+ out += [base + ("setup",), base + ("rows",)]
+ out += [base + ("rows", k) for k in items]
+ elif g.kind == "deep":
+ for k, v in items.items():
+ out.append(base + (k,))
+ out += [base + (k, j) for j in range(v % 3 + 1)]
+ else:
+ out += [base + (k,) for k in items]
+ return out
+
+
+def model_components(program: Program) -> set[Path]:
+ """The component paths the program mounts (the root included)."""
+ out: set[Path] = {()}
+ for g in program.groups.values():
+ base = g.base
+ items = program.source.get(g.name, {})
+ if g.kind in ("nested", "deep", "usemount"):
+ out.add(base)
+ if g.kind == "container":
+ out.add(base + ("setup",))
+ out.update(base + ("rows", k) for k in items)
+ elif g.kind == "deep":
+ for k, v in items.items():
+ out.add(base + (k,))
+ out.update(base + (k, j) for j in range(v % 3 + 1))
+ else:
+ out.update(base + (k,) for k in items)
+ return out
+
+
+def model_dirs(program: Program) -> set[Path]:
+ """The paths the program mounts as directories: the strict prefixes of
+ its components that are not components. A directory nothing is mounted
+ under is not declared at all."""
+ components = model_components(program)
+ return {
+ c[:i] for c in components for i in range(1, len(c)) if c[:i] not in components
+ }
+
+
+def generate(seed: int, n_steps: int) -> list[Step]:
+ rng = random.Random(seed)
+ program = Program()
+ steps: list[Step] = []
+ seen_paths: set[Path] = set()
+ n_groups = rng.randint(1, 4)
+ for i in range(n_groups):
+ name = f"g{i}"
+ kind = rng.choice(KINDS)
+ s = Step("add_group", name, kind=kind, value=rng.randint(0, 1))
+ steps.append(s)
+ apply_program_step(program, s)
+ if rng.random() < 0.3:
+ s = Step("move", name)
+ steps.append(s)
+ apply_program_step(program, s)
+ for k in rng.sample(KEY_POOL, rng.randint(0, 4)):
+ s = Step("add", name, key=k, value=rng.randint(0, 9))
+ steps.append(s)
+ apply_program_step(program, s)
+ # The first update is selective now and then: a first-ever run with a selector.
+ while len(steps) < n_steps + n_groups:
+ seen_paths.update(model_paths(program))
+ r = rng.random()
+ names = list(program.groups) or ["g0"]
+ g = rng.choice(names)
+ src = program.source.get(g, {})
+ if r < 0.45:
+ s = _gen_update(rng, program, seen_paths)
+ elif r < 0.60:
+ s = Step(
+ "edit",
+ g,
+ key=rng.choice(list(src) or KEY_POOL),
+ value=rng.randint(0, 9),
+ )
+ elif r < 0.68:
+ s = Step("add", g, key=rng.choice(KEY_POOL), value=rng.randint(0, 9))
+ elif r < 0.76:
+ s = Step("delete", g, key=rng.choice(list(src) or KEY_POOL))
+ elif r < 0.79:
+ s = Step("retype", g, key=rng.choice(list(src) or KEY_POOL))
+ elif r < 0.81 and g in DATADEP_GROUPS:
+ s = Step(
+ "ext_edit",
+ g,
+ key=rng.choice(list(src) or KEY_POOL),
+ value=rng.randint(0, 9),
+ )
+ elif r < 0.83:
+ s = Step(rng.choice(["bump_version", "flip_variant", "toggle_memo"]), g)
+ elif r < 0.90:
+ s = Step("reshape", g, kind=rng.choice(KINDS))
+ elif r < 0.93:
+ s = Step("move", g)
+ elif r < 0.96:
+ s = Step("drop_group", g)
+ else:
+ missing = [f"g{i}" for i in range(5) if f"g{i}" not in program.groups]
+ if not missing:
+ continue
+ s = Step(
+ "add_group",
+ rng.choice(missing),
+ kind=rng.choice(KINDS),
+ value=rng.randint(0, 1),
+ )
+ steps.append(s)
+ apply_program_step(program, s)
+ return steps
+
+
+def _gen_update(rng: random.Random, program: Program, seen: set[Path]) -> Step:
+ mode = rng.choices(["plain", "selective", "preview"], [0.25, 0.6, 0.15])[0]
+ current = model_paths(program)
+ pool = sorted(seen | set(current), key=repr)
+ selector: list[Path] = []
+ if mode != "plain":
+ shape = rng.random()
+ if shape < 0.08:
+ selector = []
+ elif shape < 0.12:
+ selector = [()]
+ elif shape < 0.17:
+ selector = [("zz", "missing")]
+ elif shape < 0.27 and pool:
+ # An ancestor and a descendant of it, at once.
+ p = rng.choice([p for p in pool if len(p) >= 2] or pool)
+ selector = [p[:1], p] if rng.random() < 0.5 else [p, p[:1]]
+ else:
+ selector = rng.sample(pool, min(len(pool), rng.randint(1, 3)))
+ inject = ""
+ fail_path: Path = ()
+ r = rng.random()
+ if mode != "preview" and r < 0.08:
+ inject = "sink"
+ elif mode != "preview" and r < 0.18:
+ candidates = [p for p in current if p]
+ if candidates:
+ inject = "body"
+ fail_path = rng.choice(candidates)
+ elif r < 0.24 and any(g.kind == "container" for g in program.groups.values()):
+ inject = "schema:" + rng.choice(["destructive", "lossy"])
+ return Step(
+ "update",
+ mode=mode,
+ selector=tuple(selector),
+ full_reprocess=rng.random() < 0.15,
+ inject=inject,
+ fail_path=fail_path,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Observing an app: LMDB rows, external target states, owners
+# ---------------------------------------------------------------------------
+
+
+class RawReader:
+ """The helper process that dumps an app's LMDB database."""
+
+ def __init__(self, command: str) -> None:
+ self._proc = subprocess.Popen(
+ shlex.split(command),
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ text=True,
+ )
+
+ def rows(self, env_dir: str, app_name: str) -> dict[bytes, bytes]:
+ assert self._proc.stdin is not None and self._proc.stdout is not None
+ self._proc.stdin.write(json.dumps({"path": env_dir, "db": app_name}) + "\n")
+ self._proc.stdin.flush()
+ out = json.loads(self._proc.stdout.readline())
+ if "error" in out:
+ raise RuntimeError(out["error"])
+ return {bytes.fromhex(k): bytes.fromhex(v) for k, v in out["rows"]}
+
+ def close(self) -> None:
+ if self._proc.stdin:
+ self._proc.stdin.close()
+ self._proc.wait(timeout=10)
+
+
+class _Reader:
+ def __init__(self, data: bytes, pos: int) -> None:
+ self.data = data
+ self.pos = pos
+
+ def byte(self) -> int:
+ b = self.data[self.pos]
+ self.pos += 1
+ return b
+
+ def slice(self) -> bytes:
+ out = bytearray()
+ while True:
+ b = self.byte()
+ if b == 0:
+ return bytes(out)
+ if b == 1:
+ b = self.byte()
+ out.append(b)
+
+ def key(self) -> Key | None:
+ """One storekey-encoded StableKey; None at the end of a path."""
+ tag = self.byte()
+ if tag == 0:
+ return None
+ if tag == 5:
+ raw = self.data[self.pos : self.pos + 8]
+ self.pos += 8
+ return int.from_bytes(raw, "big") - (1 << 63)
+ if tag == 6:
+ return self.slice().decode()
+ if tag == 3:
+ return "<sym>" + self.slice().decode()
+ raise ValueError(f"unsupported key tag {tag}")
+
+ def path(self) -> Path:
+ parts: list[Key] = []
+ while (k := self.key()) is not None:
+ parts.append(k)
+ return tuple(parts)
+
+
+@dataclass(frozen=True)
+class RowId:
+ """What one LMDB row is about: `subject` is the path the selector judges it
+ by."""
+
+ kind: str # "path" or "target_state" or "global"
+ subject: Path | None
+ entry: str
+ raw_key: bytes
+
+
+def classify_row(key: bytes, value: bytes) -> RowId:
+ if key[0] == 0x10:
+ r = _Reader(key, 1)
+ path = r.path()
+ tag = r.byte()
+ if tag in (0x20, 0x30, 0x34, 0x40):
+ return RowId("path", path, f"{tag:#x}", key)
+ if tag == 0xA0:
+ k = r.key()
+ assert k is not None
+ return RowId("path", path + (k,), "child_existence", key)
+ if tag == 0xB0:
+ return RowId("path", path + r.path(), "tombstone", key)
+ raise ValueError(f"unknown path entry {tag:#x}")
+ if key[0] == 0x20:
+ owner = msgspec.msgpack.decode(value)
+ parts = owner.get("C") if isinstance(owner, dict) else None
+ return RowId(
+ "target_state", tuple(parts) if parts is not None else None, "ts", key
+ )
+ return RowId("global", None, f"{key[0]:#x}", key)
+
+
+def use_mount_paths(program: Program) -> list[Path]:
+ """The components the root reaches through `use_mount`: they run whatever
+ the selector says, as the root waits for their value."""
+ out: list[Path] = []
+ for g in program.groups.values():
+ if g.kind == "usemount":
+ out.append(g.base)
+ elif g.kind == "container":
+ out.append(g.base + ("setup",))
+ return out
+
+
+def selection(
+ selector: tuple[Path, ...], path: Path, always_run: list[Path] = []
+) -> str:
+ """Python model of `ComponentSelector::classify`, plus the components that
+ run whatever it says (the root, a use_mount child of the root)."""
+
+ def same(a: Key, b: Key) -> bool:
+ return type(a) is type(b) and a == b
+
+ def is_prefix(p: Path, q: Path) -> bool:
+ return len(p) <= len(q) and all(same(x, y) for x, y in zip(p, q))
+
+ if any(is_prefix(s, path) for s in selector):
+ return "selected"
+ # The root always runs, so it counts as an ancestor even of nothing.
+ if not path or any(is_prefix(path, s) for s in selector):
+ return "ancestor"
+ if any(is_prefix(path, u) for u in always_run):
+ return "use_mount"
+ return "unselected"
+
+
+def external(side: str) -> dict[tuple[str, ...], Any]:
+ out: dict[tuple[str, ...], Any] = {}
+ for k, v in FLAT[side].data.items():
+ out[("flat", k)] = v.data
+ for name, store in CONT[side].data.items():
+ out[("cont", name)] = None
+ for k, v in store.items():
+ out[("cont", name, k)] = v.data
+ return out
+
+
+def owners(app: coco.App[Any, Any], side: str) -> dict[tuple[str, ...], Path]:
+ """External target-state key -> owning component path."""
+
+ async def collect() -> dict[tuple[str, ...], Path]:
+ out: dict[tuple[str, ...], Path] = {}
+ async for entry in coco_inspect.iter_target_states(app):
+ assert not entry.dangling, f"dangling owner row {entry.readable_path}"
+ segs = list(entry.readable_segments)
+ out[_ext_key(segs, side)] = _path_of(
+ coco.StablePath(entry.owner_component_path)
+ )
+ return out
+
+ return asyncio.run(collect())
+
+
+def _ext_key(segs: list[str], side: str) -> tuple[str, ...]:
+ def unq(s: str) -> str:
+ return s[1:-1] if len(s) >= 2 and s[0] == s[-1] == '"' else s
+
+ provider = segs[0]
+ rest = [unq(s) for s in segs[1:]]
+ if "fuzz_flat" in provider:
+ return ("flat", *rest)
+ if "fuzz_cont" in provider:
+ return ("cont", *rest)
+ return ("?", provider, *rest)
+
+
+def _path_of(path: coco.StablePath) -> Path:
+ """A stable path as the model's tuple (the fuzzer uses str and int keys)."""
+ return tuple(k for k in path.parts() if isinstance(k, (str, int)))
+
+
+def _plain(obj: Any, depth: int = 0) -> Any:
+ """An inspect object as nested tuples of its public fields, to compare."""
+ if depth > 6 or obj is None or isinstance(obj, (str, int, float, bytes, bool)):
+ return obj
+ if isinstance(obj, (list, tuple)):
+ return tuple(_plain(x, depth + 1) for x in obj)
+ if isinstance(obj, dict):
+ return tuple(sorted((repr(k), _plain(v, depth + 1)) for k, v in obj.items()))
+ fields = [f for f in sorted(dir(obj)) if not f.startswith("_")]
+ out = []
+ for f in fields:
+ value = getattr(obj, f)
+ if not callable(value):
+ out.append((f, _plain(value, depth + 1)))
+ return (type(obj).__name__, tuple(out)) if out else repr(obj)
+
+
+def path_details(app: coco.App[Any, Any]) -> dict[Path, Any]:
+ async def collect() -> dict[Path, Any]:
+ out: dict[Path, Any] = {}
+ async for d in coco_inspect.iter_stable_path_details(app):
+ out[_path_of(coco.StablePath(d.path))] = (
+ str(d.node_type),
+ d.version,
+ d.processor_name,
+ d.has_memoization,
+ sorted(repr(_plain(i)) for i in d.target_state_items),
+ )
+ return out
+
+ return asyncio.run(collect())
+
+
+# ---------------------------------------------------------------------------
+# Running a seed
+# ---------------------------------------------------------------------------
+
+
+class Failure(AssertionError):
+ pass
+
+
+@dataclass
+class Snapshot:
+ raw: dict[bytes, bytes] | None
+ details: dict[Path, Any]
+ external: dict[tuple[str, ...], Any]
+ owners: dict[tuple[str, ...], Path]
+
+
+class Runner:
+ def __init__(self, tag: str, raw_reader: RawReader | None) -> None:
+ self.env = common.create_test_env(__file__, suffix=tag)
+ self.env_dir = str(
+ get_env_db_path(f"core__test_component_selector_fuzz__{tag}") / "mdb"
+ )
+ self.raw_reader = raw_reader
+ self.tag = tag
+ self.apps: dict[str, coco.App[Any, Any]] = {}
+ self.log: list[str] = []
+
+ def app(self, side: str) -> coco.App[Any, Any]:
+ if side not in self.apps:
+ self.apps[side] = coco.App(
+ coco.AppConfig(name=f"fz_{side}", environment=self.env), app_main, side
+ )
+ return self.apps[side]
+
+ def snapshot(self, side: str) -> Snapshot:
+ app = self.app(side)
+ raw = (
+ self.raw_reader.rows(self.env_dir, f"fz_{side}")
+ if self.raw_reader is not None
+ else None
+ )
+ return Snapshot(raw, path_details(app), external(side), owners(app, side))
+
+ def update(self, side: str, step: Step) -> Exception | None:
+ app = self.app(side)
+ kwargs: dict[str, Any] = {"full_reprocess": step.full_reprocess}
+ # COCO_FUZZ_MUTANT=ignore_selector checks the checker: it must fail.
+ mutant = os.environ.get("COCO_FUZZ_MUTANT") == "ignore_selector"
+ if side == "sut" and step.mode != "plain" and not mutant:
+ kwargs["component_selector"] = [_to_stable_path(p) for p in step.selector]
+ if side == "sut" and step.mode == "preview":
+ kwargs["preview"] = True
+ try:
+ app.update_blocking(**kwargs)
+ except Exception as e: # noqa: BLE001
+ return e
+ return None
+
+
+def _to_stable_path(p: Path) -> coco.StablePath:
+ out = coco.ROOT_PATH
+ for k in p:
+ out = out / k
+ return out
+
+
+def _reset_targets() -> None:
+ for side in SIDES:
+ FLAT[side].clear()
+ FLAT[side].sink_exception = False
+ CONT[side].clear()
+ CONT[side].sink_exception = False
+ FAIL.clear()
+
+
+def check_unselected_untouched(
+ step: Step, before: Snapshot, after: Snapshot, preview: bool
+) -> None:
+ sel = step.selector
+ always = use_mount_paths(PROGRAM)
+
+ def unselected(subject: Path) -> bool:
+ return selection(sel, subject, always) == "unselected"
+
+ # A selected component that declares a target state an unselected one owns
+ # takes it over, as in a plain update; the takeover removes the item from
+ # the old owner's tracking record. That edit, and only it, is allowed.
+ taken_from = {
+ before.owners[k]
+ for k in before.owners
+ if k in after.owners
+ and after.owners[k] != before.owners[k]
+ and unselected(before.owners[k])
+ and not unselected(after.owners[k])
+ }
+
+ def judged(subject: Path | None, entry: str = "") -> bool:
+ if preview or subject is None:
+ return True
+ if entry == "0x40" and subject in taken_from:
+ STATS["takeover edits of an unselected tracking record"] += 1
+ return False
+ if entry == "0x20" and any(t[: len(subject)] == subject for t in taken_from):
+ # A takeover drops the component memo of the old owner and of each
+ # ancestor: it no longer matches the tracking record.
+ STATS["takeover drops of an unselected component memo"] += 1
+ return False
+ return unselected(subject)
+
+ if before.raw is not None and after.raw is not None:
+ for key in before.raw:
+ row = classify_row(key, before.raw[key])
+ if row.kind != "global" and judged(row.subject):
+ STATS["unselected rows byte-compared"] += 1
+ for key in sorted(set(before.raw) | set(after.raw)):
+ b, a = before.raw.get(key), after.raw.get(key)
+ if a == b:
+ continue
+ row = classify_row(key, b if b is not None else a) # type: ignore[arg-type]
+ if row.kind == "global" and not preview:
+ continue
+ if row.kind == "global" and row.entry == "0x28":
+ continue # segment names: write-once, harmless
+ if row.kind == "target_state" and b is not None and a is not None:
+ after_owner = classify_row(key, a).subject
+ if (
+ not preview
+ and row.subject in taken_from
+ and after_owner is not None
+ and not unselected(after_owner)
+ ):
+ continue
+ if judged(row.subject, row.entry):
+ change = "added" if b is None else "removed" if a is None else "changed"
+ raise Failure(
+ f"LMDB row {row.entry} for unselected {row.subject} {change}"
+ f" (key {key.hex()})"
+ )
+ else:
+ for path in sorted(set(before.details) | set(after.details), key=repr):
+ if any(t[: len(path)] == path for t in taken_from) and not preview:
+ continue # A takeover edits the old owner and drops memos up the chain.
+ if before.details.get(path) != after.details.get(path) and judged(path):
+ raise Failure(
+ f"stable path detail of unselected {path} changed:"
+ f" {before.details.get(path)} -> {after.details.get(path)}"
+ )
+
+ for ext_key in sorted(set(before.external) | set(after.external), key=repr):
+ b, a = before.external.get(ext_key), after.external.get(ext_key)
+ if a == b and before.owners.get(ext_key) == after.owners.get(ext_key):
+ continue
+ owner_paths = {
+ p for p in (before.owners.get(ext_key), after.owners.get(ext_key)) if p
+ }
+ if before.owners.get(ext_key) in taken_from and not unselected(
+ after.owners.get(ext_key, ())
+ ):
+ continue
+ if (
+ not preview
+ and ext_key[0] == "cont"
+ and len(ext_key) == 3
+ and ("cont", ext_key[1]) not in after.external
+ ):
+ # A selected container owner that is gone takes the rows with it.
+ # Nothing can declare under it any more; the next plain update
+ # cleans up their tracking (checked against replay).
+ STATS["container rows gone with their selected, deleted owner"] += 1
+ continue
+ if preview or any(unselected(p) for p in owner_paths):
+ raise Failure(
+ f"external target state {ext_key} of unselected owner {owner_paths}:"
+ f" {b} -> {a}; owner {before.owners.get(ext_key)} ->"
+ f" {after.owners.get(ext_key)}"
+ )
+
+
+def check_reached_like_replay(
+ step: Step, before: Snapshot, sut: Snapshot, replay: Snapshot
+) -> None:
+ """What a selective update runs ends as a plain update leaves it: every
+ target state owned, on either side, by a component the update reached
+ (selected, an ancestor of a selected path, a use_mount child of the root)
+ is the same on both sides, with the same owner."""
+ sel = step.selector
+ always = use_mount_paths(PROGRAM)
+
+ dirs = model_dirs(PROGRAM)
+ mounted = model_components(PROGRAM) | dirs
+
+ def reached(path: Path | None) -> bool:
+ """The update runs the component at `path`, or deletes it. A path the
+ program no longer mounts is deleted when the walk from the root gets
+ to it: each ancestor still mounted, covered by the selector, or a
+ directory on disk. An ancestor that is a component on disk and no
+ longer mounted stays whole, and so does what lies below it."""
+ if path is None or selection(sel, path, always) == "unselected":
+ return False
+ if path in mounted and path not in dirs:
+ return True
+ if selection(sel, path, always) != "selected":
+ # Gone, and only an ancestor of a selected path: kept whole.
+ return False
+ for i in range(1, len(path)):
+ a = path[:i]
+ if a in mounted:
+ continue
+ if selection(sel, a, always) == "selected":
+ return True
+ detail = before.details.get(a)
+ # A component whose delete failed has lost its entry in its
+ # parent, so inspect lists it as a directory; its processor
+ # name still marks it a component.
+ if detail is not None and ("Component" in detail[0] or detail[2]):
+ return False
+ return True
+
+ keys = (
+ set(sut.external) | set(replay.external) | set(sut.owners) | set(replay.owners)
+ )
+ for k in sorted(keys, key=repr):
+ if k[0] == "cont" and len(k) == 2:
+ continue
+ so, ro = sut.owners.get(k), replay.owners.get(k)
+ if not (reached(so) or reached(ro)):
+ continue
+ # An unselected component that still declares the key wins it in the
+ # replay only because the replay ran it.
+ if (so is not None and not reached(so)) or (ro is not None and not reached(ro)):
+ continue
+ STATS["reached target states compared with replay"] += 1
+ if sut.external.get(k) != replay.external.get(k) or so != ro:
+ raise Failure(
+ f"reached target state {k}: sut {sut.external.get(k)} owned by {so},"
+ f" replay {replay.external.get(k)} owned by {ro}"
+ )
+
+
+def row_shape(raw: dict[bytes, bytes] | None) -> set[tuple[Any, ...]]:
+ if raw is None:
+ return set()
+ out: set[tuple[Any, ...]] = set()
+ for k, v in raw.items():
+ row = classify_row(k, v)
+ if row.kind == "path":
+ out.add((row.entry, row.subject))
+ elif row.kind == "target_state":
+ out.add(("ts_owner", row.subject))
+ return out
+
+
+def compare_sides(r: Runner, a: str, b: str, where: str) -> None:
+ sa, sb = r.snapshot(a), r.snapshot(b)
+ if sa.external != sb.external:
+ diff = {
+ k: (sa.external.get(k), sb.external.get(k))
+ for k in set(sa.external) | set(sb.external)
+ if sa.external.get(k) != sb.external.get(k)
+ }
+ raise Failure(f"{where}: external target states of {a} != {b}: {diff}")
+ if sa.owners != sb.owners:
+ diff = {
+ k: (sa.owners.get(k), sb.owners.get(k))
+ for k in set(sa.owners) | set(sb.owners)
+ if sa.owners.get(k) != sb.owners.get(k)
+ }
+ raise Failure(f"{where}: target-state owners of {a} != {b}: {diff}")
+ pa = set(sa.details)
+ pb = set(sb.details)
+ if pa != pb:
+ raise Failure(
+ f"{where}: stable paths of {a} - {b}: {pa - pb}; {b} - {a}: {pb - pa}"
+ )
+ ra, rb = row_shape(sa.raw), row_shape(sb.raw)
+ # Function memos depend on which runs happened; component memos on whether
+ # an earlier run left one. Compare the rest.
+ keep = {"0x40", "child_existence", "tombstone", "0x34", "ts_owner"}
+ ra = {x for x in ra if x[0] in keep}
+ rb = {x for x in rb if x[0] in keep}
+ if ra != rb:
+ raise Failure(
+ f"{where}: LMDB rows of {a} - {b}: {sorted(ra - rb, key=repr)}; {b} - {a}: {sorted(rb - ra, key=repr)}"
+ )
+
+
+def run_steps(steps: list[Step], tag: str, raw_reader: RawReader | None) -> list[str]:
+ """Run `steps`; raise Failure on a contract violation. Returns the log."""
+ global PROGRAM
+ PROGRAM = Program()
+ EXT.clear()
+ _reset_targets()
+ r = Runner(tag, raw_reader)
+ try:
+ for i, step in enumerate(steps):
+ if step.op != "update":
+ apply_program_step(PROGRAM, step)
+ continue
+ where = f"step {i} ({step})"
+ injected = bool(step.inject) and not step.inject.startswith("schema")
+ # replay: plain, without failures; previews are skipped.
+ if step.mode != "preview" and not injected:
+ if step.inject.startswith("schema"):
+ CONT["replay"].child_invalidation = step.inject.split(":")[1] # type: ignore[assignment]
+ err = r.update("replay", step)
+ CONT["replay"].child_invalidation = None
+ if err is not None:
+ raise Failure(f"{where}: replay failed: {err!r}")
+ before = r.snapshot("sut")
+ if step.inject == "sink":
+ FLAT["sut"].sink_exception = True
+ CONT["sut"].sink_exception = True
+ elif step.inject == "body":
+ FAIL.add(("sut", step.fail_path))
+ elif step.inject.startswith("schema"):
+ CONT["sut"].child_invalidation = step.inject.split(":")[1] # type: ignore[assignment]
+ err = r.update("sut", step)
+ STATS[
+ f"sut {step.mode}{' full_reprocess' if step.full_reprocess else ''}{' inject=' + step.inject.split(':')[0] if step.inject else ''}{' (failed)' if err else ''}"
+ ] += 1
+ FLAT["sut"].sink_exception = False
+ CONT["sut"].sink_exception = False
+ CONT["sut"].child_invalidation = None
+ FAIL.clear()
+ r.log.append(f"{where}: {'error ' + repr(err)[:120] if err else 'ok'}")
+ # A selective update refuses a container change, as it would leave
+ # the unselected rows behind. Nothing of the change may apply.
+ refused = (
+ err is not None
+ and step.mode in ("selective", "preview")
+ and step.inject.startswith("schema")
+ and "without component_selector" in str(err)
+ )
+ if refused:
+ STATS["container changes refused under a selector"] += 1
+ if err is not None and not injected and not refused:
+ raise Failure(f"{where}: sut failed without injection: {err!r}")
+ after = r.snapshot("sut")
+ if step.mode in ("selective", "preview"):
+ check_unselected_untouched(step, before, after, step.mode == "preview")
+ if step.mode == "selective" and not injected and not refused:
+ check_reached_like_replay(step, before, after, r.snapshot("replay"))
+ if step.mode == "plain" and not injected:
+ compare_sides(r, "sut", "replay", where)
+ STATS["plain steps compared with replay"] += 1
+ # The end: one plain update on each side, and a fresh app.
+ final = Step("update", mode="plain")
+ for side in ("sut", "replay", "fresh"):
+ err = r.update(side, final)
+ if err is not None:
+ raise Failure(f"final plain update of {side} failed: {err!r}")
+ compare_sides(r, "sut", "replay", "final")
+ sut, fresh = r.snapshot("sut"), r.snapshot("fresh")
+ if sut.external != fresh.external:
+ raise Failure(f"final: sut != fresh: {sut.external} vs {fresh.external}")
+ if sut.owners != fresh.owners:
+ raise Failure(f"final: owners sut != fresh: {sut.owners} vs {fresh.owners}")
+ STATS["seeds passed"] += 1
+ return r.log
+ finally:
+ r.env.close()
+
+
+_attempt = 0
+
+
+def run_seed(
+ seed: int, n_steps: int, raw_reader: RawReader | None, shrink: bool = True
+) -> None:
+ global _attempt
+ steps = generate(seed, n_steps)
+ try:
+ _attempt += 1
+ run_steps(steps, f"s{seed}_{_attempt}", raw_reader)
+ return
+ except Failure as first:
+ if not shrink:
+ raise
+ minimal, message = shrink_steps(steps, raw_reader, str(first))
+ lines = "\n".join(f" {s}" for s in minimal)
+ raise Failure(
+ f"seed {seed}: {first}\nminimal steps ({len(minimal)}):\n{lines}\n"
+ f"minimal failure: {message}"
+ ) from None
+
+
+def _fails(steps: list[Step], raw_reader: RawReader | None) -> str | None:
+ global _attempt
+ _attempt += 1
+ try:
+ run_steps(steps, f"shrink_{_attempt}", raw_reader)
+ except Failure as e:
+ return str(e)
+ except Exception as e: # noqa: BLE001
+ return f"crash: {e!r}"
+ return None
+
+
+def _signature(message: str) -> str:
+ """The kind of failure, so a shrink does not wander to a different bug."""
+ for marker in (
+ "LMDB row",
+ "external target state",
+ "external target states",
+ "target-state owners",
+ "stable paths",
+ "LMDB rows",
+ "failed",
+ "crash",
+ ):
+ if marker in message:
+ return marker
+ return message[:40]
+
+
+def shrink_steps(
+ steps: list[Step], raw_reader: RawReader | None, message: str
+) -> tuple[list[Step], str]:
+ sig = _signature(message)
+ chunk = max(1, len(steps) // 2)
+ while chunk >= 1:
+ i = 0
+ changed = False
+ while i < len(steps):
+ candidate = steps[:i] + steps[i + chunk :]
+ got = _fails(candidate, raw_reader)
+ if got is not None and _signature(got) == sig:
+ steps, message, changed = candidate, got, True
+ else:
+ i += chunk
+ if not changed:
+ chunk //= 2
+ return steps, message
+
+
+def _seeds() -> list[int]:
+ spec = os.environ.get("COCO_FUZZ_SEEDS", "0-11")
+ if "-" in spec:
+ lo, hi = spec.split("-")
+ return list(range(int(lo), int(hi) + 1))
+ return [int(s) for s in spec.split(",")]
+
+
+_RAW_READER: RawReader | None = None
+
+
+def _raw_reader() -> RawReader | None:
+ global _RAW_READER
+ command = os.environ.get("COCO_FUZZ_LMDB_SERVER")
+ if command and _RAW_READER is None:
+ _RAW_READER = RawReader(command)
+ return _RAW_READER
+
+
[email protected]("seed", _seeds())
+def test_selective_updates_against_a_plain_replay(seed: int) -> None:
+ run_seed(seed, int(os.environ.get("COCO_FUZZ_STEPS", "25")), _raw_reader())
+
+
+if __name__ == "__main__":
+ # python -m tests.core.test_component_selector_fuzz SEEDS STEPS
+ import sys
+ import time
+
+ seeds_spec, n = sys.argv[1], int(sys.argv[2])
+ os.environ["COCO_FUZZ_SEEDS"] = seeds_spec
+ start = time.time()
+ failures: list[str] = []
+ for seed in _seeds():
+ try:
+ run_seed(seed, n, _raw_reader())
+ except Failure as e:
+ failures.append(str(e))
+ print(f"FAIL {e}", flush=True)
+ print(f"{time.time() - start:.0f}s", dict(sorted(STATS.items())), flush=True)
+ print(f"{len(failures)} failing seeds", flush=True)
diff --git a/python/tests/core/test_component_selector_live.py b/python/tests/core/test_component_selector_live.py
new file mode 100644
index 00000000..69b90bb6
--- /dev/null
+++ b/python/tests/core/test_component_selector_live.py
@@ -0,0 +1,659 @@
+"""Sliced execution in live mode: live events, and a running live update beside a slice."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex._internal.live_component import LiveMapSubscriber
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+_source: dict[str, int] = {}
+_runs: list[str] = []
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ GlobalDictTarget.store.sink_exception = False
+ _source.clear()
+ _runs.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _declare(key: str, value: Any) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(str(key), value))
+
+
+async def _live_item(key: str, value: int) -> None:
+ _runs.append(key)
+ _declare(key, value)
+
+
+def _env(request: pytest.FixtureRequest) -> coco.Environment:
+ return common.create_test_env(__file__, suffix=request.node.name)
+
+
+def _app(env: coco.Environment, name: str, main: Any) -> coco.App[Any, Any]:
+ return coco.App(coco.AppConfig(name=f"selector_live_{name}", environment=env), main)
+
+
+class _QueueLive:
+ """`process` mounts `_source`; `process_live` replays events from a queue."""
+
+ queue: asyncio.Queue[tuple[str, str, int]]
+ started: asyncio.Event
+ cancelled: list[str] = []
+
+ async def process(self) -> None:
+ _runs.append("live_process")
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath(key), _live_item, key, value)
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+ _QueueLive.started.set()
+ try:
+ while True:
+ kind, key, value = await _QueueLive.queue.get()
+ subpath = coco.component_subpath(key)
+ if kind == "update":
+ handle = await operator.update(subpath, _live_item, key, value)
+ else:
+ handle = await operator.delete(subpath)
+ await handle.ready()
+ _runs.append(f"event_done:{key}")
+ except asyncio.CancelledError:
+ _QueueLive.cancelled.append("cancelled")
+ raise
+
+
+async def _queue_main() -> None:
+ await coco.mount(coco.component_subpath("live"), _QueueLive)
+ await coco.mount(coco.component_subpath("other"), _live_item, "other", 1)
+
+
+async def _wait_for(cond: Any, timeout: float = 5.0) -> bool:
+ loop = asyncio.get_running_loop()
+ end = loop.time() + timeout
+ while loop.time() < end:
+ if cond():
+ return True
+ await asyncio.sleep(0.02)
+ return bool(cond())
+
+
+async def _start_running_live(
+ request: pytest.FixtureRequest, name: str
+) -> tuple[coco.App[Any, Any], asyncio.Future[Any]]:
+ _QueueLive.queue = asyncio.Queue()
+ _QueueLive.started = asyncio.Event()
+ _QueueLive.cancelled = []
+ _source.update(a=1, b=1)
+ app = _app(_env(request), name, _queue_main)
+ running = asyncio.ensure_future(app.update(live=True).result())
+ await asyncio.wait_for(_QueueLive.started.wait(), timeout=10)
+ return app, running
+
+
+async def _stop(app: coco.App[Any, Any], running: asyncio.Future[Any]) -> None:
+ running.cancel()
+ try:
+ await asyncio.wait_for(running, timeout=10)
+ except (asyncio.CancelledError, Exception):
+ pass
+
+
+# ---------------------------------------------------------------------------
+# 1. A parallel update that runs THROUGH a live component of a running live
+# update. Contract: parallel updates do not interfere.
+# ---------------------------------------------------------------------------
+
+
+ "kind",
+ ["selective_through_live", "selective_preview_through"],
+)
+async def test_running_live_update_survives_a_parallel_selective_update(
+ request: pytest.FixtureRequest, kind: str
+) -> None:
+ app, running = await _start_running_live(request, kind)
+ try:
+ _source.update(a=2)
+ if kind == "selective_through_live":
+ await app.update(component_selector=[coco.ROOT_PATH / "live" / "a"])
+ else:
+ await app.update(
+ preview=True, component_selector=[coco.ROOT_PATH / "live" / "a"]
+ )
+ # The running live update gets a new event: does it still process it?
+ _QueueLive.queue.put_nowait(("update", "late", 7))
+ ok = await _wait_for(lambda: "event_done:late" in _runs, timeout=3)
+ assert ok, (
+ f"running live update lost its live component; cancelled={_QueueLive.cancelled}, "
+ f"running.done()={running.done()}, stored={_stored()}"
+ )
+ finally:
+ await _stop(app, running)
+
+
+async def test_running_live_update_survives_a_parallel_plain_preview(
+ request: pytest.FixtureRequest,
+) -> None:
+ app, running = await _start_running_live(request, "baseline_preview")
+ try:
+ await app.update(preview=True)
+ _QueueLive.queue.put_nowait(("update", "late", 7))
+ ok = await _wait_for(lambda: "event_done:late" in _runs, timeout=3)
+ assert ok, (
+ f"a plain preview ended the live update; cancelled={_QueueLive.cancelled}, "
+ f"running.done()={running.done()}"
+ )
+ finally:
+ await _stop(app, running)
+
+
+# ---------------------------------------------------------------------------
+# 2. Live events under a selective live update.
+# ---------------------------------------------------------------------------
+
+
+async def test_selective_live_events_for_keys_appearing_after_start_and_readd(
+ request: pytest.FixtureRequest,
+) -> None:
+ _QueueLive.queue = asyncio.Queue()
+ _QueueLive.started = asyncio.Event()
+ _source.update(a=1, b=1)
+ app = _app(_env(request), "events_after_start", _queue_main)
+ await app.update()
+ _runs.clear()
+
+ running = asyncio.ensure_future(
+ app.update(
+ live=True,
+ component_selector=[
+ coco.ROOT_PATH / "live" / "a",
+ coco.ROOT_PATH / "live" / "new_sel",
+ ],
+ ).result()
+ )
+ try:
+ await asyncio.wait_for(_QueueLive.started.wait(), timeout=10)
+ q = _QueueLive.queue
+ for ev in [
+ ("update", "new_sel", 1),
+ ("update", "new_unsel", 1),
+ ("delete", "a", 0),
+ ("update", "a", 5), # re-add
+ ("delete", "b", 0), # unselected delete: skipped
+ ("update", "b", 9), # unselected update: skipped
+ ("delete", "new_sel", 0),
+ ("update", "new_sel", 3),
+ ]:
+ q.put_nowait(ev)
+ assert await _wait_for(lambda: _runs.count("event_done:new_sel") == 3)
+ assert _stored() == {"a": 5, "b": 1, "other": 1, "new_sel": 3}
+ assert "new_unsel" not in _runs and "b" not in _runs
+ finally:
+ await _stop(app, running)
+
+ # A plain update catches up and does not lose anything.
+ await app.update()
+ assert _stored() == {"a": 1, "b": 1, "other": 1}
+
+
+async def test_selective_live_coalescing_on_selected_and_skipped_paths(
+ request: pytest.FixtureRequest,
+) -> None:
+ gate = asyncio.Event()
+ handles: dict[str, list[Any]] = {"sel": [], "unsel": []}
+
+ @coco.fn
+ async def slow_item(key: str, value: int) -> None:
+ await gate.wait()
+ _runs.append(f"{key}={value}")
+ _declare(key, value)
+
+ class Live:
+ async def process(self) -> None:
+ pass
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+ for i in range(5):
+ for key in ("sel", "unsel"):
+ handles[key].append(
+ await operator.update(
+ coco.component_subpath(key), slow_item, key, i
+ )
+ )
+ gate.set()
+ for key in ("sel", "unsel"):
+ for h in handles[key]:
+ await h.ready()
+ _runs.append("all_ready")
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), Live)
+
+ app = _app(_env(request), "coalescing", main)
+ running = asyncio.ensure_future(
+ app.update(
+ live=True, component_selector=[coco.ROOT_PATH / "live" / "sel"]
+ ).result()
+ )
+ try:
+ assert await _wait_for(lambda: "all_ready" in _runs)
+ sel_runs = [r for r in _runs if r.startswith("sel=")]
+ assert sel_runs[-1] == "sel=4" and len(sel_runs) <= 3, _runs
+ assert not [r for r in _runs if r.startswith("unsel")]
+ assert _stored() == {"sel": 4}
+ finally:
+ await _stop(app, running)
+
+
+# ---------------------------------------------------------------------------
+# 3. Termination: catch-up and live=True when everything is skipped.
+# ---------------------------------------------------------------------------
+
+
[email protected]("live", [False, True])
+async def test_selective_update_terminates_when_every_live_child_is_skipped(
+ request: pytest.FixtureRequest, live: bool
+) -> None:
+ class Live:
+ async def process(self) -> None:
+ for key in ["a", "b"]:
+ await coco.mount(coco.component_subpath(key), _live_item, key, 1)
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), Live)
+ await coco.mount(coco.component_subpath("live2"), Live)
+
+ app = _app(_env(request), f"terminates_{live}", main)
+ await app.update()
+ for selector in (
+ [coco.ROOT_PATH / "nothing"],
+ [coco.ROOT_PATH / "live" / "nothing"],
+ [],
+ ):
+ handle = app.update(live=live, component_selector=selector)
+ await asyncio.wait_for(handle.result(), timeout=10)
+ assert handle.stats() is not None
+
+
+async def test_watch_and_stats_on_a_selective_handle(
+ request: pytest.FixtureRequest,
+) -> None:
+ @coco.fn
+ async def main() -> None:
+ for key in ["a", "b", "c"]:
+ await coco.mount(coco.component_subpath(key), _live_item, key, 1)
+
+ app = _app(_env(request), "watch_stats", main)
+ await app.update()
+ handle = app.update(component_selector=[coco.ROOT_PATH / "b"])
+ snapshots = []
+ async for snap in handle.watch():
+ snapshots.append(snap)
+ stats = handle.stats()
+ assert snapshots, "watch() yielded nothing"
+ assert stats is not None
+ text = str(stats)
+ # Only one item component ran.
+ assert sorted(_runs) == ["a", "b", "b", "c"], _runs
+ print(text)
+
+
+# ---------------------------------------------------------------------------
+# 4. Committed live state under a selector: a partial scan must not be
+# recorded as a bootstrap (OCI connector pattern, oci_object_storage/_source.py:423-440).
+# ---------------------------------------------------------------------------
+
+_logic_version = ["v1"]
+
+
+class _BootstrapView:
+ """A LiveMapView that skips its startup scan when the stored version matches."""
+
+ def __aiter__(self) -> AsyncIterator[tuple[str, int]]:
+ async def gen() -> AsyncIterator[tuple[str, int]]:
+ for k, v in list(_source.items()):
+ yield k, v
+
+ return gen()
+
+ async def watch(self, subscriber: LiveMapSubscriber[str, int]) -> None:
+ stored = await subscriber.read_committed_state("scan_version")
+ if stored != _logic_version[0]:
+ await subscriber.update_all()
+ await subscriber.mark_ready()
+ if stored != _logic_version[0]:
+ await subscriber.write_committed_state("scan_version", _logic_version[0])
+
+
+async def _versioned_item(value: int, key: str) -> None:
+ _runs.append(key)
+ _declare(key, f"{_logic_version[0]}:{value}")
+
+
+async def _bootstrap_main() -> None:
+ await coco.mount_each( # type: ignore[call-overload]
+ coco.component_subpath("items"),
+ lambda value, key: _versioned_item(value, key),
+ _BootstrapView(),
+ )
+
+
[email protected]("preview", [False, True])
+async def test_selective_run_does_not_record_a_partial_scan_as_bootstrap(
+ request: pytest.FixtureRequest, preview: bool
+) -> None:
+ @coco.fn
+ async def item(value: int) -> None:
+ key = f"k{value}"
+ _runs.append(key)
+ _declare(key, f"{_logic_version[0]}:{value}")
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("items"), item, _BootstrapView())
+
+ _logic_version[0] = "v1"
+ _source.update(k1=1, k2=2, k3=3)
+ app = _app(_env(request), f"bootstrap_{preview}", main)
+ await app.update(live=True)
+ assert _stored() == {"k1": "v1:1", "k2": "v1:2", "k3": "v1:3"}
+
+ # The logic changes. A selective run processes one item.
+ _logic_version[0] = "v2"
+ await app.update(
+ live=True,
+ preview=preview,
+ component_selector=[coco.ROOT_PATH / "items" / "k1"],
+ )
+ # The next plain run must still catch up the rest.
+ await app.update(live=True)
+ assert _stored() == {"k1": "v2:1", "k2": "v2:2", "k3": "v2:3"}
+
+
+# ---------------------------------------------------------------------------
+# 5. auto_refresh, LiveMapFeed / LiveStream style feeds, nested live.
+# ---------------------------------------------------------------------------
+
+
+async def test_auto_refresh_under_a_selector(request: pytest.FixtureRequest) -> None:
+ import datetime
+
+ cycles: list[int] = []
+
+ @coco.fn
+ async def refresh_all() -> None:
+ cycles.append(1)
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath(key), _live_item, key, value)
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(
+ coco.component_subpath("refresh"),
+ coco.auto_refresh(refresh_all, interval=datetime.timedelta(seconds=0.05)),
+ )
+
+ _source.update(a=1, b=1)
+ app = _app(_env(request), "auto_refresh", main)
+ await app.update()
+ _runs.clear()
+ _source.update(a=2, b=2)
+ running = asyncio.ensure_future(
+ app.update(
+ live=True, component_selector=[coco.ROOT_PATH / "refresh" / "a"]
+ ).result()
+ )
+ try:
+ assert await _wait_for(lambda: len(cycles) >= 4)
+ _source.update(a=3, b=3, c=3)
+ assert await _wait_for(lambda: _stored().get("a") == 3)
+ await asyncio.sleep(0.2)
+ assert _stored() == {"a": 3, "b": 1}, _stored()
+ assert "b" not in _runs and "c" not in _runs
+ finally:
+ await _stop(app, running)
+ await app.update()
+ assert _stored() == {"a": 3, "b": 3, "c": 3}
+
+
+class _Feed:
+ """A LiveMapFeed (watch only), like Kafka."""
+
+ events: asyncio.Queue[tuple[str, str, int]]
+
+ async def watch(self, subscriber: LiveMapSubscriber[str, int]) -> None:
+ await subscriber.mark_ready()
+ while True:
+ kind, key, value = await _Feed.events.get()
+ if kind == "update":
+ h = await subscriber.update(key, value)
+ else:
+ h = await subscriber.delete(key)
+ await h.ready()
+ _runs.append(f"feed_done:{key}")
+
+
+async def test_mount_each_over_a_live_map_feed_under_a_selector(
+ request: pytest.FixtureRequest,
+) -> None:
+ @coco.fn
+ async def item(value: int, key_holder: list[str]) -> None:
+ pass
+
+ @coco.fn
+ async def feed_item(value: tuple[str, int]) -> None:
+ _runs.append(value[0])
+ _declare(*value)
+
+ class Feed:
+ async def watch(self, subscriber: LiveMapSubscriber[str, Any]) -> None:
+ await subscriber.mark_ready()
+ while True:
+ kind, key, value = await _Feed.events.get()
+ if kind == "update":
+ h = await subscriber.update(key, (key, value))
+ else:
+ h = await subscriber.delete(key)
+ await h.ready()
+ _runs.append(f"feed_done:{key}")
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(coco.component_subpath("feed"), feed_item, Feed()) # type: ignore[call-overload]
+
+ _Feed.events = asyncio.Queue()
+ app = _app(_env(request), "feed", main)
+ running = asyncio.ensure_future(app.update(live=True).result())
+ for k in ["a", "b"]:
+ _Feed.events.put_nowait(("update", k, 1))
+ assert await _wait_for(lambda: "feed_done:b" in _runs)
+ await _stop(app, running)
+ _runs.clear()
+
+ _Feed.events = asyncio.Queue()
+ running = asyncio.ensure_future(
+ app.update(
+ live=True, component_selector=[coco.ROOT_PATH / "feed" / "a"]
+ ).result()
+ )
+ try:
+ for ev in [
+ ("update", "a", 2),
+ ("update", "b", 2),
+ ("delete", "b", 0),
+ ("update", "c", 2),
+ ]:
+ _Feed.events.put_nowait(ev)
+ assert await _wait_for(lambda: "feed_done:c" in _runs)
+ assert _stored() == {"a": 2, "b": 1}
+ finally:
+ await _stop(app, running)
+
+
+async def test_one_shot_update_that_selects_a_running_live_component_runs_beside_it(
+ request: pytest.FixtureRequest,
+) -> None:
+ # As a plain one-shot update does: the live update keeps running.
+ app, running = await _start_running_live(request, "beside")
+ try:
+ _source.update(a=2)
+ await app.update(component_selector=[coco.ROOT_PATH / "live"])
+ assert _stored()["a"] == 2
+ _QueueLive.queue.put_nowait(("update", "late", 3))
+ assert await _wait_for(lambda: "event_done:late" in _runs)
+ assert _stored()["late"] == 3
+ assert not running.done()
+ assert _QueueLive.cancelled == []
+ finally:
+ await _stop(app, running)
+
+
+async def test_live_update_that_selects_a_running_live_component_replaces_it(
+ request: pytest.FixtureRequest,
+) -> None:
+ # As a second plain live update does: the running instance is cancelled,
+ # and the new one handles the events from then on.
+ app, running = await _start_running_live(request, "replaced")
+ _QueueLive.started = asyncio.Event()
+ running2 = asyncio.ensure_future(
+ app.update(live=True, component_selector=[coco.ROOT_PATH / "live"]).result()
+ )
+ try:
+ await asyncio.wait_for(_QueueLive.started.wait(), 10)
+ assert _QueueLive.cancelled == ["cancelled"]
+ _QueueLive.queue.put_nowait(("update", "late", 3))
+ assert await _wait_for(lambda: "event_done:late" in _runs)
+ assert _stored()["late"] == 3
+ finally:
+ await _stop(app, running2)
+ await _stop(app, running)
+
+
+async def test_update_through_a_live_component_queues_behind_its_running_cycle(
+ request: pytest.FixtureRequest,
+) -> None:
+ gate = asyncio.Event()
+
+ @coco.fn
+ async def slow(key: str, value: int) -> None:
+ if key == "slow":
+ await gate.wait()
+ _runs.append(key)
+ _declare(key, value)
+
+ class Live:
+ async def process(self) -> None:
+ for key in ["a", "slow"]:
+ await coco.mount(coco.component_subpath(key), slow, key, 1)
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+ await asyncio.Event().wait()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("live"), Live)
+
+ app = _app(_env(request), "queues_behind_cycle", main)
+ running = asyncio.ensure_future(app.update(live=True).result())
+ await asyncio.sleep(0.3) # The running cycle is blocked on "slow".
+ selective = asyncio.ensure_future(
+ app.update(component_selector=[coco.ROOT_PATH / "live" / "a"]).result()
+ )
+ await asyncio.sleep(0.3)
+ assert not selective.done()
+
+ gate.set()
+ await asyncio.wait_for(selective, 20)
+ assert not running.done()
+ assert _stored() == {"a": 1, "slow": 1}
+ await _stop(app, running)
+
+
+_constructed: list[str] = []
+
+
+class _SideEffectLive:
+ def __init__(self, name: str) -> None:
+ _constructed.append(name)
+
+ async def process(self) -> None:
+ pass
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+
+
+async def test_unselected_live_component_constructor_is_not_run(
+ request: pytest.FixtureRequest,
+) -> None:
+ class Outer:
+ async def process(self) -> None:
+ pass
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ for n in ["inner_sel", "inner_unsel"]:
+ h = await operator.update(coco.component_subpath(n), _SideEffectLive, n)
+ await h.ready()
+ await operator.mark_ready()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("sel"), _SideEffectLive, "sel")
+ await coco.mount(coco.component_subpath("unsel"), _SideEffectLive, "unsel")
+ await coco.mount(coco.component_subpath("outer"), Outer)
+
+ app = _app(_env(request), "ctor", main)
+ await app.update()
+ _constructed.clear()
+ await app.update(
+ component_selector=[
+ coco.ROOT_PATH / "sel",
+ coco.ROOT_PATH / "outer" / "inner_sel",
+ ]
+ )
+ assert _constructed == ["sel", "inner_sel"], _constructed
diff --git a/python/tests/core/test_component_selector_panel.py b/python/tests/core/test_component_selector_panel.py
new file mode 100644
index 00000000..3afe26e9
--- /dev/null
+++ b/python/tests/core/test_component_selector_panel.py
@@ -0,0 +1,687 @@
+"""CocoInsight panel flow, end to end, with random source edits.
+
+Each iteration: 1-3 random edits; list the app's paths with ``list_stable_paths``;
+pick a page of 10 or 50 paths; preview the page; update the page with the same
+selector. Checked every iteration:
+
+- Preview and update agree: the same error, or the same actions (the update's
+ actions are recorded at the sinks). Extra update actions that are deletes of
+ target states owned by a page component no longer mounted are counted apart
+ (the docs say a preview does not plan those).
+- Unselected components are untouched: every LMDB row whose subject is outside
+ the page (not covered, not an ancestor of a page path, not the root's
+ use_mount child) stays byte for byte, and so does every external target
+ state such a component owns. A takeover by a page component is the one
+ allowed edit (old owner's tracking record and the memos up its chain).
+- Every 4th iteration, a plain update; afterwards external target states and
+ owners equal those of a replay app that only ever ran plain updates.
+
+Longer runs: set ``COCO_PANEL_SEEDS`` (for example ``0-99``) and
+``COCO_PANEL_ITERS``, and ``COCO_FUZZ_LMDB_SERVER`` as for
+``test_component_selector_fuzz.py`` to compare LMDB rows byte for byte.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import collections
+import os
+import random
+import threading
+from dataclasses import dataclass, field
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+import cocoindex.inspect as coco_inspect
+from cocoindex._internal.inspect_api import list_stable_paths
+
+from tests import common
+from tests.common.environment import get_env_db_path
+from tests.common.target_states import DictsTargetStateStore, DictTargetStateStore
+from tests.core.test_component_selector_fuzz import RawReader, classify_row
+
+SIDES = ("sut", "replay")
+_lock = threading.Lock()
+# Actions the sinks applied, per side, while recording.
+APPLIED: dict[str, list[tuple[Any, ...]] | None] = {s: None for s in SIDES}
+
+
+def _norm_value(v: Any) -> Any:
+ if coco.is_non_existence(v):
+ return None
+ return (v.data, tuple(sorted(map(repr, v.prev))), v.prev_may_be_missing)
+
+
+class RecFlat(DictTargetStateStore):
+ def __init__(self, side: str, tag: str) -> None:
+ self.side, self.tag = side, tag
+ super().__init__()
+
+ def _sink(self, context_provider: Any, actions: Any, /) -> None:
+ if self.sink_exception:
+ raise ValueError("injected sink exception")
+ with _lock:
+ rec = APPLIED[self.side]
+ for key, value in actions:
+ if rec is not None:
+ rec.append((self.tag, key, _norm_value(value)))
+ if coco.is_non_existence(value):
+ self.data.pop(key, None)
+ else:
+ self.data[key] = value
+
+
+class RecCont(DictsTargetStateStore):
+ def __init__(self, side: str) -> None:
+ self.side = side
+ super().__init__()
+
+ def _child_handler(self, context_provider: Any, action: Any, /) -> Any:
+ with self._lock:
+ existing = self._stores.get(action.name)
+ if existing is not None and not action.destructive:
+ return existing
+ staged = self._staged.get(action.name)
+ if staged is None:
+ staged = RecFlat(self.side, f"row:{action.name}")
+ self._staged[action.name] = staged
+ return staged
+
+ def _new_store(self, name: str) -> DictTargetStateStore:
+ staged = self._staged.pop(name, None)
+ return staged if staged is not None else RecFlat(self.side, f"row:{name}")
+
+ def _sink(self, context_provider: Any, actions: Any, /) -> None:
+ if self.sink_exception:
+ raise ValueError("injected sink exception")
+ with self._lock:
+ rec = APPLIED[self.side]
+ for name, exists, action, destructive in actions:
+ if rec is not None:
+ rec.append(("cont", name, (exists, action, destructive)))
+ if action == "insert" or (
+ action == "upsert" and (destructive or name not in self._stores)
+ ):
+ self._stores[name] = self._new_store(name)
+ elif action == "delete":
+ self._stores.pop(name, None)
+
+
+FLAT = {s: RecFlat(s, "flat") for s in SIDES}
+FLAT_P = {
+ s: coco.register_root_target_states_provider(f"panel_flat/{s}", FLAT[s])
+ for s in SIDES
+}
+CONT = {s: RecCont(s) for s in SIDES}
+CONT_P = {
+ s: coco.register_root_target_states_provider(f"panel_cont/{s}", CONT[s])
+ for s in SIDES
+}
+
+
+def _pv(action: Any) -> tuple[Any, ...]:
+ """A preview action, normalized as the sinks record theirs."""
+ if isinstance(action, tuple) and len(action) == 4 and isinstance(action[1], bool):
+ name, exists, act, destructive = action
+ return ("cont", name, (exists, act, destructive))
+ key, value = action
+ tag = "flat" if not str(key).startswith("row|") else f"row:{CONT_NAME}"
+ return (tag, key, _norm_value(value))
+
+
+CONT_NAME = "C"
+
+# ---------------------------------------------------------------------------
+# The app
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class Source:
+ files: dict[Any, tuple[int, int]] = field(
+ default_factory=dict
+ ) # key->(content, nchunks)
+ archive: dict[Any, int] = field(default_factory=dict)
+ grp: dict[str, int] = field(default_factory=dict)
+ um: dict[str, int] = field(default_factory=dict)
+ version: int = 0
+
+
+SRC = Source()
+EXT: dict[str, int] = {}
+
+
+def _kr(k: Any) -> str:
+ return f"{type(k).__name__}:{k}"
+
+
+def _flat(side: str, key: str, value: Any) -> None:
+ coco.declare_target_state(FLAT_P[side].target_state(key, value))
+
+
+def _validate_ext(key: str, prev: int) -> coco.MemoStateOutcome:
+ cur = EXT.get(key, 0)
+ return coco.MemoStateOutcome(state=cur, memo_valid=cur == prev)
+
+
+EXT_DEP = coco.DataDep("panel-ext", validate=_validate_ext)
+
+
+async def chunk_fn(side: str, k: Any, i: int, content: int, provider: Any) -> None:
+ coco.declare_target_state(
+ provider.target_state(f"row|{_kr(k)}#{i}", content * 10 + i)
+ )
+ _flat(side, f"c|{_kr(k)}#{i}", content + i)
+
+
+async def _file_body(
+ entry: tuple[Any, tuple[int, int]], side: str, provider: Any
+) -> None:
+ k, (content, n) = entry
+ e = EXT.get(_kr(k), 0)
+ coco.use_data_dep(EXT_DEP, key=_kr(k), state=e)
+ _flat(side, f"f|{_kr(k)}", (content, e))
+ for i in range(n):
+ await coco.mount(
+ coco.component_subpath(i), chunk_fn, side, k, i, content, provider
+ )
+
+
+_FILE_FNS: dict[int, Any] = {}
+
+
+def file_fn(version: int) -> Any:
+ with _lock:
+ if version not in _FILE_FNS:
+ _FILE_FNS[version] = coco.fn(memo=True, version=version)(_file_body)
+ return _FILE_FNS[version]
+
+
+async def archive_fn(entry: tuple[Any, int], side: str) -> None:
+ k, v = entry
+ # The same key as a file: moving a file to the archive is a takeover.
+ _flat(side, f"f|{_kr(k)}", ("archived", v))
+
+
+async def grp_leaf(side: str, k: str, v: int) -> None:
+ _flat(side, f"g|{k}", v)
+
+
+async def um_child(side: str, k: str, v: int) -> None:
+ _flat(side, f"u|{k}", v)
+
+
+async def um_fn(side: str, items: dict[str, int]) -> int:
+ _flat(side, "um|n", len(items))
+ for k, v in sorted(items.items()):
+ await coco.mount(coco.component_subpath(k), um_child, side, k, v)
+ return len(items)
+
+
+def declare_cont(side: str) -> coco.PendingTargetStateProvider[str, None]:
+ return coco.declare_target_state_with_child(
+ CONT_P[side].target_state(CONT_NAME, None)
+ )
+
+
+async def app_main(side: str) -> None:
+ provider = await coco.use_mount(coco.component_subpath("setup"), declare_cont, side)
+ n = await coco.use_mount(coco.component_subpath("um"), um_fn, side, dict(SRC.um))
+ _flat(side, "root|n", (len(SRC.files), n))
+ await coco.mount_each(
+ coco.component_subpath("files"),
+ file_fn(SRC.version),
+ sorted(((k, (k, v)) for k, v in SRC.files.items()), key=repr),
+ side,
+ provider,
+ )
+ await coco.mount_each(
+ coco.component_subpath("archive"),
+ archive_fn,
+ sorted(((k, (k, v)) for k, v in SRC.archive.items()), key=repr),
+ side,
+ )
+ for k, v in sorted(SRC.grp.items()):
+ await coco.mount(coco.component_subpath("grp", "sub", k), grp_leaf, side, k, v)
+
+
+# ---------------------------------------------------------------------------
+# Observing
+# ---------------------------------------------------------------------------
+
+Path = tuple[Any, ...]
+
+
+def _tuple(p: coco.StablePath) -> Path:
+ return tuple(p.parts())
+
+
+def _sp(p: Path) -> coco.StablePath:
+ out = coco.ROOT_PATH
+ for k in p:
+ out = out / k
+ return out
+
+
+def external(side: str) -> dict[tuple[str, ...], Any]:
+ out: dict[tuple[str, ...], Any] = {}
+ for k, v in FLAT[side].data.items():
+ out[("flat", k)] = v.data
+ for name, store in CONT[side].data.items():
+ out[("cont", name)] = None
+ for k, v in store.items():
+ out[("row", k)] = v.data
+ return out
+
+
+def owners(app: coco.App[Any, Any]) -> dict[tuple[str, ...], Path]:
+ async def collect() -> dict[tuple[str, ...], Path]:
+ out: dict[tuple[str, ...], Path] = {}
+ async for entry in coco_inspect.iter_target_states(app):
+ assert not entry.dangling, entry.readable_path
+ segs = [
+ s[1:-1] if s.startswith('"') else s for s in entry.readable_segments
+ ]
+ kind = "flat" if "panel_flat" in segs[0] else "cont"
+ if kind == "cont" and len(segs) > 2:
+ key: tuple[str, ...] = ("row", segs[-1])
+ else:
+ key = (kind, segs[-1])
+ out[key] = _tuple(coco.StablePath(entry.owner_component_path))
+ return out
+
+ return asyncio.run(collect())
+
+
+def _is_prefix(p: Path, q: Path) -> bool:
+ return len(p) <= len(q) and all(type(a) is type(b) and a == b for a, b in zip(p, q))
+
+
+class Failure(AssertionError):
+ pass
+
+
+# Component failures the engine logs and swallows (background mounts). Any
+# not injected is a failure of the seed.
+ERRORS: list[str] = []
+
+
+def _record_error(exc: BaseException, ctx: Any) -> None:
+ ERRORS.append(f"{ctx.stable_path}: {exc!r}")
+
+
+STATS: collections.Counter[str] = collections.Counter()
+
+
+@dataclass
+class Snap:
+ raw: dict[bytes, bytes] | None
+ ext: dict[tuple[str, ...], Any]
+ own: dict[tuple[str, ...], Path]
+
+
+class Panel:
+ def __init__(self, seed: int, raw: RawReader | None) -> None:
+ self.seed = seed
+ self.rng = random.Random(seed)
+ suffix = f"p{seed}_{os.getpid()}"
+ self.env = common.create_test_env(
+ __file__, suffix=suffix, exception_handler=_record_error
+ )
+ self.env_dir = str(
+ get_env_db_path(f"core__test_component_selector_panel__{suffix}") / "mdb"
+ )
+ self.raw = raw
+ self.apps = {
+ s: coco.App(
+ coco.AppConfig(name=f"panel_{s}", environment=self.env), app_main, s
+ )
+ for s in SIDES
+ }
+
+ def snap(self) -> Snap:
+ raw = self.raw.rows(self.env_dir, "panel_sut") if self.raw else None
+ return Snap(raw, external("sut"), owners(self.apps["sut"]))
+
+ # -- edits --------------------------------------------------------------
+ def edit(self) -> str:
+ r = self.rng.random()
+ keys = list(SRC.files)
+ pool: list[Any] = ["a", "b", "c", "d", "e", 1, 2, 3, "1", "x y"] + [
+ f"k{i}" for i in range(20)
+ ]
+ if r < 0.25 and keys:
+ k = self.rng.choice(keys)
+ c, n = SRC.files[k]
+ SRC.files[k] = (self.rng.randint(0, 9), n)
+ return f"edit {k!r}"
+ if r < 0.38:
+ k = self.rng.choice(pool)
+ if k not in SRC.archive:
+ SRC.files[k] = (self.rng.randint(0, 9), self.rng.randint(0, 3))
+ return f"add {k!r}"
+ if r < 0.50 and keys:
+ k = self.rng.choice(keys)
+ del SRC.files[k]
+ return f"delete {k!r}"
+ if r < 0.58 and keys:
+ k = self.rng.choice(keys)
+ c, n = SRC.files[k]
+ SRC.files[k] = (c, self.rng.randint(0, 3))
+ return f"rechunk {k!r}"
+ if r < 0.66:
+ if keys and self.rng.random() < 0.6:
+ k = self.rng.choice(keys)
+ c, _ = SRC.files.pop(k)
+ SRC.archive[k] = c
+ return f"archive {k!r}"
+ if SRC.archive:
+ k = self.rng.choice(list(SRC.archive))
+ SRC.files[k] = (SRC.archive.pop(k), 1)
+ return f"unarchive {k!r}"
+ if r < 0.72 and keys:
+ k = self.rng.choice(keys)
+ EXT[_kr(k)] = self.rng.randint(0, 3)
+ return f"ext {k!r}"
+ if r < 0.75:
+ SRC.version += 1
+ return "bump file_fn version"
+ if r < 0.87:
+ k = self.rng.choice(["p", "q", "r", "s"])
+ if k in SRC.grp and self.rng.random() < 0.5:
+ del SRC.grp[k]
+ return f"grp del {k}"
+ SRC.grp[k] = self.rng.randint(0, 9)
+ return f"grp set {k}"
+ k = self.rng.choice(["m", "n", "o"])
+ if k in SRC.um and self.rng.random() < 0.5:
+ del SRC.um[k]
+ return f"um del {k}"
+ SRC.um[k] = self.rng.randint(0, 9)
+ return f"um set {k}"
+
+ # -- one update ---------------------------------------------------------
+ def run(self, side: str, **kw: Any) -> tuple[Any, Exception | None]:
+ try:
+ return self.apps[side].update_blocking(**kw), None
+ except Exception as e: # noqa: BLE001
+ return None, e
+
+ def recorded(self, side: str, **kw: Any) -> tuple[Any, Exception | None, list[Any]]:
+ APPLIED[side] = []
+ try:
+ out, err = self.run(side, **kw)
+ finally:
+ rec, APPLIED[side] = APPLIED[side], None
+ return out, err, rec or []
+
+
+def _uncovered(page: list[Path], path: Path) -> bool:
+ """True for a path the page update must leave alone: not covered, not an
+ ancestor of a page path (the root included), not under the root's
+ use_mount children."""
+ if any(_is_prefix(p, path) for p in page):
+ return False
+ if any(_is_prefix(path, p) for p in page):
+ return False
+ if path in (("setup",), ("um",)):
+ return False
+ return True
+
+
+def check_untouched(page: list[Path], before: Snap, after: Snap) -> None:
+ taken_from = {
+ before.own[k]
+ for k in before.own
+ if k in after.own
+ and after.own[k] != before.own[k]
+ and _uncovered(page, before.own[k])
+ and not _uncovered(page, after.own[k])
+ }
+ if taken_from:
+ STATS["takeovers from an unselected owner"] += 1
+ if before.raw is not None and after.raw is not None:
+ for key in sorted(set(before.raw) | set(after.raw)):
+ b, a = before.raw.get(key), after.raw.get(key)
+ if a == b:
+ if b is not None:
+ row = classify_row(key, b)
+ if row.subject is not None and _uncovered(page, row.subject):
+ STATS["unselected rows byte-compared"] += 1
+ continue
+ row = classify_row(key, b if b is not None else a) # type: ignore[arg-type]
+ if row.kind == "global" or row.subject is None:
+ continue
+ if not _uncovered(page, row.subject):
+ continue
+ if row.entry == "0x40" and row.subject in taken_from:
+ continue
+ if row.entry == "0x20" and any(
+ _is_prefix(row.subject, t) for t in taken_from
+ ):
+ continue
+ if row.kind == "target_state" and a is not None:
+ new_owner = classify_row(key, a).subject
+ if (
+ row.subject in taken_from
+ and new_owner is not None
+ and not _uncovered(page, new_owner)
+ ):
+ continue
+ change = "added" if b is None else "removed" if a is None else "changed"
+ raise Failure(f"LMDB row {row.entry} of unselected {row.subject} {change}")
+ for k in sorted(set(before.ext) | set(after.ext), key=repr):
+ if before.ext.get(k) == after.ext.get(k) and before.own.get(k) == after.own.get(
+ k
+ ):
+ continue
+ ob, oa = before.own.get(k), after.own.get(k)
+ if (
+ ob is not None
+ and ob in taken_from
+ and oa is not None
+ and not _uncovered(page, oa)
+ ):
+ continue
+ if any(o is not None and _uncovered(page, o) for o in (ob, oa)):
+ raise Failure(
+ f"external {k} of unselected owner {ob}->{oa}: "
+ f"{before.ext.get(k)} -> {after.ext.get(k)}"
+ )
+
+
+def compare_actions(
+ panel: Panel,
+ page: list[Path],
+ before: Snap,
+ preview: Any,
+ perr: Exception | None,
+ uerr: Exception | None,
+ applied: list[Any],
+) -> None:
+ if (perr is None) != (uerr is None):
+ raise Failure(f"preview error {perr!r} vs update error {uerr!r}")
+ if perr is not None:
+ if type(perr) is not type(uerr) or str(perr) != str(uerr):
+ raise Failure(f"different errors: {perr!r} vs {uerr!r}")
+ STATS["page refused alike in preview and update"] += 1
+ return
+ p = collections.Counter(_pv(a) for a in preview)
+ u = collections.Counter(applied)
+ extra_u = u - p
+ extra_p = p - u
+ # Extra update actions allowed: deletes of target states whose owner (before)
+ # is a page component that the update deleted (no longer mounted).
+ gone_deletes = 0
+ for action, n in list(extra_u.items()):
+ tag, key, value = action
+ ext_key = (
+ ("flat", key)
+ if tag == "flat"
+ else ("row", key)
+ if tag.startswith("row")
+ else ("cont", key)
+ )
+ owner = before.own.get(ext_key)
+ if value is None and owner is not None and not _uncovered(page, owner):
+ gone_deletes += n
+ del extra_u[action]
+ if gone_deletes:
+ STATS["update deletes a preview did not plan (gone components)"] += gone_deletes
+ if extra_u or extra_p:
+ raise Failure(
+ f"preview/update disagree: only in update {dict(extra_u)}, "
+ f"only in preview {dict(extra_p)}"
+ )
+ STATS["pages where preview == update"] += 1
+
+
+def compare_with_replay(panel: Panel, where: str) -> None:
+ s_ext, r_ext = external("sut"), external("replay")
+ s_own, r_own = owners(panel.apps["sut"]), owners(panel.apps["replay"])
+ if s_ext != r_ext:
+ diff = {
+ k: (s_ext.get(k), r_ext.get(k))
+ for k in set(s_ext) | set(r_ext)
+ if s_ext.get(k) != r_ext.get(k)
+ }
+ raise Failure(f"{where}: external sut != replay: {diff}")
+ if s_own != r_own:
+ diff = {
+ k: (s_own.get(k), r_own.get(k))
+ for k in set(s_own) | set(r_own)
+ if s_own.get(k) != r_own.get(k)
+ }
+ raise Failure(f"{where}: owners sut != replay: {diff}")
+ STATS["plain updates equal to replay"] += 1
+
+
+def run_panel(seed: int, iters: int, raw: RawReader | None) -> list[str]:
+ global SRC
+ SRC = Source()
+ EXT.clear()
+ ERRORS.clear()
+ for s in SIDES:
+ FLAT[s].data.clear()
+ CONT[s].clear()
+ panel = Panel(seed, raw)
+ log: list[str] = []
+ rng = panel.rng
+ try:
+ pool: list[Any] = ["a", "b", 1, 2, "1", "c"] + [f"k{i}" for i in range(20)]
+ for k in rng.sample(pool, rng.randint(4, 22)):
+ SRC.files[k] = (rng.randint(0, 9), rng.randint(0, 3))
+ SRC.grp.update(p=1)
+ SRC.um.update(m=1)
+ for s in SIDES:
+ _, err = panel.run(s)
+ if err:
+ raise Failure(f"initial update failed: {err!r}")
+ for it in range(iters):
+ for _ in range(rng.randint(1, 3)):
+ log.append(panel.edit())
+ destructive = rng.random() < 0.06
+ if it % 4 == 3:
+ log.append(f"[{it}] plain{' destructive' if destructive else ''}")
+ for s in SIDES:
+ CONT[s].child_invalidation = "destructive" if destructive else None
+ _, err = panel.run(s)
+ CONT[s].child_invalidation = None
+ if err:
+ raise Failure(f"[{it}] plain update of {s} failed: {err!r}")
+ if ERRORS:
+ raise Failure(f"[{it}] component errors: {ERRORS[:3]}")
+ compare_with_replay(panel, f"[{it}]")
+ continue
+ paths = sorted(
+ (_tuple(p) for p in asyncio.run(list_stable_paths(panel.apps["sut"]))),
+ key=repr,
+ )
+ paths = [p for p in paths if p]
+ size = rng.choice([10, 50])
+ pages = max(1, (len(paths) + size - 1) // size)
+ pi = rng.randrange(pages)
+ page = paths[pi * size : (pi + 1) * size]
+ STATS[f"page size {size}"] += 1
+ log.append(
+ f"[{it}] page {pi}/{pages} size {size}: {page}{' destructive' if destructive else ''}"
+ )
+ sel = [_sp(p) for p in page]
+ CONT["sut"].child_invalidation = "destructive" if destructive else None
+ try:
+ before = panel.snap()
+ preview, perr = panel.run("sut", component_selector=sel, preview=True)
+ mid = panel.snap()
+ if mid.raw != before.raw or mid.ext != before.ext:
+ raise Failure(f"[{it}] preview changed state")
+ _, uerr, applied = panel.recorded("sut", component_selector=sel)
+ finally:
+ CONT["sut"].child_invalidation = None
+ after = panel.snap()
+ if uerr is not None and "A full update is needed" not in str(uerr):
+ raise Failure(f"[{it}] page update failed: {uerr!r}")
+ if ERRORS:
+ raise Failure(f"[{it}] component errors: {ERRORS[:3]}")
+ compare_actions(panel, page, before, preview, perr, uerr, applied)
+ check_untouched(page, before, after)
+ # The end: one plain update converges.
+ for s in SIDES:
+ _, err = panel.run(s)
+ if err:
+ raise Failure(f"final plain update of {s} failed: {err!r}")
+ compare_with_replay(panel, "final")
+ STATS["seeds passed"] += 1
+ return log
+ except Failure as e:
+ raise Failure(f"seed {seed}: {e}\nlog:\n" + "\n".join(log[-25:])) from None
+ finally:
+ panel.env.close()
+
+
+_RAW: RawReader | None = None
+
+
+def _raw() -> RawReader | None:
+ global _RAW
+ cmd = os.environ.get("COCO_FUZZ_LMDB_SERVER")
+ if cmd and _RAW is None:
+ _RAW = RawReader(cmd)
+ return _RAW
+
+
+def _seeds() -> list[int]:
+ spec = os.environ.get("COCO_PANEL_SEEDS", "0-3")
+ lo, _, hi = spec.partition("-")
+ return list(range(int(lo), int(hi or lo) + 1))
+
+
[email protected]("seed", _seeds())
+def test_panel_flow(seed: int) -> None:
+ run_panel(seed, int(os.environ.get("COCO_PANEL_ITERS", "20")), _raw())
+
+
+if __name__ == "__main__":
+ import sys
+ import time
+
+ os.environ["COCO_PANEL_SEEDS"] = sys.argv[1]
+ iters = int(sys.argv[2])
+ t = time.time()
+ fails: list[str] = []
+ for seed in _seeds():
+ try:
+ run_panel(seed, iters, _raw())
+ except Failure as e:
+ fails.append(str(e))
+ print(f"FAIL {e}", flush=True)
+ print(f"{time.time() - t:.0f}s", dict(sorted(STATS.items())), flush=True)
+ print(f"{len(fails)} failing seeds", flush=True)
diff --git a/python/tests/core/test_component_selector_pushdown.py b/python/tests/core/test_component_selector_pushdown.py
new file mode 100644
index 00000000..5afb59f3
--- /dev/null
+++ b/python/tests/core/test_component_selector_pushdown.py
@@ -0,0 +1,318 @@
+"""Source pushdown for sliced execution: under ``component_selector``,
+``mount_each`` reads only the keys the update may run. A source that reads by
+key (``__coco_items_for_keys__``) is asked for just those keys, and a
+``mount_each`` whose path the selector leaves out reads nothing.
+"""
+
+from __future__ import annotations
+
+import pathlib
+import pickle
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex.connectors import localfs
+from cocoindex.resources.file import PatternFilePathMatcher
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+coco_env = common.create_test_env(__file__)
+
+_source: dict[Any, str] = {}
+_runs: list[str] = []
+_reads: list[str] = []
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ _source.clear()
+ _runs.clear()
+ _reads.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+class _Items:
+ """Items of `_source` that record how they are read."""
+
+ def __aiter__(self) -> AsyncIterator[tuple[Any, str]]:
+ _reads.append("list")
+ return self._all()
+
+ async def _all(self) -> AsyncIterator[tuple[Any, str]]:
+ for key, value in list(_source.items()):
+ yield key, value
+
+ async def __coco_items_for_keys__(
+ self, keys: list[Any]
+ ) -> AsyncIterator[tuple[Any, str]]:
+ _reads.append(f"keys {sorted(map(str, keys))}")
+ for key in keys:
+ if key in _source:
+ yield key, _source[key]
+
+
+class _ListedOnly:
+ """Items that can only be listed."""
+
+ def __aiter__(self) -> AsyncIterator[tuple[Any, str]]:
+ _reads.append("list")
+ return _Items()._all()
+
+
+async def _item(value: str, prefix: str) -> None:
+ _runs.append(f"{prefix}{value}")
+ coco.declare_target_state(GlobalDictTarget.target_state(f"{prefix}{value}", value))
+
+
+async def _main(items_factory: Any) -> None:
+ await coco.mount_each(coco.component_subpath("items"), _item, items_factory(), "")
+ await coco.mount(coco.component_subpath("other"), _item, "o", "other:")
+
+
+def _app(name: str, items_factory: Any = _Items) -> coco.App[Any, Any]:
+ return coco.App(
+ coco.AppConfig(name=f"test_pushdown_{name}", environment=coco_env),
+ _main,
+ items_factory,
+ )
+
+
+def _path(*parts: Any) -> coco.StablePath:
+ path = coco.ROOT_PATH
+ for part in parts:
+ path = path / part
+ return path
+
+
+def test_selected_keys_are_read_by_key_without_listing() -> None:
+ app = _app("by_key")
+ _source.update({"a": "a1", "b": "b1", "c": "c1"})
+ app.update_blocking()
+ assert _reads == ["list"]
+ _source.update({"a": "a2", "b": "b2", "c": "c2"})
+ _reads.clear()
+ _runs.clear()
+
+ app.update_blocking(component_selector=[_path("items", "a"), _path("items", "c")])
+
+ assert _reads == ["keys ['a', 'c']"]
+ assert sorted(_runs) == ["a2", "c2"]
+ assert _stored() == {"a2": "a2", "b1": "b1", "c2": "c2", "other:o": "o"}
+
+
+def test_a_selected_key_the_source_no_longer_holds_is_deleted() -> None:
+ app = _app("gone")
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+ del _source["a"]
+ del _source["b"]
+ _reads.clear()
+
+ app.update_blocking(component_selector=[_path("items", "a")])
+
+ assert _reads == ["keys ['a']"]
+ assert _stored() == {"b1": "b1", "other:o": "o"}
+ # The next plain update catches up with what the selector left out.
+ app.update_blocking()
+ assert _stored() == {"other:o": "o"}
+
+
+def test_a_selected_path_below_an_item_reads_that_item() -> None:
+ app = _app("deeper")
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+ _source["a"] = "a2"
+ _reads.clear()
+
+ app.update_blocking(component_selector=[_path("items", "a", "chunk", 3)])
+
+ assert _reads == ["keys ['a']"]
+ assert _stored() == {"a2": "a2", "b1": "b1", "other:o": "o"}
+
+
+def test_a_mount_each_the_selector_leaves_out_reads_nothing() -> None:
+ for name, factory in [("left_out", _Items), ("left_out_listed", _ListedOnly)]:
+ GlobalDictTarget.store.clear()
+ _source.clear()
+ app = _app(name, factory)
+ _source.update({"a": "a1"})
+ app.update_blocking()
+ _source["a"] = "a2"
+ _reads.clear()
+ _runs.clear()
+
+ app.update_blocking(component_selector=[_path("other")])
+
+ assert _reads == []
+ assert _runs == ["other:o"]
+ assert _stored() == {"a1": "a1", "other:o": "o"}
+ app.update_blocking()
+ assert _stored() == {"a2": "a2", "other:o": "o"}
+
+
+def test_a_selected_mount_each_lists_its_source() -> None:
+ app = _app("whole")
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+ _source.update({"a": "a2", "b": "b2", "c": "c2"})
+ _reads.clear()
+
+ app.update_blocking(component_selector=[_path("items")])
+
+ assert _reads == ["list"]
+ assert _stored() == {"a2": "a2", "b2": "b2", "c2": "c2", "other:o": "o"}
+
+
+def test_a_source_that_only_lists_is_listed_and_filtered() -> None:
+ app = _app("listed", _ListedOnly)
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+ _source.update({"a": "a2", "b": "b2"})
+ _reads.clear()
+
+ app.update_blocking(component_selector=[_path("items", "a")])
+
+ assert _reads == ["list"]
+ assert _stored() == {"a2": "a2", "b1": "b1", "other:o": "o"}
+
+
+def test_a_preview_reads_by_key_too() -> None:
+ app = _app("preview")
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+ _source.update({"a": "a2", "b": "b2"})
+ _reads.clear()
+
+ actions = app.update_blocking(
+ component_selector=[_path("items", "b")], preview=True
+ )
+
+ assert _reads == ["keys ['b']"]
+ assert {key for key, _ in actions} == {"b1", "b2"}
+ assert _stored() == {"a1": "a1", "b1": "b1", "other:o": "o"}
+
+
+# --- localfs ---------------------------------------------------------------
+
+
+async def _file(file: localfs.File, root: pathlib.Path) -> None:
+ key = file.file_path.path.relative_to(root).as_posix()
+ _runs.append(key)
+ coco.declare_target_state(
+ GlobalDictTarget.target_state(key, await file.read_text())
+ )
+
+
+async def _files_main(root: pathlib.Path) -> None:
+ files = localfs.walk_dir(
+ root,
+ recursive=True,
+ path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
+ )
+ await coco.mount_each(coco.component_subpath("files"), _file, files.items(), root)
+
+
+def test_localfs_reads_only_the_selected_files(tmp_path: pathlib.Path) -> None:
+ (tmp_path / "docs").mkdir()
+ (tmp_path / "a.md").write_text("a1")
+ (tmp_path / "docs" / "b.md").write_text("b1")
+ (tmp_path / "docs" / "c.md").write_text("c1")
+ app = coco.App(
+ coco.AppConfig(name="test_pushdown_localfs", environment=coco_env),
+ _files_main,
+ tmp_path,
+ )
+ app.update_blocking()
+ assert sorted(_runs) == ["a.md", "docs/b.md", "docs/c.md"]
+
+ (tmp_path / "a.md").write_text("a2")
+ (tmp_path / "docs" / "b.md").write_text("b2")
+ (tmp_path / "docs" / "c.md").unlink()
+ _runs.clear()
+ app.update_blocking(
+ component_selector=[
+ _path("files", "docs/b.md"),
+ _path("files", "docs/c.md"),
+ _path("files", "missing.md"),
+ ]
+ )
+ assert _runs == ["docs/b.md"]
+ assert _stored() == {"a.md": "a1", "docs/b.md": "b2"}
+
+
+async def _file_view(f: localfs.File) -> tuple[str, bytes]:
+ """A file's content and its memo key as pickled: a read by key must give
+ the memo key the walk gives, or a memo stored by one misses in the other."""
+ return await f.read_text(), pickle.dumps(f.__coco_memo_key__())
+
+
+def _walk(walker: localfs.DirWalker) -> dict[str, tuple[str, bytes]]:
+ async def collect() -> dict[str, tuple[str, bytes]]:
+ return {key: await _file_view(f) async for key, f in walker.items()}
+
+ import asyncio
+
+ return asyncio.run(collect())
+
+
+def _read(walker: localfs.DirWalker, keys: list[Any]) -> dict[str, tuple[str, bytes]]:
+ async def collect() -> dict[str, tuple[str, bytes]]:
+ items = walker.items()
+ return {
+ key: await _file_view(f)
+ async for key, f in items.__coco_items_for_keys__(keys) # type: ignore[attr-defined]
+ }
+
+ import asyncio
+
+ return asyncio.run(collect())
+
+
[email protected]("recursive", [True, False])
+def test_localfs_reads_by_key_exactly_what_it_walks(
+ tmp_path: pathlib.Path, recursive: bool
+) -> None:
+ for rel in ["a.md", "b.txt", "docs/c.md", "docs/deep/d.md", "skip/e.md"]:
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(rel)
+ walker = localfs.walk_dir(
+ tmp_path,
+ recursive=recursive,
+ path_matcher=PatternFilePathMatcher(
+ included_patterns=["**/*.md"], excluded_patterns=["skip"]
+ ),
+ )
+ walked = _walk(walker)
+ candidates: list[Any] = [
+ "a.md",
+ "b.txt",
+ "docs/c.md",
+ "docs/deep/d.md",
+ "skip/e.md",
+ "docs",
+ "./a.md",
+ "docs//c.md",
+ "../a.md",
+ "/a.md",
+ "",
+ "missing.md",
+ "A.md",
+ "DOCS/c.md",
+ 3,
+ ]
+ assert _read(walker, candidates) == walked
+ assert set(walked) == (
+ {"a.md", "docs/c.md", "docs/deep/d.md"} if recursive else {"a.md"}
+ )
diff --git a/python/tests/core/test_component_selector_skips.py b/python/tests/core/test_component_selector_skips.py
new file mode 100644
index 00000000..5a92b476
--- /dev/null
+++ b/python/tests/core/test_component_selector_skips.py
@@ -0,0 +1,157 @@
+"""Sliced execution: an unselected component prepares nothing and runs no user code."""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+import cocoindex as coco
+
+from tests import common
+from tests.common.target_states import GlobalDictTarget
+
+coco_env = common.create_test_env(__file__)
+
+_log: list[str] = []
+
+
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ _log.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _declare(key: str, value: Any) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(key, value))
+
+
+def _app(name: str, main: Any) -> coco.App[Any, Any]:
+ return coco.App(
+ coco.AppConfig(name=f"test_selector_skips_{name}", environment=coco_env), main
+ )
+
+
+# --- an unselected LiveComponent's constructor (user code) runs ----------
+
+_constructed: list[str] = []
+
+
+class _Live:
+ def __init__(self, key: str) -> None:
+ _constructed.append(key)
+ self._key = key
+
+ async def process(self) -> None:
+ _declare(self._key, 1)
+
+ async def process_live(self, operator: Any) -> None:
+ await operator.update_full()
+ await operator.mark_ready()
+
+
+def test_unselected_live_component_is_not_constructed() -> None:
+ _reset()
+ _constructed.clear()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(
+ coco.component_subpath("live"), _Live, [("a", "a"), ("b", "b")]
+ )
+
+ app = _app("p2", main)
+ app.update_blocking()
+ _constructed.clear()
+
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "live" / "a"])
+ assert _constructed == ["a"], f"constructed for unselected too: {_constructed}"
+
+
+# --- per-item work for every unselected mount_each item ------------------
+
+_keyed: list[str] = []
+
+
+class _Keyed:
+ def __init__(self, key: str) -> None:
+ self.key = key
+
+ def __coco_memo_key__(self) -> object:
+ _keyed.append(self.key)
+ return self.key
+
+
+async def _keyed_item(item: _Keyed) -> None:
+ _log.append(item.key)
+ _declare(item.key, 1)
+
+
+def test_unselected_items_are_not_fingerprinted() -> None:
+ _reset()
+ _keyed.clear()
+ keys = [f"k{i}" for i in range(50)]
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount_each(
+ coco.component_subpath("items"), _keyed_item, [(k, _Keyed(k)) for k in keys]
+ )
+
+ app = _app("p3", main)
+ app.update_blocking()
+ _keyed.clear()
+ _log.clear()
+
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "k0"])
+ assert _log == [] or _log == ["k0"]
+ assert set(_keyed) <= {"k0"}, (
+ f"user __coco_memo_key__ ran for {len(set(_keyed))} items, "
+ f"{len(set(_keyed) - {'k0'})} of them unselected"
+ )
+
+
+_helper_input = [1]
+
+
+async def _memo_helper(version: int) -> int:
+ _log.append("helper")
+ _declare("helper", version)
+ return version
+
+
+async def _item(key: str) -> None:
+ _log.append(key)
+ _declare(key, _helper_input[0])
+
+
+# --- an unselected use_mount child that mounts nothing keeps a reusable memo
+
+
+def test_unselected_use_mount_child_keeps_a_reusable_memo() -> None:
+ _reset()
+
+ @coco.fn
+ async def main() -> None:
+ await coco.use_mount(
+ coco.component_subpath("helper"), _memo_helper, _helper_input[0]
+ )
+ await coco.mount_each(coco.component_subpath("items"), _item, [("a", "a")])
+
+ app = _app("p6", main)
+ _helper_input[0] = 1
+ app.update_blocking()
+
+ _helper_input[0] = 2
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "a"])
+ _log.clear()
+
+ # Same input as the selective run, and "helper" mounts nothing: its run was
+ # complete, so a plain update could reuse a memo of it.
+ app.update_blocking()
+ assert "helper" not in _log, f"helper re-ran: memo dropped by selective run: {_log}"
diff --git a/python/tests/core/test_component_selector_sqlite.py b/python/tests/core/test_component_selector_sqlite.py
new file mode 100644
index 00000000..3e540d05
--- /dev/null
+++ b/python/tests/core/test_component_selector_sqlite.py
@@ -0,0 +1,112 @@
+"""Sliced execution with a real container target: SQLite tables and full_reprocess."""
+
+from __future__ import annotations
+
+import tempfile
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Iterator
+
+import pytest
+
+import cocoindex as coco
+from cocoindex._internal.context_keys import ContextProvider
+from cocoindex.connectors import sqlite
+
+from tests import common
+
+SQLITE_DB = coco.ContextKey[sqlite.ManagedConnection]("selector_probe_sqlite_db")
+_source: dict[str, int] = {}
+
+
+@dataclass
+class Row:
+ id: str
+ value: int
+
+
+def conn() -> Iterator[sqlite.ManagedConnection]:
+ with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
+ db_path = Path(f.name)
+ managed = sqlite.connect(db_path, load_vec=False)
+ yield managed
+ managed.close()
+ db_path.unlink(missing_ok=True)
+
+
+def _env(conn: sqlite.ManagedConnection, name: str) -> coco.Environment:
+ ctx = ContextProvider()
+ ctx.provide(SQLITE_DB, conn)
+ settings = coco.Settings.from_env(
+ db_path=common.get_env_db_path(f"selector_probe_sqlite__{name}")
+ )
+ return coco.Environment(settings, context_provider=ctx)
+
+
+async def _row(key: str, value: int, table: Any) -> None:
+ table.declare_row(row=Row(id=key, value=value))
+
+
+async def _main() -> None:
+ table = await sqlite.mount_table_target(
+ SQLITE_DB, "t", await sqlite.TableSchema.from_class(Row, primary_key=["id"])
+ )
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath("items", key), _row, key, value, table)
+
+
+def _rows(conn: sqlite.ManagedConnection) -> dict[str, int]:
+ with conn.readonly() as c:
+ return dict(c.execute('SELECT id, value FROM "t"').fetchall())
+
+
+def test_full_reprocess_with_a_selector_under_a_sqlite_table(
+ conn: sqlite.ManagedConnection,
+) -> None:
+ _source.clear()
+ _source.update(a=1, b=1)
+ app = coco.App(coco.AppConfig(name="probe_fr", environment=_env(conn, "fr")), _main)
+ app.update_blocking()
+ _source.update(a=2, b=2)
+ app.update_blocking(
+ component_selector=[coco.ROOT_PATH / "items" / "a"], full_reprocess=True
+ )
+ assert _rows(conn) == {"a": 2, "b": 1}
+
+
+async def _owns_table(name: str) -> None:
+ table = await coco.use_mount(
+ coco.component_subpath("setup"),
+ sqlite.declare_table_target,
+ SQLITE_DB,
+ name,
+ await sqlite.TableSchema.from_class(Row, primary_key=["id"]),
+ )
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath("rows", key), _row, key, value, table)
+
+
+async def _owner_main() -> None:
+ await coco.mount(coco.component_subpath("p1"), _owns_table, "t")
+
+
+def test_full_reprocess_of_a_selected_table_owner(
+ conn: sqlite.ManagedConnection,
+) -> None:
+ """full_reprocess makes the table's reconcile see prev_may_be_missing. The
+ selected subtree owns the table: is the unchanged table refused as a rebuild?"""
+ _source.clear()
+ _source.update(a=1, b=1)
+ app = coco.App(
+ coco.AppConfig(name="probe_owner_fr", environment=_env(conn, "owner_fr")),
+ _owner_main,
+ )
+ app.update_blocking()
+ _source.update(a=2, b=2)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "p1"], full_reprocess=True)
+ assert _rows(conn) == {"a": 2, "b": 2}
diff --git a/python/tests/core/test_component_selector_state.py b/python/tests/core/test_component_selector_state.py
new file mode 100644
index 00000000..e94c7f79
--- /dev/null
+++ b/python/tests/core/test_component_selector_state.py
@@ -0,0 +1,876 @@
+"""Sliced execution: target states, memoization and tree shape changes.
+
+Each test drives an app through selective updates and then checks, where the
+contract says so, that one plain update brings it to what plain updates alone
+give.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+import cocoindex as coco
+from cocoindex._internal.inspect_api import list_stable_paths_sync
+
+from tests import common
+from tests.common.target_states import (
+ AttachmentDictsTarget,
+ DictsTarget,
+ GlobalDictTarget,
+)
+
+coco_env = common.create_test_env(__file__)
+
+_src: dict[str, Any] = {}
+_runs: list[str] = []
+
+
[email protected](autouse=True)
+def _reset() -> None:
+ GlobalDictTarget.store.clear()
+ GlobalDictTarget.store.sink_exception = False
+ DictsTarget.store.clear()
+ DictsTarget.store.sink_exception = False
+ _src.clear()
+ _runs.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _app(name: str, main: Any, *args: Any) -> coco.App[Any, Any]:
+ return coco.App(
+ coco.AppConfig(name=f"selector_{name}", environment=coco_env), main, *args
+ )
+
+
+def _paths(app: coco.App[Any, Any]) -> set[str]:
+ return {str(p) for p in list_stable_paths_sync(app)}
+
+
+# ---------------------------------------------------------------------------
+# Mount shape: what a plain update rejects, a selective one must not accept
+# ---------------------------------------------------------------------------
+
+
+async def _leaf(key: str, value: Any) -> None:
+ _runs.append(key)
+ coco.declare_target_state(GlobalDictTarget.target_state(key, value))
+
+
+def test_duplicate_mount_is_rejected_with_or_without_a_selector() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("x"), _leaf, "x", 1)
+ await coco.mount(coco.component_subpath("x"), _leaf, "x", 2)
+ await coco.mount(coco.component_subpath("y"), _leaf, "y", 1)
+
+ app = _app("duplicate", main)
+ with pytest.raises(Exception):
+ app.update_blocking()
+ # "x" is unselected: is the duplicate still an error?
+ with pytest.raises(Exception):
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "y"])
+
+
+def test_component_and_its_own_subpath_both_mounted_is_rejected_either_way() -> None:
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("x"), _leaf, "x", 1)
+ await coco.mount(coco.component_subpath("x", "y"), _leaf, "xy", 1)
+
+ app = _app("component_and_dir", main)
+ with pytest.raises(Exception):
+ app.update_blocking()
+ with pytest.raises(Exception):
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x" / "y"])
+
+
+# ---------------------------------------------------------------------------
+# Tombstones of a failed delete, and the component mounted again
+# ---------------------------------------------------------------------------
+
+
+async def _mount_src_main() -> None:
+ for key, value in _src.items():
+ await coco.mount(coco.component_subpath("items", key), _leaf, key, value)
+
+
[email protected]("selected_first", [False, True])
+def test_remounted_after_a_failed_delete_keeps_its_target_states(
+ selected_first: bool,
+) -> None:
+ _src.update(a=1, b=1)
+ app = _app(f"remount_after_failed_delete_{selected_first}", _mount_src_main)
+ app.update_blocking()
+
+ # The delete of "a" fails in the sink: its tombstone stays.
+ del _src["a"]
+ GlobalDictTarget.store.sink_exception = True
+ app.update_blocking()
+ GlobalDictTarget.store.sink_exception = False
+ assert _stored() == {"a": 1, "b": 1}
+
+ # "a" comes back, with a new value.
+ _src["a"] = 2
+ if selected_first:
+ # A run that does not cover "a": "a" is not mounted, its tombstone stays.
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "b"])
+ assert _stored() == {"a": 1, "b": 1}
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "items" / "a"])
+ assert _runs == ["a"]
+ assert _stored() == {"a": 2, "b": 1}
+ owners = common.list_target_state_owners_sync(app)
+ assert owners['/@test_target_state/global_dict/"a"'] == (
+ coco.ROOT_PATH / "items" / "a"
+ )
+
+ # And a plain update agrees.
+ app.update_blocking()
+ assert _stored() == {"a": 2, "b": 1}
+ app.update_blocking()
+ assert _stored() == {"a": 2, "b": 1}
+
+
+# ---------------------------------------------------------------------------
+# Containers: mount_target, child rows, provider generations
+# ---------------------------------------------------------------------------
+
+
+async def _row(entry: tuple[str, int], provider: Any) -> None:
+ key, value = entry
+ _runs.append(key)
+ coco.declare_target_state(provider.target_state(key, value))
+
+
+async def _container_main() -> None:
+ provider = await coco.mount_target(DictsTarget.dict_target("t"))
+ await coco.mount_each(
+ coco.component_subpath("rows"),
+ _row,
+ [(k, (k, v)) for k, v in _src.items()],
+ provider,
+ )
+
+
+def _rows() -> dict[str, Any]:
+ return {k: v.data for k, v in DictsTarget.store.data.get("t", {}).items()}
+
+
+def _row_path(key: str) -> coco.StablePath:
+ path: coco.StablePath = coco.ROOT_PATH / "rows" / key
+ return path
+
+
+def test_container_dropped_while_its_rows_are_unselected() -> None:
+ declare = {"on": True}
+
+ @coco.fn
+ async def main() -> None:
+ if not declare["on"]:
+ return
+ await _container_main()
+
+ _src.update(a=1, b=1)
+ app = _app("container_dropped", main)
+ app.update_blocking()
+ assert _rows() == {"a": 1, "b": 1}
+
+ declare["on"] = False
+ # The root runs and no longer declares the container (a use_mount child
+ # of the root through mount_target), while the rows are unselected.
+ app.update_blocking(component_selector=[_row_path("a")])
+ after_selective = (dict(DictsTarget.store.data), _paths(app))
+
+ app.update_blocking()
+ assert DictsTarget.store.data == {}, after_selective
+ assert common.list_target_state_owners_sync(app) == {}
+ assert _paths(app) == {"/"}
+
+
+def test_first_ever_update_is_selective_and_creates_the_container() -> None:
+ _src.update(a=1, b=1)
+ app = _app("container_first_selective", _container_main)
+ app.update_blocking(component_selector=[_row_path("a")])
+ assert _rows() == {"a": 1}
+ app.update_blocking()
+ assert _rows() == {"a": 1, "b": 1}
+
+
+async def _memo_container_parent(items: dict[str, int]) -> None:
+ _runs.append("parent")
+ provider = await coco.mount_target(DictsTarget.dict_target("t"))
+ await coco.mount_each(
+ coco.component_subpath("rows"),
+ _row,
+ [(k, (k, v)) for k, v in items.items()],
+ provider,
+ )
+
+
+async def _memo_parent_main() -> None:
+ await coco.mount(coco.component_subpath("p"), _memo_container_parent, dict(_src))
+
+
+def test_selected_row_under_a_memoized_container_parent() -> None:
+ _src.update(a=1, b=1)
+ app = _app("memo_container_parent", _memo_parent_main)
+ app.update_blocking()
+
+ # Nothing changed: the parent memo-hits and stands in for the row.
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "p" / "rows" / "a"])
+ assert _runs == []
+
+ # Both rows change; only "a" is selected.
+ _src.update(a=2, b=2)
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "p" / "rows" / "a"])
+ assert sorted(_runs) == ["a", "parent"]
+ assert _rows() == {"a": 2, "b": 1}
+
+ # The parent stored no memo: the next plain update reaches "b".
+ _runs.clear()
+ app.update_blocking()
+ assert _rows() == {"a": 2, "b": 2}
+ assert "b" in _runs
+
+
+# ---------------------------------------------------------------------------
+# Memo and dependencies
+# ---------------------------------------------------------------------------
+
+_CTX = coco.ContextKey[int]("selector_ctx", detect_change=True)
+
+
+async def _ctx_leaf(key: str) -> None:
+ _runs.append(key)
+ coco.declare_target_state(
+ GlobalDictTarget.target_state(key, coco.use_context(_CTX))
+ )
+
+
+async def _ctx_main() -> None:
+ for key in _src:
+ await coco.mount(coco.component_subpath(key), _ctx_leaf, key)
+
+
+def test_tracked_context_change_reaches_an_unselected_memo_later() -> None:
+ env = common.create_test_env(__file__, suffix="ctx")
+ env.context_provider.provide(_CTX, 1)
+ _src.update(a=None, b=None)
+ app = coco.App(coco.AppConfig(name="selector_ctx", environment=env), _ctx_main)
+ app.update_blocking()
+ assert _stored() == {"a": 1, "b": 1}
+
+ env.context_provider.provide(_CTX, 2)
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "a"])
+ assert _runs == ["a"]
+ assert _stored() == {"a": 2, "b": 1}
+
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == ["b"]
+ assert _stored() == {"a": 2, "b": 2}
+
+
+async def _double(x: int) -> int:
+ _runs.append(f"double({x})")
+ return x * 2
+
+
+async def _map_main() -> None:
+ doubled = await coco.map(_double, sorted(_src.values()))
+ coco.declare_target_state(GlobalDictTarget.target_state("sum", sum(doubled)))
+ for key, value in _src.items():
+ await coco.mount(coco.component_subpath(key), _leaf, key, value)
+
+
+def test_map_and_function_memo_in_the_root_under_a_selector() -> None:
+ _src.update(a=1, b=2)
+ app = _app("map_root", _map_main)
+ app.update_blocking()
+ assert _stored() == {"sum": 6, "a": 1, "b": 2}
+
+ _src.update(b=3)
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "a"])
+ # The root runs: its function memos are its own (it is always run).
+ assert "double(3)" in _runs and "b" not in _runs
+ assert _stored() == {"sum": 8, "a": 1, "b": 2}
+
+ _runs.clear()
+ app.update_blocking()
+ assert _stored() == {"sum": 8, "a": 1, "b": 3}
+ # The memo of double(1) survived the selective run of the root.
+ assert "double(1)" not in _runs
+
+
+async def _um_inner(items: dict[str, int]) -> int:
+ _runs.append("inner")
+ for key, value in items.items():
+ await coco.mount(coco.component_subpath(key), _leaf, key, value)
+ return len(items)
+
+
+async def _um_outer(items: dict[str, int]) -> int:
+ _runs.append("outer")
+ return await coco.use_mount( # type: ignore[no-any-return]
+ coco.component_subpath("inner"), _um_inner, items
+ )
+
+
+async def _um_chain_main() -> None:
+ n = await coco.use_mount(coco.component_subpath("outer"), _um_outer, dict(_src))
+ coco.declare_target_state(GlobalDictTarget.target_state("n", n))
+
+
+def test_memoized_use_mount_chain_under_a_selector() -> None:
+ _src.update(a=1, b=1)
+ app = _app("um_chain", _um_chain_main)
+ app.update_blocking()
+ sel = [coco.ROOT_PATH / "outer" / "inner" / "a"]
+
+ _src.update(a=2, b=2, c=1)
+ _runs.clear()
+ app.update_blocking(component_selector=sel)
+ assert sorted(_runs) == ["a", "inner", "outer"]
+ assert _stored() == {"n": 3, "a": 2, "b": 1}
+
+ # Neither link of the chain may memo-hit now: "b" and "c" are behind.
+ _runs.clear()
+ app.update_blocking()
+ assert _stored() == {"n": 3, "a": 2, "b": 2, "c": 1}
+
+ _runs.clear()
+ app.update_blocking()
+ assert _runs == []
+
+
+async def _state_leaf(key: str, value: int) -> None:
+ state = coco.use_state("seen", 0)
+ state.value = state.value + 1
+ _runs.append(key)
+ coco.declare_target_state(GlobalDictTarget.target_state(key, (value, state.value)))
+
+
+async def _state_main() -> None:
+ for key, value in _src.items():
+ await coco.mount(coco.component_subpath(key), _state_leaf, key, value)
+
+
+def test_use_state_of_an_unselected_component_is_not_advanced() -> None:
+ _src.update(a=1, b=1)
+ app = _app("use_state", _state_main)
+ app.update_blocking()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "a"])
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "a"])
+ assert _stored() == {"a": (1, 3), "b": (1, 1)}
+ # A preview does not advance it either.
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "b"], preview=True)
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "b"])
+ assert _stored() == {"a": (1, 3), "b": (1, 2)}
+
+
+# ---------------------------------------------------------------------------
+# Tree shape
+# ---------------------------------------------------------------------------
+
+
+async def _deep(depth: int, max_depth: int) -> None:
+ _runs.append(str(depth))
+ coco.declare_target_state(GlobalDictTarget.target_state(f"d{depth}", _src["v"]))
+ if depth < max_depth:
+ await coco.mount(coco.component_subpath("n"), _deep, depth + 1, max_depth)
+
+
+def test_very_deep_path_selects_only_the_deepest_and_runs_its_ancestors() -> None:
+ depth = 60
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("n"), _deep, 1, depth)
+
+ _src["v"] = 1
+ app = _app("deep", main)
+ app.update_blocking()
+
+ _src["v"] = 2
+ deepest = coco.ROOT_PATH
+ for _ in range(depth):
+ deepest = deepest / "n"
+ _runs.clear()
+ app.update_blocking(component_selector=[deepest])
+ assert _runs == [str(i) for i in range(1, depth + 1)]
+ # Ancestors run, so they redeclare with the new value too.
+ assert all(v == 2 for v in _stored().values())
+
+
+def test_selected_delete_with_nested_children_deletes_the_subtree() -> None:
+ @coco.fn
+ async def group(name: str, keys: list[str]) -> None:
+ for key in keys:
+ await coco.mount(coco.component_subpath(key), _leaf, f"{name}/{key}", 1)
+
+ @coco.fn
+ async def main() -> None:
+ for name, keys in _src.items():
+ await coco.mount(coco.component_subpath(name), group, name, keys)
+
+ _src.update(g=["a", "b"], h=["a"])
+ app = _app("nested_delete", main)
+ app.update_blocking()
+ del _src["g"]
+ del _src["h"]
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "g"])
+ assert _stored() == {"h/a": 1}
+ assert not any(p.startswith('/"g"') for p in _paths(app)), _paths(app)
+ assert '/"h"/"a"' in _paths(app)
+ app.update_blocking()
+ assert _stored() == {}
+ assert _paths(app) == {"/"}
+
+
+def test_component_becomes_a_directory_with_the_same_child_keys() -> None:
+ """`x` was a component mounting `x/a`; now the root mounts `x/a` itself."""
+ shape = {"nested": True}
+
+ @coco.fn
+ async def x_component() -> None:
+ await coco.mount(coco.component_subpath("a"), _leaf, "a", _src["a"])
+ coco.declare_target_state(GlobalDictTarget.target_state("x", 1))
+
+ @coco.fn
+ async def main() -> None:
+ if shape["nested"]:
+ await coco.mount(coco.component_subpath("x"), x_component)
+ else:
+ await coco.mount(coco.component_subpath("x", "a"), _leaf, "a", _src["a"])
+
+ for selective in (False, True):
+ GlobalDictTarget.store.clear()
+ shape["nested"] = True
+ _src["a"] = 1
+ app = _app(f"component_to_dir_{selective}", main)
+ app.update_blocking()
+ assert _stored() == {"a": 1, "x": 1}
+
+ shape["nested"] = False
+ _src["a"] = 2
+ if selective:
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x" / "a"])
+ # "x" is unselected: its own target state stays.
+ assert _stored() == {"a": 2, "x": 1}
+ app.update_blocking()
+ assert _stored() == {"a": 2}, f"selective={selective}"
+ app.update_blocking()
+ assert _stored() == {"a": 2}, f"selective={selective}, second plain"
+ assert common.list_target_state_owners_sync(app) == {
+ '/@test_target_state/global_dict/"a"': coco.ROOT_PATH / "x" / "a"
+ }
+
+ # And back: "x" a component again.
+ shape["nested"] = True
+ _src["a"] = 3
+ if selective:
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x"])
+ app.update_blocking()
+ assert _stored() == {"a": 3, "x": 1}, f"selective={selective}, back"
+
+
+def test_selected_child_removed_after_a_selective_demotion_is_deleted() -> None:
+ """`x` was a component mounting `x/k` and `x/m`; a selective run of `x/k`
+ makes `x` a directory; then `x/k` goes, and a selective run of `x/k` must
+ delete it, as it would under a directory that was always one."""
+ nested = [True]
+ keys = ["k", "m"]
+
+ @coco.fn
+ async def x_component() -> None:
+ for key in keys:
+ await coco.mount(coco.component_subpath(key), _leaf, key, 1)
+
+ @coco.fn
+ async def main() -> None:
+ if nested[0]:
+ await coco.mount(coco.component_subpath("x"), x_component)
+ else:
+ for key in keys:
+ await coco.mount(coco.component_subpath("x", key), _leaf, key, 1)
+
+ app = _app("selective_demotion_then_delete", main)
+ app.update_blocking()
+ assert _stored() == {"k": 1, "m": 1}
+
+ selected = [coco.ROOT_PATH / "x" / "k"]
+ nested[0] = False
+ app.update_blocking(component_selector=selected)
+ keys.remove("k")
+ app.update_blocking(component_selector=selected)
+ assert _stored() == {"m": 1}
+
+
+def test_selected_gone_child_is_deleted_when_its_component_parent_becomes_a_directory() -> (
+ None
+):
+ nested = [True]
+ keys = ["k", "b"]
+
+ @coco.fn
+ async def x_component() -> None:
+ for key in keys:
+ await coco.mount(coco.component_subpath(key), _leaf, key, 1)
+
+ @coco.fn
+ async def main() -> None:
+ if nested[0]:
+ await coco.mount(coco.component_subpath("x"), x_component)
+ else:
+ for key in keys:
+ await coco.mount(coco.component_subpath("x", key), _leaf, key, 1)
+
+ app = _app("component_parent_becomes_directory", main)
+ app.update_blocking()
+ assert _stored() == {"k": 1, "b": 1}
+
+ # One change: `x` becomes a directory and `b` goes. Selecting `x/b` must
+ # delete it, as selecting a gone item under a directory does.
+ nested[0] = False
+ keys.remove("b")
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "x" / "b"])
+ assert _stored() == {"k": 1}
+
+
+# ---------------------------------------------------------------------------
+# Ownership transfer from an unselected component
+# ---------------------------------------------------------------------------
+
+
+async def _memo_leaf(key: str, value: int) -> None:
+ _runs.append(key)
+ coco.declare_target_state(GlobalDictTarget.target_state(key, value))
+
+
+def test_owner_taken_over_while_unselected_redeclares_when_mounted_again() -> None:
+ where = {"group": "items"}
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(
+ coco.component_subpath(where["group"], "c"), _memo_leaf, "c", 5
+ )
+
+ app = _app("takeover_then_memo_hit", main)
+ app.update_blocking()
+ assert _stored() == {"c": 5}
+
+ # The item moves under another group. A selective run of that group runs
+ # the new component, which takes "c" over; the old one is unselected, so it
+ # is neither run nor deleted.
+ where["group"] = "other"
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "other"])
+ assert _stored() == {"c": 5}
+
+ # The item moves back. A plain update must give what a plain update gives:
+ # "c" declared by items/c.
+ where["group"] = "items"
+ app.update_blocking()
+ assert _stored() == {"c": 5}
+ assert common.list_target_state_owners_sync(app) == {
+ '/@test_target_state/global_dict/"c"': coco.ROOT_PATH / "items" / "c"
+ }
+
+
+async def _memo_group(name: str, keys: tuple[str, ...]) -> None:
+ # Declares nothing of its own: only its child owns a target state.
+ _runs.append(name)
+ for key in keys:
+ await coco.mount(coco.component_subpath(key), _memo_leaf, key, 5)
+
+
+def test_owner_taken_over_under_a_memoized_parent_redeclares() -> None:
+ where = {"group": "items"}
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(
+ coco.component_subpath(where["group"]), _memo_group, "grp", ("c",)
+ )
+
+ app = _app("takeover_under_memo_parent", main)
+ app.update_blocking()
+ assert _stored() == {"c": 5}
+
+ where["group"] = "other"
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "other"])
+ where["group"] = "items"
+ app.update_blocking()
+ assert _stored() == {"c": 5}
+
+
+# ---------------------------------------------------------------------------
+# Pre-existing (reproduces with plain updates only): a failed cascaded delete
+# ---------------------------------------------------------------------------
+
+
+def _tolerant_global_dict() -> None:
+ store = GlobalDictTarget.store
+
+ def sink(ctx: Any, actions: Any, /) -> None:
+ if store.sink_exception:
+ raise ValueError("injected sink exception")
+ for key, value in actions:
+ if coco.is_non_existence(value):
+ store.data.pop(key, None)
+ else:
+ store.data[key] = value
+
+ store._action_sink = coco.TargetActionSink.from_fn(sink)
+
+
+def test_failed_delete_under_a_deleted_parent_is_retried() -> None:
+ _tolerant_global_dict()
+ mounted = {"m": True}
+
+ @coco.fn
+ async def leaf() -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state("x", 1))
+
+ @coco.fn
+ async def mid() -> None:
+ # Declares nothing of its own: its delete has nothing to sink.
+ await coco.mount(coco.component_subpath("l"), leaf)
+
+ @coco.fn
+ async def main() -> None:
+ if mounted["m"]:
+ await coco.mount(coco.component_subpath("m"), mid)
+
+ try:
+ app = _app("orphan_tombstone", main)
+ app.update_blocking()
+ assert _stored() == {"x": 1}
+
+ mounted["m"] = False
+ GlobalDictTarget.store.sink_exception = True
+ app.update_blocking()
+ GlobalDictTarget.store.sink_exception = False
+
+ app.update_blocking()
+ app.update_blocking()
+ assert _stored() == {}
+ assert common.list_target_state_owners_sync(app) == {}
+ finally:
+ GlobalDictTarget.store._action_sink = coco.TargetActionSink.from_fn(
+ GlobalDictTarget.store._sink
+ )
+
+
+# ---------------------------------------------------------------------------
+# A memoized parent that a selective run leaves partly unrun
+# ---------------------------------------------------------------------------
+
+
+def _memo_parent_app(name: str) -> tuple[coco.App[Any, Any], dict[str, bool]]:
+ """`p` is memoized and mounts `a` and `b` while `_src` has them; a child
+ whose key is in `fail` raises."""
+ fail: dict[str, bool] = {}
+
+ @coco.fn
+ async def child(key: str) -> None:
+ _runs.append(key)
+ if fail.get(key):
+ raise ValueError(f"injected failure in {key}")
+ coco.declare_target_state(GlobalDictTarget.target_state(key, _src[key]))
+
+ @coco.fn(memo=True)
+ async def parent() -> None:
+ _runs.append("p")
+ for key in ("a", "b"):
+ if key in _src:
+ await coco.mount(coco.component_subpath(key), child, key)
+
+ @coco.fn
+ async def main() -> None:
+ await coco.mount(coco.component_subpath("p"), parent)
+
+ return _app(name, main), fail
+
+
+def _update_tolerating_failure(app: coco.App[Any, Any], **kwargs: Any) -> None:
+ try:
+ app.update_blocking(**kwargs)
+ except Exception:
+ pass
+
+
+def test_a_selective_run_with_a_failed_child_still_drops_the_parent_memo() -> None:
+ app, fail = _memo_parent_app("memo_failed_child")
+ _src.update(a=1, b=1)
+ app.update_blocking()
+ assert _stored() == {"a": 1, "b": 1}
+
+ del _src["b"]
+ fail["a"] = True
+ _update_tolerating_failure(
+ app,
+ full_reprocess=True,
+ component_selector=[coco.ROOT_PATH / "p" / "a"],
+ )
+ # `b` is left out, so it keeps its target state for now.
+ assert _stored() == {"a": 1, "b": 1}
+
+ fail["a"] = False
+ _runs.clear()
+ app.update_blocking()
+ assert "p" in _runs
+ assert _stored() == {"a": 1}
+
+
+def test_a_tombstone_the_selector_keeps_is_no_failed_delete() -> None:
+ store = GlobalDictTarget.store
+ fail_delete = {"b": False}
+
+ def sink(ctx: Any, actions: Any, /) -> None:
+ for key, value in actions:
+ if coco.is_non_existence(value) and fail_delete.get(key):
+ raise ValueError(f"injected delete failure for {key}")
+ for key, value in actions:
+ if coco.is_non_existence(value):
+ store.data.pop(key, None)
+ else:
+ store.data[key] = value
+
+ store._action_sink = coco.TargetActionSink.from_fn(sink)
+ try:
+ app, _ = _memo_parent_app("memo_kept_tombstone")
+ _src.update(a=1, b=1)
+ app.update_blocking()
+
+ # `b`'s delete fails, so its tombstone stays under `p`.
+ del _src["b"]
+ fail_delete["b"] = True
+ _update_tolerating_failure(app, full_reprocess=True)
+ assert _stored() == {"a": 1, "b": 1}
+ fail_delete["b"] = False
+
+ # A selective run that leaves the tombstone alone succeeds.
+ app.update_blocking(
+ full_reprocess=True, component_selector=[coco.ROOT_PATH / "p" / "a"]
+ )
+ assert _stored() == {"a": 1, "b": 1}
+
+ # The next plain update runs `p` and deletes `b`.
+ _runs.clear()
+ app.update_blocking()
+ assert "p" in _runs
+ assert _stored() == {"a": 1}
+ finally:
+ store._action_sink = coco.TargetActionSink.from_fn(store._sink)
+
+
+def test_a_failed_child_delete_under_full_reprocess_is_retried() -> None:
+ store = GlobalDictTarget.store
+ fail_delete = {"b": False}
+
+ def sink(ctx: Any, actions: Any, /) -> None:
+ for key, value in actions:
+ if coco.is_non_existence(value) and fail_delete.get(key):
+ raise ValueError(f"injected delete failure for {key}")
+ for key, value in actions:
+ if coco.is_non_existence(value):
+ store.data.pop(key, None)
+ else:
+ store.data[key] = value
+
+ store._action_sink = coco.TargetActionSink.from_fn(sink)
+ try:
+ app, _ = _memo_parent_app("memo_failed_delete_full_reprocess")
+ _src.update(a=1, b=1)
+ app.update_blocking()
+
+ del _src["b"]
+ fail_delete["b"] = True
+ _update_tolerating_failure(app, full_reprocess=True)
+ fail_delete["b"] = False
+
+ # Same memo key as the stored memo: only a dropped memo makes `p`
+ # run, and only a run of `p` sweeps `b`'s tombstone again.
+ app.update_blocking()
+ assert _stored() == {"a": 1}
+ finally:
+ store._action_sink = coco.TargetActionSink.from_fn(store._sink)
+
+
+# ---------------------------------------------------------------------------
+# Attachments declared by children, some unselected
+# ---------------------------------------------------------------------------
+
+
+async def _attach_child(entry: tuple[str, int], provider: Any) -> None:
+ key, value = entry
+ _runs.append(key)
+ coco.declare_target_state(provider.attachment("items").target_state(key, value))
+
+
+async def _attachment_main() -> None:
+ provider = await coco.use_mount(
+ coco.component_subpath("setup"), AttachmentDictsTarget.declare_dict_target, "D"
+ )
+ await coco.mount_each(
+ coco.component_subpath("kids"),
+ _attach_child,
+ [(k, (k, v)) for k, v in _src.items()],
+ provider,
+ )
+
+
+def _attachments() -> dict[str, Any]:
+ data = AttachmentDictsTarget.store.attachment_data.get("D", {}).get("items", {})
+ return {k: v.data for k, v in data.items()}
+
+
+def test_attachments_of_unselected_children_are_kept_and_converge() -> None:
+ AttachmentDictsTarget.store.clear()
+ _src.update(a=1, b=1, c=1)
+ app = _app("attachments", _attachment_main)
+ app.update_blocking()
+ assert _attachments() == {"a": 1, "b": 1, "c": 1}
+
+ _src.update(a=2, b=2)
+ del _src["c"]
+ _runs.clear()
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "kids" / "a"])
+ assert _runs == ["a"]
+ assert _attachments() == {"a": 2, "b": 1, "c": 1}
+
+ app.update_blocking(component_selector=[coco.ROOT_PATH / "kids" / "c"])
+ assert _attachments() == {"a": 2, "b": 1}
+
+ app.update_blocking()
+ assert _attachments() == {"a": 2, "b": 2}
diff --git a/python/tests/core/test_nested_delete_retry.py b/python/tests/core/test_nested_delete_retry.py
new file mode 100644
index 00000000..5ef9eb47
--- /dev/null
+++ b/python/tests/core/test_nested_delete_retry.py
@@ -0,0 +1,426 @@
+"""A failed delete below a deleted component is retried by a later update.
+
+When a component is no longer mounted, its delete cascades: the delete of each
+child component runs from its parent's delete, and the child's tombstone is
+keyed under that parent. A child delete that fails keeps its tombstone, so the
+parent must keep its own tombstone too: otherwise nothing finds the child's
+tombstone again, and the child's target states stay for good.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any, Collection, Iterator
+
+import cocoindex as coco
+import cocoindex.inspect as coco_inspect
+import pytest
+
+from tests import common
+from tests.common.target_states import DictDataWithPrev, GlobalDictTarget
+
+coco_env = common.create_test_env(__file__)
+
+# Keys whose actions make the sink fail. A sink call can batch the actions of
+# several components, so a failure can also fail other keys in the same call.
+_failing_keys: set[str] = set()
+
+
[email protected](autouse=True)
+def _failing_sink() -> Iterator[None]:
+ store = GlobalDictTarget.store
+ store.clear()
+ _failing_keys.clear()
+
+ def sink(
+ ctx: coco.ContextProvider,
+ actions: Collection[tuple[str, DictDataWithPrev | coco.NonExistenceType]],
+ /,
+ ) -> None:
+ if any(key in _failing_keys for key, _ in actions):
+ raise ValueError("injected sink exception")
+ store._sink(ctx, actions)
+
+ store._action_sink = coco.TargetActionSink.from_fn(sink)
+ try:
+ yield
+ finally:
+ store._action_sink = coco.TargetActionSink.from_fn(store._sink)
+ _failing_keys.clear()
+
+
+def _stored() -> dict[str, Any]:
+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}
+
+
+def _assert_all_gone(app: coco.App[Any, Any]) -> None:
+ assert _stored() == {}
+ assert common.list_target_state_owners_sync(app) == {}
+ assert coco_inspect.list_stable_paths_sync(app) == [coco.ROOT_PATH]
+
+
+##################################################################################
+# A parent that declares nothing itself, with one child that declares `x`.
+
+_mounted: dict[str, int | None] = {}
+
+
+async def _leaf(value: int) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state("x", value))
+
+
+async def _mid(leaf_value: int | None) -> None:
+ if leaf_value is not None:
+ await coco.mount(coco.component_subpath("l"), _leaf, leaf_value)
+
+
+async def _mid_main() -> None:
+ if "m" in _mounted:
+ await coco.mount(coco.component_subpath("m"), _mid, _mounted["m"])
+
+
+def _mid_app(name: str) -> coco.App[Any, Any]:
+ _mounted.clear()
+ _mounted["m"] = 1
+ app = coco.App(coco.AppConfig(name=name, environment=coco_env), _mid_main)
+ app.update_blocking()
+ assert _stored() == {"x": 1}
+ return app
+
+
+def _fail_delete_of_m(app: coco.App[Any, Any]) -> None:
+ """Unmount `m` while the delete of `x` fails."""
+ del _mounted["m"]
+ _failing_keys.add("x")
+ try:
+ app.update_blocking()
+ finally:
+ _failing_keys.clear()
+ assert _stored() == {"x": 1}
+ assert common.list_target_state_owners_sync(app) == {
+ '/@test_target_state/global_dict/"x"': coco.ROOT_PATH / "m" / "l",
+ }
+
+
+def test_failed_delete_under_a_deleted_parent_is_retried() -> None:
+ app = _mid_app("failed_delete_under_deleted_parent")
+ _fail_delete_of_m(app)
+
+ app.update_blocking()
+ _assert_all_gone(app)
+
+
+def test_failed_delete_is_retried_until_it_succeeds() -> None:
+ app = _mid_app("failed_delete_retried_until_success")
+ _fail_delete_of_m(app)
+
+ # The retry fails too: the delete stays owed.
+ _failing_keys.add("x")
+ try:
+ app.update_blocking()
+ finally:
+ _failing_keys.clear()
+ assert _stored() == {"x": 1}
+
+ app.update_blocking()
+ _assert_all_gone(app)
+ # Nothing is left to retry.
+ GlobalDictTarget.store.metrics.clear()
+ app.update_blocking()
+ assert GlobalDictTarget.store.metrics.collect() == {}
+
+
+def test_remount_before_retry_keeps_the_remounted_child() -> None:
+ app = _mid_app("remount_before_retry_keeps_child")
+ _fail_delete_of_m(app)
+
+ # `m` comes back, with `l` declaring a new value, before any retry. The
+ # owed deletes must not remove what the re-mounted components declare.
+ _mounted["m"] = 2
+ app.update_blocking()
+ assert _stored() == {"x": 2}
+ assert common.list_target_state_owners_sync(app) == {
+ '/@test_target_state/global_dict/"x"': coco.ROOT_PATH / "m" / "l",
+ }
+ app.update_blocking()
+ assert _stored() == {"x": 2}
+
+ del _mounted["m"]
+ app.update_blocking()
+ _assert_all_gone(app)
+
+
+def test_remount_before_retry_without_the_child_deletes_it() -> None:
+ app = _mid_app("remount_before_retry_drops_child")
+ _fail_delete_of_m(app)
+
+ # `m` comes back without `l`: the re-mounted `m` retries the delete of `l`.
+ _mounted["m"] = None
+ app.update_blocking()
+ assert _stored() == {}
+ assert common.list_target_state_owners_sync(app) == {}
+
+ del _mounted["m"]
+ app.update_blocking()
+ _assert_all_gone(app)
+
+
+async def test_concurrent_updates_retry_a_failed_delete_once() -> None:
+ app = await asyncio.to_thread(_mid_app, "concurrent_updates_retry")
+ await asyncio.to_thread(_fail_delete_of_m, app)
+
+ GlobalDictTarget.store.metrics.clear()
+ await asyncio.gather(app.update(), app.update())
+ assert GlobalDictTarget.store.metrics.collect()["delete"] == 1
+ assert _stored() == {}
+ assert await common.list_target_state_owners(app) == {}
+
+
+def test_preview_after_a_failed_delete_changes_nothing() -> None:
+ app = _mid_app("preview_after_failed_delete")
+ _fail_delete_of_m(app)
+
+ GlobalDictTarget.store.metrics.clear()
+ app.update_blocking(preview=True)
+ assert _stored() == {"x": 1}
+ assert GlobalDictTarget.store.metrics.collect() == {}
+
+ app.update_blocking()
+ _assert_all_gone(app)
+
+
+def test_drop_after_a_failed_delete() -> None:
+ app = _mid_app("drop_after_failed_delete")
+ _fail_delete_of_m(app)
+
+ app.drop_blocking()
+ assert _stored() == {}
+ assert coco_inspect.list_stable_paths_sync(app) == []
+ assert common.list_target_state_owners_sync(app) == {}
+
+
+def test_failed_drop_of_a_nested_child_is_retried() -> None:
+ app = _mid_app("failed_drop_of_nested_child")
+
+ _failing_keys.add("x")
+ try:
+ with pytest.raises(Exception, match="injected sink exception"):
+ app.drop_blocking()
+ finally:
+ _failing_keys.clear()
+ assert _stored() == {"x": 1}
+
+ app.drop_blocking()
+ assert _stored() == {}
+ assert coco_inspect.list_stable_paths_sync(app) == []
+ assert common.list_target_state_owners_sync(app) == {}
+
+
+##################################################################################
+# A chain c0 β†’ c0/c1 β†’ c0/c1/c2 β†’ c0/c1/c2/c3; level `i` declares `k{i}`.
+
+_CHAIN_DEPTH = 4
+_chain_mounted: list[bool] = [True]
+
+
+async def _chain_level(level: int) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(f"k{level}", level))
+ if level + 1 < _CHAIN_DEPTH:
+ await coco.mount(
+ coco.component_subpath(f"c{level + 1}"), _chain_level, level + 1
+ )
+
+
+async def _chain_main() -> None:
+ if _chain_mounted[0]:
+ await coco.mount(coco.component_subpath("c0"), _chain_level, 0)
+
+
[email protected]("failing_level", range(_CHAIN_DEPTH))
+def test_failed_delete_at_any_depth_is_retried(failing_level: int) -> None:
+ _chain_mounted[0] = True
+ app = coco.App(
+ coco.AppConfig(
+ name=f"failed_delete_at_depth_{failing_level}", environment=coco_env
+ ),
+ _chain_main,
+ )
+ app.update_blocking()
+ assert _stored() == {f"k{i}": i for i in range(_CHAIN_DEPTH)}
+
+ _chain_mounted[0] = False
+ failing_key = f"k{failing_level}"
+ _failing_keys.add(failing_key)
+ try:
+ app.update_blocking()
+ finally:
+ _failing_keys.clear()
+ assert _stored()[failing_key] == failing_level
+
+ app.update_blocking()
+ _assert_all_gone(app)
+
+
[email protected]("failing_level", range(_CHAIN_DEPTH))
+def test_failed_delete_at_any_depth_then_drop(failing_level: int) -> None:
+ _chain_mounted[0] = True
+ app = coco.App(
+ coco.AppConfig(
+ name=f"failed_delete_at_depth_{failing_level}_then_drop",
+ environment=coco_env,
+ ),
+ _chain_main,
+ )
+ app.update_blocking()
+
+ _chain_mounted[0] = False
+ _failing_keys.add(f"k{failing_level}")
+ try:
+ app.update_blocking()
+ finally:
+ _failing_keys.clear()
+
+ app.drop_blocking()
+ assert _stored() == {}
+ assert coco_inspect.list_stable_paths_sync(app) == []
+ assert common.list_target_state_owners_sync(app) == {}
+
+
+##################################################################################
+# A memoized parent whose own run deletes a child it no longer mounts.
+
+_memo_runs: list[str] = []
+
+
+async def _memo_parent(names: tuple[str, ...]) -> None:
+ _memo_runs.append("parent")
+ for name in names:
+ await coco.mount(coco.component_subpath(name), _named_leaf, name)
+
+
+async def _named_leaf(name: str) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(name, 1))
+
+
+async def _memo_grandparent(names: tuple[str, ...]) -> None:
+ await coco.mount(coco.component_subpath("p"), _memo_parent, names)
+
+
+_memo_names: list[tuple[str, ...]] = []
+
+
+async def _memo_main() -> None:
+ await coco.mount(coco.component_subpath("g"), _memo_grandparent, _memo_names[0])
+
+
+def test_memoized_parent_retries_a_failed_child_delete() -> None:
+ _memo_runs.clear()
+ _memo_names[:] = [("a", "b")]
+ app = coco.App(
+ coco.AppConfig(
+ name="memoized_parent_retries_child_delete", environment=coco_env
+ ),
+ _memo_main,
+ )
+ app.update_blocking()
+ assert _stored() == {"a": 1, "b": 1}
+
+ # The parent runs with new arguments and no longer mounts `b`; the delete
+ # of `b` fails.
+ _memo_names[:] = [("a",)]
+ _failing_keys.add("b")
+ try:
+ app.update_blocking()
+ finally:
+ _failing_keys.clear()
+ assert _stored() == {"a": 1, "b": 1}
+
+ # Same arguments: the parent stored no memo from the run that left the
+ # delete owed (and nor did the grandparent), so it runs and retries it.
+ _memo_runs.clear()
+ app.update_blocking()
+ assert _memo_runs == ["parent"]
+ assert _stored() == {"a": 1}
+ assert common.list_target_state_owners_sync(app) == {
+ '/@test_target_state/global_dict/"a"': coco.ROOT_PATH / "g" / "p" / "a",
+ }
+
+ # Now the memo holds.
+ _memo_runs.clear()
+ app.update_blocking()
+ assert _memo_runs == []
+ assert _stored() == {"a": 1}
+
+
+##################################################################################
+# `operator.delete` of a live component's child whose own child declares `y`.
+
+_live_children: dict[str, int] = {}
+_live_delete: list[str] = []
+
+
+async def _live_child(value: int) -> None:
+ await coco.mount(coco.component_subpath("g"), _named_value, "y", value)
+
+
+async def _named_value(name: str, value: int) -> None:
+ coco.declare_target_state(GlobalDictTarget.target_state(name, value))
+
+
+class _LiveParent:
+ async def process(self) -> None:
+ for key, value in _live_children.items():
+ await coco.mount(coco.component_subpath(key), _live_child, value)
+
+ async def process_live(self, operator: coco.LiveComponentOperator) -> None:
+ await operator.update_full()
+ for key in _live_delete:
+ handle = await operator.delete(coco.component_subpath(key))
+ await handle.ready()
+ await operator.mark_ready()
+
+
+async def _live_main() -> None:
+ await coco.mount(coco.component_subpath("live"), _LiveParent)
+
+
+def test_failed_live_delete_of_a_nested_child_is_retried() -> None:
+ _live_children.clear()
+ _live_delete.clear()
+ _live_children["c"] = 1
+ app = coco.App(
+ coco.AppConfig(name="failed_live_delete_nested", environment=coco_env),
+ _live_main,
+ )
+ app.update_blocking(live=True)
+ assert _stored() == {"y": 1}
+
+ # `operator.delete` of `c` cascades to `c/g`, whose delete fails.
+ _live_delete.append("c")
+ _failing_keys.add("y")
+ try:
+ app.update_blocking(live=True)
+ finally:
+ _failing_keys.clear()
+ assert _stored() == {"y": 1}
+
+ # The source no longer has `c`: the live component's next full update
+ # retries the delete.
+ _live_delete.clear()
+ del _live_children["c"]
+ app.update_blocking(live=True)
+ assert _stored() == {}
+ assert common.list_target_state_owners_sync(app) == {}
diff --git a/rust/cli/src/commands.rs b/rust/cli/src/commands.rs
index 3ebef4ec..fe8c9568 100644
--- a/rust/cli/src/commands.rs
+++ b/rust/cli/src/commands.rs
@@ -3,6 +3,7 @@
use std::path::{Path, PathBuf};
+use cocoindex::StablePath;
use cocoindex::app::DB_PATH_ENV;
use cocoindex::cli::protocol::{AppInfo, Event, Outcome};
use cocoindex::connectors::gdrive;
@@ -264,6 +265,8 @@ pub struct UpdateArgs {
pub full_reprocess: bool,
pub live: bool,
pub preview: bool,
+ /// The `--select` paths: run only these components and those below them.
+ pub select: Vec<StablePath>,
pub build: BuildOpts,
}
@@ -278,6 +281,11 @@ pub async fn update(args: UpdateArgs) -> CliResult<()> {
"--preview and --live cannot be used together.",
));
}
+ if !args.select.is_empty() && args.reset {
+ return Err(CliError::usage(
+ "--select and --reset cannot be used together.",
+ ));
+ }
let target = parse_target(args.target.as_deref())?;
let exe = resolve_exe(&target, &args.build).await?;
@@ -299,6 +307,9 @@ pub async fn update(args: UpdateArgs) -> CliResult<()> {
flags.push(flag.to_string());
}
}
+ for path in &args.select {
+ flags.extend(["--select".to_string(), path.to_string()]);
+ }
let mut renderer = Renderer::new(args.quiet || args.preview, args.live);
let mut previews = Vec::new();
diff --git a/rust/cli/src/main.rs b/rust/cli/src/main.rs
index f005141a..c5e3d338 100644
--- a/rust/cli/src/main.rs
+++ b/rust/cli/src/main.rs
@@ -16,8 +16,10 @@ mod target;
use std::path::PathBuf;
use std::process::ExitCode;
+use std::str::FromStr;
use clap::{Args, Parser, Subcommand};
+use cocoindex::StablePath;
use build::BuildOpts;
use commands::{DropArgs, ShowArgs, UpdateArgs};
@@ -134,6 +136,11 @@ enum Command {
/// Compute target actions without applying them. Prints planned actions.
#[arg(long)]
preview: bool,
+ /// Run only the component at PATH and the components below it; repeat to run several.
+ /// Write PATH as `cocoindex show` prints it, such as '/"process_file"/"docs/a.md"'.
+ /// Other components are not run and not treated as gone.
+ #[arg(long, value_name = "PATH", value_parser = parse_selected_path)]
+ select: Vec<StablePath>,
#[command(flatten)]
build: BuildArgs,
},
@@ -271,6 +278,7 @@ async fn run(cli: Cli) -> CliResult<()> {
full_reprocess,
live,
preview,
+ select,
build,
} => {
commands::update(UpdateArgs {
@@ -281,6 +289,7 @@ async fn run(cli: Cli) -> CliResult<()> {
full_reprocess,
live,
preview,
+ select,
build: build.opts(quiet),
})
.await
@@ -316,6 +325,11 @@ async fn run(cli: Cli) -> CliResult<()> {
}
}
+/// A `--select` path, in the form `cocoindex show` prints.
+fn parse_selected_path(text: &str) -> Result<StablePath, String> {
+ StablePath::from_str(text).map_err(|err| err.to_string())
+}
+
#[tokio::main]
async fn main() -> ExitCode {
let cli = Cli::parse();
@@ -329,3 +343,46 @@ async fn main() -> ExitCode {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
+ Cli::try_parse_from(std::iter::once("cocoindex").chain(args.iter().copied()))
+ }
+
+ #[test]
+ fn update_takes_repeated_select_paths() {
+ let cli = parse(&[
+ "update",
+ "--select",
+ r#"/@process/"a.md""#,
+ "--select",
+ "/3",
+ ])
+ .unwrap();
+ let Command::Update { select, .. } = cli.command else {
+ panic!("not an update");
+ };
+ let shown: Vec<String> = select.iter().map(ToString::to_string).collect();
+ assert_eq!(shown, [r#"/@process/"a.md""#, "/3"]);
+ }
+
+ #[test]
+ fn select_rejects_a_path_not_in_show_form() {
+ let err = parse(&["update", "--select", "process/a.md"])
+ .err()
+ .unwrap();
+ assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
+ assert!(
+ err.to_string().contains("cannot parse component path"),
+ "{err}"
+ );
+ }
+
+ #[test]
+ fn select_is_only_for_update() {
+ assert!(parse(&["drop", "--select", "/3"]).is_err());
+ }
+}
diff --git a/rust/cli/tests/e2e.rs b/rust/cli/tests/e2e.rs
index fea4f5fd..e85aac2f 100644
--- a/rust/cli/tests/e2e.rs
+++ b/rust/cli/tests/e2e.rs
@@ -395,6 +395,13 @@ fn usage_errors() {
assert_eq!(both.status.code(), Some(2));
assert!(stderr(&both).contains("Error: --preview and --reset cannot be used together."));
+ let select_reset = sb.cli(&["update", "--select", "/1", "--reset", FIXTURE]);
+ assert_eq!(select_reset.status.code(), Some(2));
+ assert!(stderr(&select_reset).contains("Error: --select and --reset cannot be used together."));
+ let bad_select = sb.cli(&["update", "--select", "process", FIXTURE]);
+ assert_eq!(bad_select.status.code(), Some(2));
+ assert!(stderr(&bad_select).contains("cannot parse component path"));
+
let missing = sb.cli(&["update", "/definitely/not/here"]);
assert_eq!(missing.status.code(), Some(2));
assert!(stderr(&missing).contains("does not exist"));
diff --git a/rust/core/src/engine/app.rs b/rust/core/src/engine/app.rs
index 08f9e101..48ade8c3 100644
--- a/rust/core/src/engine/app.rs
+++ b/rust/core/src/engine/app.rs
@@ -9,6 +9,7 @@ use crate::engine::live_component::{LIVE_COMPONENT_DRAIN_TIMEOUT_SECS, LiveCompo
use crate::engine::environment::{AppRegistration, Environment};
use crate::engine::runtime::get_runtime;
+use crate::state::component_selector::ComponentSelector;
use crate::state::stable_path::StablePath;
use tokio::sync::watch;
@@ -21,6 +22,9 @@ pub struct AppUpdateOptions {
pub live: bool,
/// Deadline for the root processor and for observing the update result.
pub deadline: DeadlineContext,
+ /// If set, run only the selected components (and what reaches them),
+ /// leaving every other component as it is.
+ pub component_selector: Option<ComponentSelector>,
}
impl Default for AppUpdateOptions {
@@ -29,6 +33,7 @@ impl Default for AppUpdateOptions {
full_reprocess: false,
live: false,
deadline: DeadlineContext::NONE,
+ component_selector: None,
}
}
}
@@ -145,8 +150,15 @@ impl<Prof: EngineProfile> App<Prof> {
// failed" with "the whole update failed", which is too strict;
// tombstones survive for retry on the next reconcile.)
None,
+ // The root always runs: a parent has to run to reach what is
+ // selected below it.
+ ComponentSelector::scoped_to(
+ options.component_selector.as_ref(),
+ self.root_component.stable_path(),
+ ),
)?;
+ let update_refusal = context.update_refusal().clone();
let root_component = self.root_component.clone();
let stats_for_task = processing_stats.clone();
let cancel_token = self.app_ctx().cancellation_token();
@@ -172,7 +184,12 @@ impl<Prof: EngineProfile> App<Prof> {
root_component.wait_until_inactive().await;
}
stats_for_task.notify_terminated();
- result
+ // A change refused for the selector's sake fails the update,
+ // wherever the run that refused it was (see `UpdateRefusal`).
+ match (result, update_refusal.take()) {
+ (Ok(_), Some(refusal)) => Err(Error::client(refusal)),
+ (result, _) => result,
+ }
}
.instrument(span),
);
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index f200989a..c94a606b 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -12,13 +12,15 @@ use crate::engine::context::{
};
use crate::engine::deadline::DeadlineContext;
use crate::engine::execution::{
- OpenDescendantsVerdict, RestoredComponentMemo, cleanup_tombstone, delete_component_memo,
- eager_existence_upsert, post_submit_for_build, submit, update_component_memo_states,
- use_or_invalidate_component_memoization, validate_open_descendants,
+ ChildDeletes, OpenDescendantsVerdict, RestoredComponentMemo, cleanup_tombstone,
+ delete_component_memo, eager_existence_upsert, post_submit_for_build, submit,
+ update_component_memo_states, use_or_invalidate_component_memoization,
+ validate_open_descendants,
};
use crate::engine::profile::EngineProfile;
use crate::engine::stats::ProcessingStats;
use crate::engine::target_state::{TargetStateProvider, TargetStateProviderRegistry};
+use crate::state::component_selector::{ComponentSelection, ComponentSelector, MountDecision};
use crate::state::stable_path::{StablePath, StablePathRef};
use crate::state::stable_path_set::StablePathSet;
use crate::state::target_state_path::{TargetProviderDeps, TargetStatePath};
@@ -328,6 +330,9 @@ pub(crate) struct ComponentRunOutcome {
/// outcome's own list is never what a component reports upward about
/// itself: a component is listed by its parent, not by its own outcome.
open_children: Vec<StablePath>,
+ /// A selector left out a child of the component or of a descendant, so the
+ /// subtree is not up to date: no memo may say it is.
+ left_out_children: bool,
}
impl ComponentRunOutcome {
@@ -354,6 +359,7 @@ impl ComponentRunOutcome {
target_provider_deps,
cannot_skip,
open_children: Vec::new(),
+ left_out_children: false,
}
}
@@ -363,6 +369,7 @@ impl ComponentRunOutcome {
self.target_provider_deps.extend(other.target_provider_deps);
self.cannot_skip |= other.cannot_skip;
self.open_children.extend(other.open_children);
+ self.left_out_children |= other.left_out_children;
}
}
@@ -660,6 +667,11 @@ impl ComponentExecutionHandle {
Self { fut: Box::pin(fut) }
}
+ /// A handle for a mount that does nothing: there is nothing to wait for.
+ pub(crate) fn finished() -> Self {
+ Self::new(async { Ok(()) })
+ }
+
pub async fn ready(self) -> Result<()> {
self.fut.await.into_result()
}
@@ -964,10 +976,15 @@ impl<Prof: EngineProfile> Component<Prof> {
processor: Prof::ComponentProc,
deadline: DeadlineContext,
) -> Result<ComponentMountRunHandle<Prof>> {
+ // An unselected child runs for its value, not to be reprocessed.
+ let selector = parent_ctx.component_selector();
+ let unselected = selector.is_some_and(|selector| {
+ selector.classify(self.stable_path()) == ComponentSelection::Unselected
+ });
let child_ctx = self.new_processor_context_for_build(
Some(parent_ctx),
parent_ctx.processing_stats().clone(),
- parent_ctx.full_reprocess(),
+ parent_ctx.full_reprocess() && !unselected,
parent_ctx.live(), // use_mount inherits live from parent
parent_ctx.preview_collector().cloned(),
parent_ctx.host_ctx().clone(),
@@ -976,6 +993,9 @@ impl<Prof: EngineProfile> Component<Prof> {
// Orphan-delete failures during this child's commit fall
// through to the framework's default `error!` log.
None,
+ // A use_mount child always runs, selected or not: its parent is
+ // waiting for its value.
+ ComponentSelector::scoped_to(selector, self.stable_path()),
)?;
self.run(processor, child_ctx, deadline, deadline).await
}
@@ -988,6 +1008,17 @@ impl<Prof: EngineProfile> Component<Prof> {
processor: Prof::ComponentProc,
on_error: Option<OnError>,
) -> Result<ComponentExecutionHandle> {
+ // An unselected child stops here: not run, and the parent's commit
+ // keeps what the store holds for it (`reconcile_child_existence`).
+ let component_selector =
+ match ComponentSelector::for_mount(parent_ctx.component_selector(), self.stable_path())
+ {
+ MountDecision::Skip => {
+ parent_ctx.record_skipped_mount(self.stable_path())?;
+ return Ok(ComponentExecutionHandle::finished());
+ }
+ MountDecision::Run(component_selector) => component_selector,
+ };
// Store `on_error` on the child's build context too, so the
// commit-phase GC sweep can cascade it to orphan deletes. The
// same handler is also passed to `run_in_background` for the
@@ -1000,6 +1031,7 @@ impl<Prof: EngineProfile> Component<Prof> {
parent_ctx.preview_collector().cloned(),
parent_ctx.host_ctx().clone(),
on_error.clone(),
+ component_selector,
)?;
self.run_in_background(processor, child_ctx, on_error).await
}
@@ -1463,9 +1495,43 @@ impl<Prof: EngineProfile> Component<Prof> {
}
})
.await?;
+ // A child delete that the commit's GC sweep owed failed. Its
+ // tombstone stays under this component, and only a later run
+ // of this component sweeps it again, so count it as a failed
+ // descendant: a build stores no memo (and its ancestors none,
+ // through the outcome), so the next update runs it again; a
+ // delete keeps its own tombstone, so its parent's next sweep
+ // deletes it again. The GC-spawned deletes register with this
+ // component's readiness only after it resolved, so their
+ // outcomes never reach `children_outcome`.
+ if submit_output.child_deletes == ChildDeletes::Pending {
+ children_outcome.has_exception = true;
+ }
let build_output = match ret {
Some(ret) => {
+ // Two cases leave this subtree owing work to a later
+ // run, so a memo would wrongly tell the next update
+ // that it is up to date: a selector left out a child
+ // here or below (the outcome carries this up, so no
+ // ancestor stores one either), or a child delete is
+ // still owed. Drop the stored memo whether or not a
+ // descendant failed: a failure only skips storing a
+ // new one, and under `full_reprocess` the next update
+ // has the same memo key and would hit the old one.
+ children_outcome.left_out_children |=
+ processor_context.left_out_children();
+ if (children_outcome.left_out_children
+ || submit_output.child_deletes == ChildDeletes::Pending)
+ && memo_fp_to_store.is_some()
+ {
+ delete_component_memo(processor_context).await?;
+ self.inner
+ .last_stored_memos
+ .lock()
+ .unwrap()
+ .forget(processor_context.app_store().write_scope());
+ }
if !children_outcome.has_exception {
// Collect initial memo states on cache miss if processor has a state handler.
let memo_states: MemoStatesPayload<Prof> = if let Some(processor) =
@@ -1513,16 +1579,23 @@ impl<Prof: EngineProfile> Component<Prof> {
open_children.sort();
open_children.dedup();
let has_open_descendants = !open_children.is_empty();
- let comp_memo = if let Some((kind_fp, key_fp)) = data_deps.conflict() {
- // The run observed one key in two states: no
- // stored state can validate its output. Store
- // no memo, and drop the previous one: submit has
- // replaced the target states, so an older
- // entry's return value must not be reused.
+ let data_dep_conflict = data_deps.conflict();
+ if let Some((kind_fp, key_fp)) = data_dep_conflict {
debug!(
"{} observed data dependency (kind {kind_fp:?}, key {key_fp:?}) in two states; storing no memo",
processor_context.stable_path()
);
+ }
+ // A run that observed one key in two states stores
+ // no memo and drops the previous one: submit has
+ // replaced the target states, so an older entry's
+ // return value must not be reused, and no stored
+ // state can validate its output. A run that left
+ // out a child stores none either; its old one is
+ // already dropped above.
+ let comp_memo = if children_outcome.left_out_children {
+ None
+ } else if data_dep_conflict.is_some() {
if memo_fp_to_store.is_some() {
delete_component_memo(processor_context).await?;
self.inner
@@ -1575,11 +1648,14 @@ impl<Prof: EngineProfile> Component<Prof> {
})
}
None => {
- // Delete path. When any descendant delete failed,
- // skip `cleanup_tombstone` (symmetric with the
- // build branch skipping `post_submit_for_build`)
- // β€” that preserves the tombstone for the next
- // reconcile to retry.
+ // Delete path. When any descendant delete failed
+ // (including a child delete the GC sweep left
+ // owed, see above), skip `cleanup_tombstone`
+ // (symmetric with the build branch skipping
+ // `post_submit_for_build`) β€” that preserves the
+ // tombstone for the next reconcile to retry, and
+ // with it the way back to the child tombstones
+ // keyed under this component.
//
// We do NOT propagate via `Err` from here.
// Descendant-failure propagation to awaiting
@@ -1669,6 +1745,7 @@ impl<Prof: EngineProfile> Component<Prof> {
preview_collector: Option<PreviewActionCollector<Prof>>,
host_ctx: Arc<Prof::HostCtx>,
on_error: Option<OnError>,
+ component_selector: Option<ComponentSelector>,
) -> Result<ComponentProcessorContext<Prof>> {
let providers = if let Some(parent_ctx) = parent_ctx {
let sub_path = self
@@ -1705,6 +1782,7 @@ impl<Prof: EngineProfile> Component<Prof> {
live,
on_error,
preview_collector,
+ component_selector,
),
))
}
@@ -1754,6 +1832,8 @@ mod tests {
ChildHandling, TargetActionSink, TargetActionSinkKeeper, TargetActionWithChildSlot,
TargetHandler, TargetReconcileOutput, TargetStateProvider, TargetStateProviderRegistry,
};
+ use crate::inspect::db_inspect::StablePathNodeType;
+ use crate::state::component_selector::ComponentSelector;
use crate::state::stable_path::{StableKey, StablePath};
use crate::state_store::StorageSettings;
use crate::state_store::test_support::hold_write_batch;
@@ -1909,11 +1989,13 @@ mod tests {
/// Applies nothing but counts its `apply` calls. With `children`, it
/// provides a `CountingHandler` counting into the given counter for every
/// child-bearing action, in the given way: from `child_handlers` or by
- /// fulfilling the slots in `apply`.
+ /// fulfilling the slots in `apply`. With `failing`, `apply` fails (after
+ /// counting) while the flag is set.
#[derive(Default)]
struct NoopSink {
apply_calls: Arc<AtomicUsize>,
children: Option<(ChildHandling, Arc<AtomicUsize>)>,
+ failing: Option<Arc<AtomicBool>>,
}
impl NoopSink {
@@ -1923,6 +2005,7 @@ mod tests {
let sink = Self {
apply_calls: apply_calls.clone(),
children: Some((child_handling, child_reconcile_calls.clone())),
+ failing: None,
};
(sink, apply_calls, child_reconcile_calls)
}
@@ -1934,6 +2017,7 @@ mod tests {
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject: false,
change_only: false,
+ plans_deletes: false,
}
}
}
@@ -1962,6 +2046,11 @@ mod tests {
actions: &[TargetActionWithChildSlot<TestProfile>],
) -> crate::prelude::Result<()> {
self.apply_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(failing) = &self.failing
+ && failing.load(Ordering::SeqCst)
+ {
+ cocoindex_utils::client_bail!("injected sink failure");
+ }
for slot in actions.iter().filter_map(|(_, slot)| slot.as_ref()) {
slot.fulfill(self.child_handler())?;
}
@@ -1969,10 +2058,10 @@ mod tests {
}
}
- /// Plans an action for every desired target state (none for a deletion)
- /// and counts its `reconcile` calls. With `reject`, it rejects every
- /// desired target state instead, as a connector rejecting a declared
- /// value does.
+ /// Plans an action for every desired target state (for a deletion, only
+ /// with `plans_deletes`) and counts its `reconcile` calls. With `reject`,
+ /// it rejects every desired target state instead, as a connector
+ /// rejecting a declared value does.
struct CountingHandler {
reconcile_calls: Arc<AtomicUsize>,
sink: TargetActionSinkKeeper<TestProfile>,
@@ -1981,6 +2070,7 @@ mod tests {
/// nothing for a desired target state the stored records already
/// hold, and a deletion for one no longer declared.
change_only: bool,
+ plans_deletes: bool,
}
impl TargetHandler<TestProfile> for CountingHandler {
@@ -2009,10 +2099,13 @@ mod tests {
child_invalidation: None,
}));
}
- Ok(desired_target_state.map(|_| TargetReconcileOutput {
+ if desired_target_state.is_none() && !self.plans_deletes {
+ return Ok(None);
+ }
+ Ok(Some(TargetReconcileOutput {
action: (),
sink: self.sink.clone(),
- tracking_record: Some(TestData(Vec::new())),
+ tracking_record: desired_target_state.map(|_| TestData(Vec::new())),
child_invalidation: None,
}))
}
@@ -2377,6 +2470,7 @@ mod tests {
ctx.live(),
None,
None,
+ None,
),
);
// No token is free and the root's is lent, yet the
@@ -2517,6 +2611,7 @@ mod tests {
ctx.live(),
None,
None,
+ None,
),
);
let second = child
@@ -2828,6 +2923,7 @@ mod tests {
ctx.live(),
None,
None,
+ None,
),
);
let second = child
@@ -2950,6 +3046,7 @@ mod tests {
sink: container_sink,
reject: false,
change_only: false,
+ plans_deletes: false,
},
)?;
*child_provider.lock().unwrap() = Some(declare_target_state_with_child(
@@ -3101,11 +3198,13 @@ mod tests {
Some(collector),
Arc::new(()),
None,
+ None,
)
.unwrap();
let live_path = StablePath::root().concat_part(StableKey::Str(Arc::from("live")));
let MountLiveResult { controller, .. } =
mount_live_prepare(&ctx, &FnCallContext::default(), live_path.clone(), false)
+ .unwrap()
.unwrap()
.complete()
.await
@@ -3192,6 +3291,7 @@ mod tests {
Some(collector.clone()),
Arc::new(()),
None,
+ None,
)
.unwrap();
let provider = register_root_target_state_provider(
@@ -3202,6 +3302,7 @@ mod tests {
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject: false,
change_only: false,
+ plans_deletes: false,
},
)
.unwrap();
@@ -3225,6 +3326,7 @@ mod tests {
Some(collector.clone()),
Arc::new(()),
None,
+ None,
)
.unwrap();
declare_target_state(
@@ -3400,6 +3502,7 @@ mod tests {
let sink = TargetActionSinkKeeper::new(NoopSink {
apply_calls: apply_calls.clone(),
children: None,
+ failing: None,
});
let reconcile_calls = reconcile_calls.clone();
Box::pin(async move {
@@ -3411,6 +3514,7 @@ mod tests {
sink,
reject: false,
change_only: true,
+ plans_deletes: false,
},
)?;
for key in [0, 1] {
@@ -3469,6 +3573,7 @@ mod tests {
let sink = TargetActionSinkKeeper::new(NoopSink {
apply_calls: apply_calls.clone(),
children: None,
+ failing: None,
});
Box::pin(async move {
let provider = register_root_target_state_provider(
@@ -3479,6 +3584,7 @@ mod tests {
sink,
reject: false,
change_only: true,
+ plans_deletes: false,
},
)?;
for key in keys {
@@ -3635,6 +3741,7 @@ mod tests {
None,
Arc::new(()),
None,
+ None,
)
.unwrap();
let reconcile_calls = Arc::new(AtomicUsize::new(0));
@@ -3646,6 +3753,7 @@ mod tests {
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject,
change_only: false,
+ plans_deletes: false,
},
)
.unwrap();
@@ -3692,4 +3800,401 @@ mod tests {
"the accepting precommit runs again to commit without the rejected one"
);
}
+
+ /// A root whose memo key is `run`: it mounts each of `children`, each of
+ /// which records its path in `ran` when its body runs. A child's stored memo
+ /// stays reusable, so that only a miss runs it.
+ fn mounting_root(
+ run: &str,
+ children: &'static [&'static str],
+ ran: &Arc<Mutex<Vec<String>>>,
+ ) -> TestProcessor {
+ let ran = ran.clone();
+ TestProcessor::new(
+ "root",
+ Fingerprint::from(&run).unwrap(),
+ Arc::new(AtomicBool::new(false)),
+ false,
+ )
+ .with_on_process(Arc::new(move |ctx| {
+ let ran = ran.clone();
+ Box::pin(async move {
+ for child in children {
+ let ran = ran.clone();
+ let processor = TestProcessor::new(
+ child,
+ Fingerprint::from(child).unwrap(),
+ Arc::new(AtomicBool::new(false)),
+ false,
+ )
+ .with_reusable_memo_states()
+ .with_on_process(Arc::new(move |ctx| {
+ ran.lock().unwrap().push(ctx.stable_path().to_string());
+ Box::pin(async { Ok(TestData(b"child".to_vec())) })
+ }));
+ ctx.component()
+ .mount_child(&FnCallContext::new(true), key_path(ctx.component(), child))?
+ .mount(&ctx, processor, None)
+ .await?;
+ }
+ Ok(TestData(b"root".to_vec()))
+ })
+ }))
+ }
+
+ async fn run_update(app: &App<TestProfile>, root: TestProcessor, options: AppUpdateOptions) {
+ let (handle, _) = app.update(root, options, Arc::new(()), None).unwrap();
+ handle.result().await.unwrap();
+ }
+
+ fn select(key: &str) -> Option<ComponentSelector> {
+ Some(ComponentSelector::new([
+ StablePath::root().concat_part(StableKey::Str(Arc::from(key)))
+ ]))
+ }
+
+ /// Not creating the tombstone in the first place: the child's row, tracking
+ /// record and memo stay byte for byte, whether the root skipped its mount
+ /// ("a", still mounted) or no longer mounts it ("b").
+ #[tokio::test]
+ async fn an_unselected_component_is_not_run_and_keeps_what_the_store_holds_for_it() {
+ let (app, _dir) = test_app("selector_unselected").await;
+ let ran = Arc::new(Mutex::new(Vec::new()));
+ run_update(
+ &app,
+ mounting_root("full", &["a", "b", "c"], &ran),
+ AppUpdateOptions::default(),
+ )
+ .await;
+ assert_eq!(ran.lock().unwrap().len(), 3);
+ ran.lock().unwrap().clear();
+
+ let app_store = app.app_ctx().persisting_app_store();
+ let path = |key: &str| StablePath::root().concat_part(StableKey::Str(Arc::from(key)));
+ let stored = |key: &'static str| {
+ let app_store = app_store.clone();
+ let path = path(key);
+ async move {
+ (
+ app_store.read_tracking_info(&path).await.unwrap(),
+ app_store.read_component_memo(&path).await.unwrap(),
+ )
+ }
+ };
+ let (a_before, b_before) = (stored("a").await, stored("b").await);
+ assert!(a_before.0.is_some() && a_before.1.is_some());
+ assert!(b_before.0.is_some() && b_before.1.is_some());
+
+ // A full reprocess, so that a child the selector lets through would run.
+ run_update(
+ &app,
+ mounting_root("selective", &["a", "c"], &ran),
+ AppUpdateOptions {
+ full_reprocess: true,
+ component_selector: select("c"),
+ ..AppUpdateOptions::default()
+ },
+ )
+ .await;
+ assert_eq!(*ran.lock().unwrap(), vec![path("c").to_string()]);
+
+ assert_eq!(stored("a").await, a_before);
+ assert_eq!(stored("b").await, b_before);
+ let key = StableKey::Str(Arc::from("b"));
+ assert_eq!(
+ app_store
+ .read_path_node_type(StablePath::root().as_ref(), &key)
+ .await
+ .unwrap(),
+ Some(StablePathNodeType::Component)
+ );
+ assert!(
+ app_store
+ .list_tombstones(&StablePath::root())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+
+ // A run the selector does not limit sees "b" gone.
+ run_update(
+ &app,
+ mounting_root("full again", &["a", "c"], &ran),
+ AppUpdateOptions::default(),
+ )
+ .await;
+ assert_eq!(
+ app_store
+ .read_path_node_type(StablePath::root().as_ref(), &key)
+ .await
+ .unwrap(),
+ None
+ );
+ }
+
+ /// A memo says the subtree is up to date, which a run that left out a child
+ /// cannot say. It stores none, and retires the one it ran over: a later
+ /// update must run the component to reach that child.
+ #[tokio::test]
+ async fn a_run_that_left_out_a_child_stores_no_memo_and_drops_the_stored_one() {
+ let (app, _dir) = test_app("selector_memo").await;
+ let ran = Arc::new(Mutex::new(Vec::new()));
+ let app_store = app.app_ctx().persisting_app_store().clone();
+ let root_memo = || {
+ let app_store = app_store.clone();
+ async move {
+ app_store
+ .read_component_memo(&StablePath::root())
+ .await
+ .unwrap()
+ }
+ };
+
+ run_update(
+ &app,
+ mounting_root("same key", &["a", "b"], &ran),
+ AppUpdateOptions::default(),
+ )
+ .await;
+ assert!(root_memo().await.is_some());
+
+ run_update(
+ &app,
+ mounting_root("same key", &["a", "b"], &ran),
+ AppUpdateOptions {
+ full_reprocess: true,
+ component_selector: select("a"),
+ ..AppUpdateOptions::default()
+ },
+ )
+ .await;
+ assert!(root_memo().await.is_none());
+
+ // Nothing left out, though under a selector: the run is complete.
+ let key_path_of =
+ |key: &str| StablePath::root().concat_part(StableKey::Str(Arc::from(key)));
+ run_update(
+ &app,
+ mounting_root("same key", &["a", "b"], &ran),
+ AppUpdateOptions {
+ full_reprocess: true,
+ component_selector: Some(ComponentSelector::new([
+ key_path_of("a"),
+ key_path_of("b"),
+ ])),
+ ..AppUpdateOptions::default()
+ },
+ )
+ .await;
+ assert!(root_memo().await.is_some());
+
+ // "b" is on disk, no longer mounted, and not selected: it is left out.
+ run_update(
+ &app,
+ mounting_root("same key", &["a"], &ran),
+ AppUpdateOptions {
+ full_reprocess: true,
+ component_selector: select("a"),
+ ..AppUpdateOptions::default()
+ },
+ )
+ .await;
+ assert!(root_memo().await.is_none());
+
+ // Selecting the root is no limit: the run is an ordinary one.
+ run_update(
+ &app,
+ mounting_root("same key", &["a", "b"], &ran),
+ AppUpdateOptions {
+ component_selector: Some(ComponentSelector::new([StablePath::root()])),
+ ..AppUpdateOptions::default()
+ },
+ )
+ .await;
+ assert!(root_memo().await.is_some());
+ }
+
+ #[tokio::test]
+ async fn an_unselected_live_component_does_not_mount() {
+ let (app, _dir) = test_app("selector_live").await;
+ let contents_before = app_store_contents(&app).await;
+ let ctx = Component::new(app.app_ctx().clone(), StablePath::root(), None)
+ .new_processor_context_for_build(
+ None,
+ ProcessingStats::new(),
+ false,
+ false,
+ None,
+ Arc::new(()),
+ None,
+ select("selected"),
+ )
+ .unwrap();
+ let live_path = |key: &str| key_path(ctx.component(), key);
+ assert!(
+ mount_live_prepare(
+ &ctx,
+ &FnCallContext::default(),
+ live_path("unselected"),
+ false
+ )
+ .unwrap()
+ .is_none()
+ );
+ assert!(app_store_contents(&app).await == contents_before);
+ assert!(
+ mount_live_prepare(
+ &ctx,
+ &FnCallContext::default(),
+ live_path("selected"),
+ false
+ )
+ .unwrap()
+ .is_some()
+ );
+ }
+
+ /// The root mounts `m` while `mount` is set; `m` declares nothing and
+ /// mounts `m/l`, which declares one target state through a handler that
+ /// plans its delete, applied by `sink`.
+ fn nested_root(sink: TargetActionSinkKeeper<TestProfile>, mount: bool) -> TestProcessor {
+ fn new_processor(name: &str) -> TestProcessor {
+ TestProcessor::new(
+ name,
+ Fingerprint::from(&format!("nested_root/{name}")).unwrap(),
+ Arc::new(AtomicBool::new(false)),
+ false,
+ )
+ }
+ type ProviderSlot = Arc<Mutex<Option<TargetStateProvider<TestProfile>>>>;
+ let provider: ProviderSlot = Default::default();
+ let leaf = {
+ let provider = provider.clone();
+ new_processor("leaf").with_on_process(Arc::new(move |ctx| {
+ let provider = provider.lock().unwrap().clone().unwrap();
+ Box::pin(async move {
+ declare_target_state(
+ &ctx,
+ &FnCallContext::default(),
+ provider,
+ StableKey::Int(0),
+ (),
+ )?;
+ Ok(TestData(b"leaf".to_vec()))
+ })
+ }))
+ };
+ let leaf = Mutex::new(Some(leaf));
+ let mid = new_processor("mid").with_on_process(Arc::new(move |ctx| {
+ let leaf = leaf.lock().unwrap().take().unwrap();
+ Box::pin(async move {
+ let child = ctx
+ .component()
+ .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "l"))?;
+ child
+ .use_mount(&ctx, leaf, DeadlineContext::NONE)
+ .await?
+ .result(Some(&ctx))
+ .await?;
+ Ok(TestData(b"mid".to_vec()))
+ })
+ }));
+ let mid = Mutex::new(Some(mid));
+ new_processor("root").with_on_process(Arc::new(move |ctx| {
+ let mid = mid.lock().unwrap().take().unwrap();
+ let provider = provider.clone();
+ let sink = sink.clone();
+ Box::pin(async move {
+ *provider.lock().unwrap() = Some(register_root_target_state_provider(
+ &ctx,
+ "target".to_string(),
+ CountingHandler {
+ reconcile_calls: Arc::new(AtomicUsize::new(0)),
+ sink,
+ reject: false,
+ plans_deletes: true,
+ change_only: false,
+ },
+ )?);
+ if mount {
+ let child = ctx
+ .component()
+ .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "m"))?;
+ child
+ .use_mount(&ctx, mid, DeadlineContext::NONE)
+ .await?
+ .result(Some(&ctx))
+ .await?;
+ }
+ Ok(TestData(b"ret".to_vec()))
+ })
+ }))
+ }
+
+ /// A child delete that fails under a deleted parent keeps the parent's
+ /// tombstone too, so the next update deletes the parent again, and with
+ /// it the child. Were the parent's tombstone cleaned, the child's, keyed
+ /// under the gone parent, would never be swept again.
+ #[tokio::test]
+ async fn a_failed_delete_under_a_deleted_parent_is_retried() {
+ let (app, _dir) = test_app("failed_delete_under_deleted_parent").await;
+ let failing = Arc::new(AtomicBool::new(false));
+ let sink = NoopSink {
+ failing: Some(failing.clone()),
+ ..Default::default()
+ };
+ let apply_calls = sink.apply_calls.clone();
+ let sink = TargetActionSinkKeeper::new(sink);
+ let update = |mount: bool| {
+ let (handle, _) = app
+ .update(
+ nested_root(sink.clone(), mount),
+ AppUpdateOptions::default(),
+ Arc::new(()),
+ None,
+ )
+ .unwrap();
+ handle.result()
+ };
+ let app_store = app.app_ctx().persisting_app_store();
+ let m = StablePath::root().concat_part(StableKey::Str(Arc::from("m")));
+ let l = StablePath::root().concat_part(StableKey::Str(Arc::from("l")));
+
+ update(true).await.unwrap();
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 1, "the upsert");
+
+ // Unmount `m`; the delete of `m/l`'s target state fails. With no
+ // handler installed, the update still succeeds.
+ failing.store(true, Ordering::SeqCst);
+ update(false).await.unwrap();
+ failing.store(false, Ordering::SeqCst);
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 2, "the failed delete");
+ assert_eq!(app_store.list_tombstones(&m).await.unwrap(), vec![l]);
+ assert_eq!(
+ app_store
+ .list_tombstones(&StablePath::root())
+ .await
+ .unwrap(),
+ vec![m.clone()],
+ "`m` keeps its tombstone while its child's delete is owed"
+ );
+
+ update(false).await.unwrap();
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 3, "the retried delete");
+ assert!(app_store.list_tombstones(&m).await.unwrap().is_empty());
+ assert!(
+ app_store
+ .list_tombstones(&StablePath::root())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+
+ update(false).await.unwrap();
+ assert_eq!(
+ apply_calls.load(Ordering::SeqCst),
+ 3,
+ "nothing left to delete"
+ );
+ }
}
diff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rs
index 2cd7aeed..907f400b 100644
--- a/rust/core/src/engine/context.rs
+++ b/rust/core/src/engine/context.rs
@@ -12,11 +12,12 @@ use crate::engine::stats::ProcessingStats;
use crate::engine::target_state::{TargetStateProvider, TargetStateProviderRegistry};
use crate::prelude::*;
+use crate::state::component_selector::{ComponentSelection, ComponentSelector};
use crate::state::stable_path::StableKey;
pub(crate) static TARGET_ID_KEY: LazyLock<StableKey> =
LazyLock::new(|| StableKey::Symbol("cocoindex/_internal/target_id".into()));
-use crate::state::stable_path_set::ChildStablePathSet;
+use crate::state::stable_path_set::{ChildStablePathSet, StablePathSet};
use crate::state::target_state_path::{
TargetProviderDeps, TargetStatePath, TargetStateProviderGeneration,
};
@@ -799,6 +800,30 @@ pub(crate) struct ComponentBuildContext<Prof: EngineProfile> {
/// `mount_inner_live`'s self-built parent context).
pub on_error: Option<crate::engine::component::OnError>,
pub preview_collector: Option<PreviewActionCollector<Prof>>,
+ /// The selector this run is under, scoped by
+ /// [`ComponentSelector::scoped_to`]. See
+ /// [`ComponentProcessorContext::component_selector`].
+ pub component_selector: Option<ComponentSelector>,
+}
+
+/// A change a run refused because the update's selector leaves out components
+/// it would affect: the rebuild or removal of a container target state whose
+/// children the update does not run. The run fails, and the update fails with
+/// the same error when it ends, wherever the run was: a background component's
+/// failure alone only reaches its error handler, and a caller that previews a
+/// slice and then updates it must see the refusal from both.
+#[derive(Clone, Default)]
+pub(crate) struct UpdateRefusal(Arc<parking_lot::Mutex<Option<String>>>);
+
+impl UpdateRefusal {
+ /// Keep the first refusal: it is the one the update reports.
+ pub(crate) fn record(&self, message: &str) {
+ self.0.lock().get_or_insert_with(|| message.to_string());
+ }
+
+ pub(crate) fn take(&self) -> Option<String> {
+ self.0.lock().take()
+ }
}
pub(crate) struct ComponentDeleteContext<Prof: EngineProfile> {
@@ -837,6 +862,7 @@ impl<Prof: EngineProfile> ComponentProcessingAction<Prof> {
live: bool,
on_error: Option<crate::engine::component::OnError>,
preview_collector: Option<PreviewActionCollector<Prof>>,
+ component_selector: Option<ComponentSelector>,
) -> Self {
Self::Build(ComponentBuildContext {
state: Mutex::new(Some(ComponentBuildingState {
@@ -852,6 +878,7 @@ impl<Prof: EngineProfile> ComponentProcessingAction<Prof> {
live,
on_error,
preview_collector,
+ component_selector,
})
}
@@ -879,6 +906,16 @@ struct ComponentProcessorContextInner<Prof: EngineProfile> {
/// see [`crate::engine::admission`].
admission: Admission,
+ /// Where a run of this update records that it refused a change for the
+ /// selector's sake (see [`UpdateRefusal`]). One per update: every context
+ /// of the update shares it, live components' runs included.
+ update_refusal: UpdateRefusal,
+
+ /// This run's selector left out a child it mounted or one the store holds,
+ /// so this subtree is not up to date when the run ends. Set by a mount, by
+ /// the commit's existence reconciliation and by its GC sweep.
+ left_out_children: Arc<AtomicBool>,
+
/// Logic fingerprints accumulated from function calls and child components.
logic_deps: Mutex<HashSet<Fingerprint>>,
@@ -961,6 +998,7 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
host_ctx,
processing_action,
app_store,
+ None,
)
}
@@ -969,6 +1007,7 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
/// It borrows its in-flight token from `lender`, the run that mounted the
/// live component, for as long as that run lasts, and reads and writes
/// the store through `app_store`, that run's handle.
+ #[allow(clippy::too_many_arguments)]
pub(crate) fn new_borrowing_from(
component: Component<Prof>,
lender: Option<Lender>,
@@ -977,6 +1016,7 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
host_ctx: Arc<Prof::HostCtx>,
processing_action: ComponentProcessingAction<Prof>,
app_store: AppStore,
+ update_refusal: UpdateRefusal,
) -> Self {
Self::from_parts(
component,
@@ -986,9 +1026,11 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
host_ctx,
processing_action,
app_store,
+ Some(update_refusal),
)
}
+ #[allow(clippy::too_many_arguments)]
fn from_parts(
component: Component<Prof>,
parent_context: Option<ComponentProcessorContext<Prof>>,
@@ -997,7 +1039,13 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
host_ctx: Arc<Prof::HostCtx>,
processing_action: ComponentProcessingAction<Prof>,
app_store: AppStore,
+ update_refusal: Option<UpdateRefusal>,
) -> Self {
+ let update_refusal = match (&parent_context, update_refusal) {
+ (Some(parent), _) => parent.update_refusal().clone(),
+ (None, Some(update_refusal)) => update_refusal,
+ (None, None) => UpdateRefusal::default(),
+ };
let operation_generation = match &parent_context {
Some(parent) => parent.operation_generation(),
None => component.app_ctx().next_operation_generation(),
@@ -1010,6 +1058,8 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
app_store,
operation_generation,
admission,
+ update_refusal,
+ left_out_children: Arc::new(AtomicBool::new(false)),
logic_deps: Mutex::new(HashSet::new()),
data_deps: Mutex::new(DataDeps::default()),
target_provider_deps: Mutex::new(TargetProviderDeps::new()),
@@ -1356,6 +1406,96 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
}
}
+ /// The selector this run is under. A delete has none: it is reached only
+ /// for a path a selector covers, and removes everything below.
+ pub(crate) fn component_selector(&self) -> Option<&ComponentSelector> {
+ match self.processing_state() {
+ ComponentProcessingAction::Build(build_ctx) => build_ctx.component_selector.as_ref(),
+ ComponentProcessingAction::Delete(_) => None,
+ }
+ }
+
+ /// The update this run belongs to leaves some components out, wherever this
+ /// run is: inside a selected subtree too. A change this run makes can reach
+ /// those components through what they share, as a container target state.
+ /// A delete does not count: the component it removes is selected and gone,
+ /// so nothing can declare under its containers any more.
+ pub(crate) fn update_leaves_out_components(&self) -> bool {
+ self.component_selector()
+ .is_some_and(|selector| !selector.selects_everything())
+ }
+
+ pub(crate) fn update_refusal(&self) -> &UpdateRefusal {
+ &self.inner.update_refusal
+ }
+
+ pub(crate) fn mark_left_out_children(&self) {
+ self.inner.left_out_children.store(true, Ordering::SeqCst);
+ }
+
+ pub(crate) fn left_out_children(&self) -> bool {
+ self.inner.left_out_children.load(Ordering::SeqCst)
+ }
+
+ pub(crate) fn left_out_children_flag(&self) -> Arc<AtomicBool> {
+ self.inner.left_out_children.clone()
+ }
+
+ /// Record a mount at `path` that the selector leaves out. It counts as a
+ /// mount of this run, so a second mount at the path is an error as usual,
+ /// and a directory it lies under counts as declared.
+ pub(crate) fn record_skipped_mount(&self, path: &StablePath) -> Result<()> {
+ self.mark_left_out_children();
+ let sub_path = path.as_ref().strip_parent(self.stable_path().as_ref())?;
+ self.update_building_state(|building_state| {
+ building_state
+ .child_path_set
+ .add_child(sub_path, StablePathSet::Skipped)
+ })
+ }
+
+ /// Whether the selector leaves out a mount at `path`, without recording
+ /// anything: for a host that prepares a mount it would then hand to
+ /// [`Component::mount`], which records the skip itself.
+ pub fn selector_leaves_out(&self, path: &StablePath) -> bool {
+ self.component_selector()
+ .is_some_and(|selector| selector.classify(path) == ComponentSelection::Unselected)
+ }
+
+ /// Whether the selector leaves out a mount at `path`, recording it if so.
+ /// For a host that wants to know before it prepares the mount: building a
+ /// processor can run user code, and costs per item. [`Component::mount`]
+ /// and `mount_live_prepare` decide alike for one that does not ask.
+ pub fn skips_mount(&self, fn_ctx: &FnCallContext, path: &StablePath) -> Result<bool> {
+ let Some(selector) = self.component_selector() else {
+ return Ok(false);
+ };
+ if selector.classify(path) != ComponentSelection::Unselected {
+ return Ok(false);
+ }
+ // Even a skipped child rules out memoizing the function that mounted it.
+ fn_ctx.update(|inner| inner.has_child_components = true);
+ self.record_skipped_mount(path)?;
+ Ok(true)
+ }
+
+ /// The keys a mount of one component per key under `path` (`mount_each`)
+ /// can run: `None` for every key, else only these, which may be none. A
+ /// host that gets a list need not list its source in full: it can read
+ /// just these keys, and with an empty list it need not read at all. The
+ /// run records that it leaves the other keys out, as
+ /// [`Self::skips_mount`] records one skip.
+ pub fn mount_each_keys(
+ &self,
+ fn_ctx: &FnCallContext,
+ path: &StablePath,
+ ) -> Option<Vec<StableKey>> {
+ let keys = self.component_selector()?.selected_child_keys(path)?;
+ fn_ctx.update(|inner| inner.has_child_components = true);
+ self.mark_left_out_children();
+ Some(keys)
+ }
+
pub fn live(&self) -> bool {
match &self.inner.processing_action {
ComponentProcessingAction::Build(build_ctx) => build_ctx.live,
diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rs
index 1b1cea87..f478a392 100644
--- a/rust/core/src/engine/execution.rs
+++ b/rust/core/src/engine/execution.rs
@@ -1,5 +1,7 @@
use crate::engine::component::ComponentProcessor;
+use crate::engine::context::UpdateRefusal;
use crate::prelude::*;
+use crate::state::component_selector::ComponentSelector;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque, btree_map};
@@ -675,7 +677,7 @@ impl<Prof: EngineProfile> Committer<Prof> {
fn_memos: FnMemoCache<Prof>,
user_states: UserStateCache<Prof::FunctionData>,
tracking: PrecommittedTracking,
- ) -> Result<()> {
+ ) -> Result<ChildDeletes> {
self.commit_writes(child_existence, fn_memos, user_states, tracking)
.await?;
self.launch_child_component_gc().await
@@ -758,18 +760,28 @@ impl<Prof: EngineProfile> Committer<Prof> {
) -> ExistenceReconciler {
let app_store = self.app_store.clone();
let component_path = self.component_path.clone();
+ let selector = self.component_ctx.component_selector().cloned();
+ let left_out_children = self.component_ctx.left_out_children_flag();
Box::new(move |wtxn| {
let app_store = app_store.clone();
let component_path = component_path.clone();
let declared_children = declared_children.clone();
+ let selector = selector.clone();
+ let left_out_children = left_out_children.clone();
Box::pin(async move {
- reconcile_child_existence(
+ let kept_unselected = reconcile_child_existence(
wtxn,
&app_store,
&component_path,
declared_children.as_deref(),
+ selector.as_ref(),
)
- .await
+ .await?;
+ // Only ever set: a re-run of this body finds the same children.
+ if kept_unselected {
+ left_out_children.store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ Ok(())
})
})
}
@@ -840,8 +852,9 @@ impl<Prof: EngineProfile> Committer<Prof> {
/// Phase 5 GC: snapshot-read tombstones and spawn child delete
/// operations. Outside the commit txn β€” tombstones are durable and the
- /// GC sweep is idempotent.
- async fn launch_child_component_gc(&self) -> Result<()> {
+ /// GC sweep is idempotent. Returns whether every tombstone is gone once
+ /// the deletes finish (see [`ChildDeletes`]).
+ async fn launch_child_component_gc(&self) -> Result<ChildDeletes> {
// Cascade the parent's on_error to descendant orphan deletes.
//
// - Delete-mode parent (recursive cascade from `App.drop()`'s
@@ -863,9 +876,20 @@ impl<Prof: EngineProfile> Committer<Prof> {
// Standalone snapshot read β€” `list_tombstones` opens its own
// fresh `RoTxn` internally.
let tombstones = self.app_store.list_tombstones(&self.component_path).await?;
+ if tombstones.is_empty() {
+ return Ok(ChildDeletes::Done);
+ }
let mut handles = Vec::with_capacity(tombstones.len());
+ // A tombstone left by an earlier run for a component this run's selector
+ // does not cover stays for a run that covers it: the deletion would
+ // touch that component's target states.
+ let selector = self.component_ctx.component_selector();
for relative_path in tombstones {
let stable_path = self.component_path.concat(relative_path.as_ref());
+ if selector.is_some_and(|selector| !selector.covers(&stable_path)) {
+ self.component_ctx.mark_left_out_children();
+ continue;
+ }
let component = self.component_ctx.component().get_child(stable_path);
let delete_ctx = component.new_processor_context_for_delete(
self.target_states_providers.clone(),
@@ -887,10 +911,43 @@ impl<Prof: EngineProfile> Committer<Prof> {
for handle in handles {
handle.ready().await?;
}
- Ok(())
+ // A child delete that failed keeps its tombstone, and with no handler
+ // (or one that swallows) its handle still resolves `Ok`; the store is
+ // what tells. Each child delete cleans its tombstone before its
+ // handle resolves, so one still listed that this sweep was to delete
+ // is a delete still owed. One the selector kept is not this run's
+ // to delete: the run reports leaving it out, not a failure.
+ let owed = self
+ .app_store
+ .list_tombstones(&self.component_path)
+ .await?
+ .into_iter()
+ .any(|relative_path| {
+ let stable_path = self.component_path.concat(relative_path.as_ref());
+ selector.is_none_or(|selector| selector.covers(&stable_path))
+ });
+ Ok(if owed {
+ ChildDeletes::Pending
+ } else {
+ ChildDeletes::Done
+ })
}
}
+/// What a commit's Phase 5 GC sweep left owed, for the run that committed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ChildDeletes {
+ /// The run leaves no child delete owed: the sweep deleted every child it
+ /// found, or found none. A run that sweeps nothing reports it too: a
+ /// preview, which persists nothing, and the delete of a component that
+ /// was mounted again, whose own builds sweep its tombstones.
+ Done,
+ /// A child delete failed, and its tombstone stays under the component.
+ /// Only a later commit of this same component sweeps it again, so the
+ /// run must make sure one happens: see `Component::execute_once`.
+ Pending,
+}
+
struct SinkInput<Prof: EngineProfile> {
actions: Vec<TargetActionWithChildSlot<Prof>>,
/// For a [`ChildHandling::Factory`] sink: child providers awaiting a
@@ -1092,6 +1149,47 @@ enum PreCommitOutcome<Prof: EngineProfile> {
PendingRetry,
}
+/// A change to a container target state takes the target states of all its
+/// children with it, and the selector leaves some of them unrun: nothing would
+/// declare theirs again. Refused before anything is applied, so that a selective
+/// update can't delete the data of the components it leaves alone. A preview
+/// with the same selector refuses it alike: it shows what the update would do.
+fn bail_container_change_under_selector(
+ update_refusal: &UpdateRefusal,
+ container: &str,
+ stable_path: &StablePath,
+ change: &str,
+) -> Result<()> {
+ let message = format!(
+ "container target state {container}, declared by the component at {stable_path}, \
+ needs a {change}, which can affect child components that component_selector leaves \
+ out. A full update is needed: run it without component_selector"
+ );
+ update_refusal.record(&message);
+ Err(Error::client(message))
+}
+
+/// Whether a target state below `container` belongs to a component the
+/// update does not run. A change to the container that drops or converts its
+/// children's data must then wait for a full update; when every owner runs,
+/// the update declares the children again, as a plain one does.
+async fn container_has_left_out_children(
+ app_store: &AppStore,
+ wtxn: &mut WriteTxn<'_>,
+ container: &TargetStatePath,
+ selector: Option<&ComponentSelector>,
+ stable_path: &StablePath,
+) -> Result<bool> {
+ let Some(selector) = selector else {
+ return Ok(false);
+ };
+ app_store
+ .any_owner_below_in_txn(wtxn, container, |owner| {
+ owner != stable_path && !selector.update_runs(owner)
+ })
+ .await
+}
+
/// Captures bundle shared into the precommit callback closure. Every
/// field is `O(1)` to clone (Arc-internal or persistent data structure)
/// so the body's per-call `Arc::clone(&captures)` is cheap. The callback
@@ -1105,6 +1203,8 @@ struct PreCommitCaptures<Prof: EngineProfile> {
stable_path: StablePath,
processor_name: Option<Arc<str>>,
contained_target_state_paths: Arc<HashSet<TargetStatePath>>,
+ update_refusal: UpdateRefusal,
+ selector: Option<ComponentSelector>,
target_states_providers: rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
declared_target_states:
Arc<tokio::sync::Mutex<BTreeMap<TargetStatePath, DeclaredTargetState<Prof>>>>,
@@ -1175,6 +1275,9 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
process_token: u128,
stable_path: &StablePath,
full_reprocess: bool,
+ limited_by_selector: bool,
+ update_refusal: &UpdateRefusal,
+ selector: Option<&ComponentSelector>,
processor_name: Option<&str>,
contained_target_state_paths: &HashSet<TargetStatePath>,
target_states_providers: &rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
@@ -1459,6 +1562,50 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
.as_ref()
.and_then(|item| item.provider_generation.clone());
+ // A rebuild drops the container's data, so it is always refused.
+ // A lossy change is refused only if the container's record
+ // changed: a reconcile that could not trust the previous state
+ // (`full_reprocess`, a pending state) reports one for a
+ // container that is just as it was, and that converts nothing.
+ let refused = limited_by_selector
+ && child_provider.is_some()
+ && prev_item.is_some()
+ && match recon_output.child_invalidation {
+ Some(ChildInvalidation::Destructive) => true,
+ Some(ChildInvalidation::Lossy) => {
+ match (&prev_item, &recon_output.tracking_record) {
+ (Some(item), Some(record)) => {
+ let record = record.to_bytes()?;
+ item.states.is_empty()
+ || !item
+ .states
+ .iter()
+ .all(|(_, s)| s.as_ref() == Some(record.as_ref()))
+ }
+ _ => true,
+ }
+ }
+ None => false,
+ };
+ if refused
+ && let Some(container) = &child_provider
+ && container_has_left_out_children(
+ app_store,
+ wtxn,
+ target_state_path,
+ selector,
+ stable_path,
+ )
+ .await?
+ {
+ bail_container_change_under_selector(
+ update_refusal,
+ &container.display_name(),
+ stable_path,
+ "rebuild",
+ )?;
+ }
+
if let Some(child_provider) = &child_provider {
// A state created this pass mints a fresh generation for
// its children, not the shared default: tracking left
@@ -1605,6 +1752,14 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
.filter_map(|(_, s)| s.as_ref())
.map(Prof::TargetStateTrackingRecord::from_bytes)
.collect::<Result<Vec<_>>>()?;
+ // Named before `reconcile` takes the key; only a container needs it.
+ let container_name =
+ (limited_by_selector && item.provider_generation.is_some()).then(|| {
+ format!(
+ "{}/{target_state_key}",
+ target_states_provider.display_name()
+ )
+ });
let recon_output = target_states_provider
.handler()
@@ -1615,6 +1770,23 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
})?
.reconcile(target_state_key, None, &prev_states, prev_may_be_missing)?;
if let Some(recon_output) = recon_output {
+ if let Some(container_name) = &container_name
+ && container_has_left_out_children(
+ app_store,
+ wtxn,
+ &target_state_path_with_pid.target_state_path,
+ selector,
+ stable_path,
+ )
+ .await?
+ {
+ bail_container_change_under_selector(
+ update_refusal,
+ container_name,
+ stable_path,
+ "removal",
+ )?;
+ }
actions_by_sinks
.entry(recon_output.sink)
.or_default()
@@ -1704,6 +1876,19 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
.filter(|(_, owner)| owner.modified)
.map(|(path, owner)| Ok((path.clone(), rmp_serde::to_vec_named(&owner.tracking)?)))
.collect::<Result<_>>()?;
+ // An old owner this update does not run keeps a memo that says it declares
+ // the target state: a later update would reuse it, declare nothing, and
+ // leave the state to whoever took it. Its memo, and each ancestor's, must
+ // go. An owner the update runs settles it itself, as in a plain update.
+ let preempted_owners_left_out: Vec<StablePath> = selector
+ .map(|selector| {
+ preempted_owner_updates
+ .keys()
+ .filter(|owner| !selector.update_covers(owner))
+ .cloned()
+ .collect()
+ })
+ .unwrap_or_default();
// Provider-generation updates: buffered into the output, applied
// by `submit()` after the precommit txn commits β€” so a re-run of this
@@ -1721,6 +1906,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
self_path: stable_path.clone(),
new_tracking_info: new_tracking_info_bytes,
preempted_owner_updates,
+ preempted_owners_left_out,
segment_names,
},
})
@@ -1729,6 +1915,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
pub(crate) struct SubmitOutput<Prof: EngineProfile> {
pub built_target_states_providers: Option<TargetStateProviderRegistry<Prof>>,
pub touched_previous_states: bool,
+ pub child_deletes: ChildDeletes,
}
#[instrument(name = "submit", skip_all)]
@@ -1788,6 +1975,9 @@ pub(crate) async fn submit<Prof: EngineProfile>(
let comp_mode = comp_ctx.mode();
let full_reprocess = comp_ctx.full_reprocess();
+ let limited_by_selector = comp_ctx.update_leaves_out_components();
+ let update_refusal = comp_ctx.update_refusal().clone();
+ let selector = comp_ctx.component_selector().cloned();
let process_token = comp_ctx.app_ctx().env().process_token();
let mut pending_fulfillments: Vec<(TargetStateProvider<Prof>, Prof::TargetHdl)> = Vec::new();
@@ -1822,6 +2012,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
return Ok(SubmitOutput {
built_target_states_providers: None,
touched_previous_states: false,
+ child_deletes: ChildDeletes::Done,
});
}
Some(db_schema::StablePathNodeType::Directory) => {
@@ -1875,6 +2066,8 @@ pub(crate) async fn submit<Prof: EngineProfile>(
stable_path: stable_path.clone(),
processor_name: processor_name_owned.clone(),
contained_target_state_paths: Arc::clone(&contained_target_state_paths),
+ update_refusal: update_refusal.clone(),
+ selector: selector.clone(),
target_states_providers: target_states_providers.clone(),
declared_target_states: Arc::clone(&declared_target_states),
});
@@ -1945,6 +2138,9 @@ pub(crate) async fn submit<Prof: EngineProfile>(
process_token,
&c.stable_path,
full_reprocess,
+ limited_by_selector,
+ &c.update_refusal,
+ c.selector.as_ref(),
c.processor_name.as_deref(),
&c.contained_target_state_paths,
&c.target_states_providers,
@@ -2075,6 +2271,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
return Ok(SubmitOutput {
built_target_states_providers,
touched_previous_states,
+ child_deletes: ChildDeletes::Done,
});
}
@@ -2115,16 +2312,19 @@ pub(crate) async fn submit<Prof: EngineProfile>(
// Commit. `AppStore::commit` is a normal trait method β€” no
// session handoff needed.
let committer = Committer::new(comp_ctx, target_states_providers)?;
- if let Err(e) = committer
+ let child_deletes = match committer
.commit(child_existence, fn_memos, user_states, tracking)
.await
{
- // The commit txn either committed or rolled back before
- // returning Err β€” either way the stage marker may still be
- // live, so clear it via the retry helper.
- cleanup_pending_token(comp_ctx, process_token).await;
- return Err(e);
- }
+ Ok(child_deletes) => child_deletes,
+ Err(e) => {
+ // The commit txn either committed or rolled back before
+ // returning Err β€” either way the stage marker may still be
+ // live, so clear it via the retry helper.
+ cleanup_pending_token(comp_ctx, process_token).await;
+ return Err(e);
+ }
+ };
// Fulfill child handlers and register their attachment providers.
// Done after commit so the immutable borrow on providers is released.
@@ -2137,6 +2337,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
Ok(SubmitOutput {
built_target_states_providers,
touched_previous_states,
+ child_deletes,
})
}
diff --git a/rust/core/src/engine/live_component.rs b/rust/core/src/engine/live_component.rs
index f869ff82..067db1c8 100644
--- a/rust/core/src/engine/live_component.rs
+++ b/rust/core/src/engine/live_component.rs
@@ -1,3 +1,4 @@
+use crate::engine::context::UpdateRefusal;
use std::collections::HashMap;
use std::future::Future;
@@ -13,6 +14,7 @@ use crate::engine::profile::EngineProfile;
use crate::engine::stats::ProcessingStats;
use crate::engine::target_state::TargetStateProvider;
use crate::prelude::*;
+use crate::state::component_selector::{ComponentSelector, MountDecision};
use crate::state::stable_path::{StableKey, StablePath};
use crate::state::target_state_path::TargetStatePath;
use crate::state_store::AppStore;
@@ -43,22 +45,43 @@ pub struct MountLivePending<Prof: EngineProfile> {
parent_ctx: ComponentProcessorContext<Prof>,
providers: rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
live: bool,
+ component_selector: Option<ComponentSelector>,
}
/// Mount a live component. Split into two phases:
/// - `prepare` (sync): registers the child component, borrows fn_ctx
/// - `complete` (async): cancels existing live state, creates controller
+///
+/// `None` when the running update's selector leaves the component out: it does
+/// not start, and any incarnation already running keeps running.
pub fn mount_live_prepare<Prof: EngineProfile>(
parent_ctx: &ComponentProcessorContext<Prof>,
fn_ctx: &FnCallContext,
child_stable_path: StablePath,
live: bool,
-) -> Result<MountLivePending<Prof>> {
+) -> Result<Option<MountLivePending<Prof>>> {
// 1. Mount (or get existing) child component.
let child = parent_ctx
.component()
.mount_child(fn_ctx, child_stable_path.clone())?;
+ let component_selector =
+ match ComponentSelector::for_mount(parent_ctx.component_selector(), &child_stable_path) {
+ MountDecision::Skip => {
+ parent_ctx.record_skipped_mount(&child_stable_path)?;
+ return Ok(None);
+ }
+ MountDecision::Run(component_selector) => component_selector,
+ };
+ // A live component reports nothing up (see `MountLivePending::complete`), so
+ // what its runs leave out is taken as left out here.
+ if component_selector
+ .as_ref()
+ .is_some_and(ComponentSelector::can_leave_out_children)
+ {
+ parent_ctx.mark_left_out_children();
+ }
+
// Register the child in the parent's child_path_set and get providers
// in a single lock acquisition.
let sub_path = child_stable_path
@@ -76,12 +99,13 @@ pub fn mount_live_prepare<Prof: EngineProfile>(
.clone())
})?;
- Ok(MountLivePending {
+ Ok(Some(MountLivePending {
child,
parent_ctx: parent_ctx.clone(),
providers,
live,
- })
+ component_selector,
+ }))
}
impl<Prof: EngineProfile> MountLivePending<Prof> {
@@ -92,18 +116,24 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {
parent_ctx,
providers,
live,
+ component_selector,
} = self;
- // 2. A catch-up (non-live) mount β€” a catch-up or preview update run
- // while a live update of the same app is running β€” leaves a
- // running live incarnation at this path alone: replacing it would
- // stop the live update's watcher with no notice to anyone. The
- // catch-up incarnation runs beside it instead (its runs of this
- // component serialize with the live one's on the component's
- // build permit) and is not installed as the component's live
- // state, so a later mount still finds, and replaces, the live one.
- // Any other existing incarnation is cancelled and drained, with a
- // 30s timeout.
+ // 2. An existing incarnation at this path is left alone, and the new
+ // one runs beside it, uninstalled, in two cases:
+ // - A run that applies nothing (a preview), or runs this component
+ // only to reach selected paths below (a selective update), does
+ // not stand in for what is already running: a preview from a UI
+ // must not end the live update of the app it looks at.
+ // - A catch-up (non-live) mount β€” a catch-up or preview update run
+ // while a live update of the same app is running β€” leaves a
+ // running live incarnation alone: replacing it would stop the
+ // live update's watcher with no notice to anyone.
+ // An incarnation running beside a running live one takes turns
+ // with it (see `LiveComponentState::beside`) and is not installed
+ // as the component's live state, so a later mount still finds, and
+ // replaces, the live one. Any other existing incarnation is
+ // cancelled and drained, with a 30s timeout.
//
// Without a timeout, a prior incarnation wedged in non-yielding
// synchronous Python compute would hold the parent's
@@ -115,12 +145,17 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {
// `update_full` reconciles. This trades quiescence for liveness β€”
// same trade `App::drop_app` makes (see "drop_app" contract in
// specs/live_component/design.md).
- let existing_state = child.live_state();
- let beside_running_live = !live
- && existing_state
+ let replaces_running = parent_ctx.preview_collector().is_none()
+ && !component_selector
.as_ref()
- .is_some_and(|state| state.is_running_live());
- if let Some(existing_state) = existing_state.as_ref().filter(|_| !beside_running_live) {
+ .is_some_and(ComponentSelector::can_leave_out_children);
+ let existing_state = child.live_state();
+ let existing_runs_live = existing_state
+ .as_ref()
+ .is_some_and(|state| state.is_running_live());
+ let leaves_existing =
+ existing_state.is_some() && (!replaces_running || (!live && existing_runs_live));
+ if let Some(existing_state) = existing_state.as_ref().filter(|_| !leaves_existing) {
let drain_fut = existing_state.cancel_and_drain();
if tokio::time::timeout(
std::time::Duration::from_secs(LIVE_COMPONENT_DRAIN_TIMEOUT_SECS),
@@ -174,7 +209,7 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {
let cancellation_token = parent_ctx.app_ctx().cancellation_token().child_token();
// 5. Create LiveComponentState.
- let beside = if beside_running_live {
+ let beside = if leaves_existing && existing_runs_live {
existing_state.clone()
} else {
None
@@ -198,9 +233,9 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {
// owner exists would die on `upgrade()`. With the strong owner held
// by `child.live_state`, the Weak in `live_components` upgrades for
// the lifetime of the live component (or until cancel-and-drain
- // releases the strong ref). An incarnation running beside a live one
- // (step 2) is anchored by its controller alone.
- if !beside_running_live {
+ // releases the strong ref). An incarnation running beside an existing
+ // one (step 2) is anchored by its controller alone.
+ if !leaves_existing {
child.set_live_state(state.clone());
}
parent_ctx
@@ -216,6 +251,8 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {
parent_ctx.full_reprocess(),
live,
parent_ctx.preview_collector().cloned(),
+ component_selector,
+ parent_ctx.update_refusal().clone(),
parent_ctx.app_store().clone(),
providers,
parent_ctx.admission().lender().clone(),
@@ -542,6 +579,19 @@ pub struct LiveComponentController<Prof: EngineProfile> {
/// The mounting run's preview collector: in a preview, this component's
/// runs preview too rather than apply.
preview_collector: Option<PreviewActionCollector<Prof>>,
+ /// The selector this component's runs are under, as in
+ /// [`ComponentProcessorContext::component_selector`]. It holds for the whole
+ /// update, live events included.
+ component_selector: Option<ComponentSelector>,
+ /// The mounting update's refusal slot (see [`UpdateRefusal`]), shared by
+ /// this component's runs.
+ update_refusal: UpdateRefusal,
+ /// What a run under a selector wrote through
+ /// [`Self::write_committed_state`]: it keeps it for its own reads, and does
+ /// not persist it. Such a value says something about the whole component
+ /// (a full scan is done, a logic version is current), which a run that left
+ /// children out has not earned.
+ selective_committed_state: Arc<parking_lot::Mutex<HashMap<StableKey, Vec<u8>>>>,
/// The mounting run's store handle, which persists nothing in a preview
/// (see [`ComponentProcessorContext::app_store`]).
app_store: AppStore,
@@ -573,6 +623,8 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
full_reprocess: bool,
live: bool,
preview_collector: Option<PreviewActionCollector<Prof>>,
+ component_selector: Option<ComponentSelector>,
+ update_refusal: UpdateRefusal,
app_store: AppStore,
providers: rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
lender: Lender,
@@ -586,6 +638,9 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
full_reprocess,
live,
preview_collector,
+ component_selector,
+ update_refusal,
+ selective_committed_state: Default::default(),
app_store,
providers,
lender,
@@ -618,6 +673,9 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
/// set-reduces, and not participating in any commit, so it is safe in the
/// non-committing `process_live` context.
pub async fn read_committed_state(&self, key: &StableKey) -> Result<Option<Vec<u8>>> {
+ if let Some(value) = self.selective_committed_state.lock().get(key) {
+ return Ok(Some(value.clone()));
+ }
self.app_store
.read_user_state(
self.component.stable_path(),
@@ -639,6 +697,16 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
/// value for the run instead, so a later [`Self::read_committed_state`]
/// reads it back.
pub async fn write_committed_state(&self, key: &StableKey, value: Vec<u8>) -> Result<()> {
+ if self
+ .component_selector
+ .as_ref()
+ .is_some_and(ComponentSelector::can_leave_out_children)
+ {
+ self.selective_committed_state
+ .lock()
+ .insert(key.clone(), value);
+ return Ok(());
+ }
self.app_store
.write_user_state_standalone(
self.component.stable_path(),
@@ -706,8 +774,10 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
self.live,
on_error.clone(),
self.preview_collector.clone(),
+ self.component_selector.clone(),
),
self.app_store.clone(),
+ self.update_refusal.clone(),
);
let handle = self
@@ -721,6 +791,16 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
Ok(())
}
+ /// The update's selector leaves out a mount at `subpath`. [`Self::update`]
+ /// and [`Self::mount_inner_live`] act on it themselves; a host may ask first,
+ /// to avoid preparing the mount.
+ pub fn skips_subpath(&self, subpath: &StablePath) -> bool {
+ matches!(
+ ComponentSelector::for_mount(self.component_selector.as_ref(), subpath),
+ MountDecision::Skip
+ )
+ }
+
/// Mount a child component incrementally. Same-subpath rapid calls are
/// coalesced β€” only the most-recently-queued op runs; older ones
/// resolve as `Superseded`. Returns immediately after dispatching;
@@ -735,6 +815,9 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
processor: Prof::ComponentProc,
on_error: Option<OnError>,
) -> Result<ComponentExecutionHandle> {
+ if self.skips_subpath(&subpath) {
+ return Ok(ComponentExecutionHandle::finished());
+ }
self.dispatch(
subpath,
Op::Update {
@@ -759,11 +842,20 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
/// A preview deletes nothing: like the deletes of the components an update
/// no longer mounts, a live delete is not previewed (the tombstone never
/// persists, and the drain task skips the op).
+ ///
+ /// Under a selector, only a covered path is deleted: an ancestor of a
+ /// selected path holds unselected descendants too (the same call as
+ /// `reconcile_child_existence` makes for a child no longer declared).
pub async fn delete(
&self,
subpath: StablePath,
on_error: Option<OnError>,
) -> Result<ComponentExecutionHandle> {
+ if let Some(selector) = &self.component_selector
+ && !selector.covers(&subpath)
+ {
+ return Ok(ComponentExecutionHandle::finished());
+ }
// Synchronously remove the existence entry and write a tombstone,
// matching the prior implementation's contract. The drain task does
// it again when the op runs (see `run_op`).
@@ -836,6 +928,8 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
let full_reprocess = self.full_reprocess;
let live = self.live;
let preview_collector = self.preview_collector.clone();
+ let component_selector = self.component_selector.clone();
+ let update_refusal = self.update_refusal.clone();
let app_store = self.app_store.clone();
let lender = self.lender.clone();
let share = self.share.clone();
@@ -855,6 +949,8 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
full_reprocess,
live,
preview_collector,
+ component_selector,
+ update_refusal,
app_store,
lender,
share,
@@ -969,7 +1065,13 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
/// Cancellation contract: returns `Err(<cancelled>)` if the controller's
/// token fires before or during the lock acquire / mount. The Python
/// wrapper maps this to `MountOutcome.cancelled` if needed.
- pub async fn mount_inner_live(&self, child_path: StablePath) -> Result<MountLiveResult<Prof>> {
+ ///
+ /// `None` when the selector leaves the child out (see
+ /// [`mount_live_prepare`]).
+ pub async fn mount_inner_live(
+ &self,
+ child_path: StablePath,
+ ) -> Result<Option<MountLiveResult<Prof>>> {
// Cancellable lock acquisition: shutdown breaks out within one poll.
let _full_guard = tokio::select! {
biased;
@@ -1004,8 +1106,10 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
self.live,
None,
self.preview_collector.clone(),
+ self.component_selector.clone(),
),
self.app_store.clone(),
+ self.update_refusal.clone(),
);
let fn_ctx = FnCallContext::default();
@@ -1013,10 +1117,12 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {
// next `update_full`'s tombstone scan can see this child and
// reconcile its target states on parent re-runs that don't
// re-issue this `operator.update` call.
- let pending = mount_live_prepare(&parent_ctx, &fn_ctx, child_path, self.live)?;
+ let Some(pending) = mount_live_prepare(&parent_ctx, &fn_ctx, child_path, self.live)? else {
+ return Ok(None);
+ };
let result = pending.complete().await?;
- Ok(result)
+ Ok(Some(result))
// _full_guard drops here, releasing update_full_lock.
}
}
@@ -1141,6 +1247,8 @@ async fn drain_task_body<Prof: EngineProfile>(
full_reprocess: bool,
live: bool,
preview_collector: Option<PreviewActionCollector<Prof>>,
+ component_selector: Option<ComponentSelector>,
+ update_refusal: UpdateRefusal,
app_store: AppStore,
lender: Lender,
share: LiveShare,
@@ -1211,6 +1319,8 @@ async fn drain_task_body<Prof: EngineProfile>(
full_reprocess,
live,
&preview_collector,
+ component_selector.as_ref(),
+ &update_refusal,
&app_store,
&lender,
&share,
@@ -1312,6 +1422,8 @@ async fn run_op<Prof: EngineProfile>(
full_reprocess: bool,
live: bool,
preview_collector: &Option<PreviewActionCollector<Prof>>,
+ component_selector: Option<&ComponentSelector>,
+ update_refusal: &UpdateRefusal,
app_store: &AppStore,
lender: &Lender,
share: &LiveShare,
@@ -1338,8 +1450,11 @@ async fn run_op<Prof: EngineProfile>(
live,
on_error.clone(),
preview_collector.clone(),
+ // `update` already skipped an unselected subpath.
+ ComponentSelector::scoped_to(component_selector, subpath),
),
app_store.clone(),
+ update_refusal.clone(),
);
let inner_handle = child
.run_in_background(processor, context, on_error)
@@ -1369,6 +1484,7 @@ async fn run_op<Prof: EngineProfile>(
host_ctx.clone(),
ComponentProcessingAction::new_delete(providers.clone(), on_error),
app_store.clone(),
+ update_refusal.clone(),
);
let inner_handle = child.delete(context)?;
inner_handle.ready().await
diff --git a/rust/core/src/state/component_selector.rs b/rust/core/src/state/component_selector.rs
new file mode 100644
index 00000000..d834c25d
--- /dev/null
+++ b/rust/core/src/state/component_selector.rs
@@ -0,0 +1,308 @@
+//! Which components one update runs: sliced execution.
+
+use std::collections::HashMap;
+
+use crate::prelude::*;
+use crate::state::stable_path::{StableKey, StablePath};
+
+/// The components an update runs, as a set of component paths. Selecting a path
+/// selects its whole subtree, so one path names one component or everything
+/// below a prefix alike.
+///
+/// A tree with a `HashMap` per level, so that classifying a path costs one
+/// lookup per path part however many paths are selected (a page of an
+/// observability UI selects tens of them).
+#[derive(Debug, Clone)]
+pub struct ComponentSelector {
+ root: Arc<SelectorNode>,
+ /// This view belongs to a run inside a selected subtree: every path below
+ /// it is selected. The update as a whole may still leave components out.
+ within_selected: bool,
+}
+
+#[derive(Debug, Default)]
+struct SelectorNode {
+ selected: bool,
+ children: HashMap<StableKey, SelectorNode>,
+}
+
+/// How a selector relates to one path.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ComponentSelection {
+ /// The path, or a prefix of it, is selected: it runs as without a selector.
+ Selected,
+ /// A selected path lies strictly below: it runs to reach that path, and
+ /// the selector still applies to what it mounts.
+ AncestorOfSelected,
+ /// Nothing about the path is selected.
+ Unselected,
+}
+
+/// What mounting a component comes to under the selector of the mounting run.
+pub(crate) enum MountDecision {
+ /// The component is unselected: no run, and nothing about it changes.
+ Skip,
+ /// The component runs, under this selector (see
+ /// [`ComponentSelector::scoped_to`]).
+ Run(Option<ComponentSelector>),
+}
+
+impl ComponentSelector {
+ pub fn new(paths: impl IntoIterator<Item = StablePath>) -> Self {
+ let mut root = SelectorNode::default();
+ for path in paths {
+ let mut node = &mut root;
+ for key in path.iter() {
+ if node.selected {
+ break;
+ }
+ node = node.children.entry(key.clone()).or_default();
+ }
+ // Selecting a path covers what was selected below it.
+ node.selected = true;
+ node.children = HashMap::new();
+ }
+ Self {
+ root: Arc::new(root),
+ within_selected: false,
+ }
+ }
+
+ pub fn classify(&self, path: &StablePath) -> ComponentSelection {
+ if self.within_selected {
+ return ComponentSelection::Selected;
+ }
+ let mut node = &*self.root;
+ for key in path.iter() {
+ if node.selected {
+ return ComponentSelection::Selected;
+ }
+ let Some(child) = node.children.get(key) else {
+ return ComponentSelection::Unselected;
+ };
+ node = child;
+ }
+ if node.selected {
+ ComponentSelection::Selected
+ } else {
+ ComponentSelection::AncestorOfSelected
+ }
+ }
+
+ /// The keys of the children of `path` that are selected or lead to a
+ /// selected path: `None` when `path` is selected, so every child is.
+ pub fn selected_child_keys(&self, path: &StablePath) -> Option<Vec<StableKey>> {
+ if self.within_selected {
+ return None;
+ }
+ let mut node = &*self.root;
+ for key in path.iter() {
+ if node.selected {
+ return None;
+ }
+ let Some(child) = node.children.get(key) else {
+ return Some(Vec::new());
+ };
+ node = child;
+ }
+ if node.selected {
+ return None;
+ }
+ Some(node.children.keys().cloned().collect())
+ }
+
+ /// The path is selected, directly or through a prefix.
+ pub fn covers(&self, path: &StablePath) -> bool {
+ self.classify(path) == ComponentSelection::Selected
+ }
+
+ /// The update covers `path`, wherever this view's run is. Unlike
+ /// [`Self::covers`], a view inside a selected subtree answers for paths
+ /// outside it too.
+ pub(crate) fn update_covers(&self, path: &StablePath) -> bool {
+ Self {
+ root: self.root.clone(),
+ within_selected: false,
+ }
+ .covers(path)
+ }
+
+ /// The update runs the component at `path`, wherever this view's run is:
+ /// it is selected or leads to a selected path. A `use_mount` child that
+ /// runs anyway is not counted.
+ pub(crate) fn update_runs(&self, path: &StablePath) -> bool {
+ Self {
+ root: self.root.clone(),
+ within_selected: false,
+ }
+ .classify(path)
+ != ComponentSelection::Unselected
+ }
+
+ /// A run under this view can leave out something it mounts. False inside a
+ /// selected subtree, from where on the run is an ordinary one. That never
+ /// comes back on the way down, so the ancestors of a run with this true
+ /// have it true too.
+ pub(crate) fn can_leave_out_children(&self) -> bool {
+ !self.within_selected
+ }
+
+ /// The whole app is selected, so the update is a plain one.
+ pub(crate) fn selects_everything(&self) -> bool {
+ self.root.selected
+ }
+
+ /// The selector a run of the component at `path` is under, given the
+ /// selector of the run that started it.
+ pub(crate) fn scoped_to(selector: Option<&Self>, path: &StablePath) -> Option<Self> {
+ selector.map(|selector| Self {
+ root: selector.root.clone(),
+ within_selected: selector.covers(path),
+ })
+ }
+
+ /// See [`MountDecision`]. A child the parent waits for a value from
+ /// (`use_mount`, the root) always runs, so it takes [`Self::scoped_to`].
+ pub(crate) fn for_mount(selector: Option<&Self>, path: &StablePath) -> MountDecision {
+ if selector
+ .is_some_and(|selector| selector.classify(path) == ComponentSelection::Unselected)
+ {
+ return MountDecision::Skip;
+ }
+ MountDecision::Run(Self::scoped_to(selector, path))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn path(parts: &[StableKey]) -> StablePath {
+ parts.iter().fold(StablePath::root(), |path, part| {
+ path.concat_part(part.clone())
+ })
+ }
+
+ fn s(value: &str) -> StableKey {
+ StableKey::Str(Arc::from(value))
+ }
+
+ #[test]
+ fn exact_path_selects_itself_and_its_subtree_and_runs_its_ancestors() {
+ let selector = ComponentSelector::new([path(&[s("process"), s("a")])]);
+ assert_eq!(
+ selector.classify(&StablePath::root()),
+ ComponentSelection::AncestorOfSelected
+ );
+ assert_eq!(
+ selector.classify(&path(&[s("process")])),
+ ComponentSelection::AncestorOfSelected
+ );
+ assert_eq!(
+ selector.classify(&path(&[s("process"), s("a")])),
+ ComponentSelection::Selected
+ );
+ assert_eq!(
+ selector.classify(&path(&[s("process"), s("a"), s("chunk")])),
+ ComponentSelection::Selected
+ );
+ assert_eq!(
+ selector.classify(&path(&[s("process"), s("b")])),
+ ComponentSelection::Unselected
+ );
+ assert_eq!(
+ selector.classify(&path(&[s("other")])),
+ ComponentSelection::Unselected
+ );
+ }
+
+ #[test]
+ fn selected_child_keys_lists_what_leads_to_a_selected_path() {
+ let selector = ComponentSelector::new([
+ path(&[s("process"), s("a"), s("chunk")]),
+ path(&[s("process"), s("b")]),
+ path(&[s("other")]),
+ ]);
+ let mut keys = selector
+ .selected_child_keys(&path(&[s("process")]))
+ .unwrap();
+ keys.sort();
+ assert_eq!(keys, vec![s("a"), s("b")]);
+ assert_eq!(selector.selected_child_keys(&path(&[s("other")])), None);
+ assert_eq!(
+ selector.selected_child_keys(&path(&[s("other"), s("x")])),
+ None
+ );
+ assert_eq!(
+ selector.selected_child_keys(&path(&[s("none")])),
+ Some(Vec::new())
+ );
+ let within = ComponentSelector::scoped_to(Some(&selector), &path(&[s("other")])).unwrap();
+ assert_eq!(within.selected_child_keys(&path(&[s("process")])), None);
+ }
+
+ #[test]
+ fn a_prefix_covers_paths_selected_below_it_in_either_order() {
+ let prefix = path(&[s("process")]);
+ let below = path(&[s("process"), s("a")]);
+ for paths in [
+ vec![prefix.clone(), below.clone()],
+ vec![below.clone(), prefix.clone()],
+ ] {
+ let selector = ComponentSelector::new(paths);
+ assert!(selector.covers(&prefix));
+ assert!(selector.covers(&below));
+ assert!(selector.covers(&path(&[s("process"), s("b")])));
+ assert!(!selector.covers(&path(&[s("other")])));
+ }
+ }
+
+ #[test]
+ fn the_root_path_selects_everything_and_no_path_selects_nothing() {
+ let everything = ComponentSelector::new([StablePath::root()]);
+ assert!(everything.covers(&StablePath::root()));
+ assert!(everything.covers(&path(&[s("any"), s("thing")])));
+
+ let nothing = ComponentSelector::new([]);
+ assert_eq!(
+ nothing.classify(&StablePath::root()),
+ ComponentSelection::AncestorOfSelected
+ );
+ assert_eq!(
+ nothing.classify(&path(&[s("any")])),
+ ComponentSelection::Unselected
+ );
+ }
+
+ #[test]
+ fn keys_match_by_type_not_by_how_they_print() {
+ let tuple = StableKey::Array(Arc::from(vec![s("a"), StableKey::Int(1)]));
+ let selector = ComponentSelector::new([
+ path(&[StableKey::Int(1)]),
+ path(&[StableKey::Bool(true)]),
+ path(std::slice::from_ref(&tuple)),
+ path(&[StableKey::Symbol(Arc::from("process"))]),
+ ]);
+ assert!(selector.covers(&path(&[StableKey::Int(1)])));
+ assert!(selector.covers(&path(&[StableKey::Bool(true)])));
+ assert!(selector.covers(&path(&[tuple])));
+ assert!(selector.covers(&path(&[StableKey::Symbol(Arc::from("process"))])));
+ assert!(!selector.covers(&path(&[s("1")])));
+ assert!(!selector.covers(&path(&[s("true")])));
+ assert!(!selector.covers(&path(&[s("process")])));
+ }
+
+ #[test]
+ fn scoping_inside_a_selected_subtree_covers_everything_below() {
+ let selector = ComponentSelector::new([path(&[s("process"), s("a")])]);
+ let scoped =
+ |target: &StablePath| ComponentSelector::scoped_to(Some(&selector), target).unwrap();
+ assert!(scoped(&path(&[s("process")])).can_leave_out_children());
+ assert!(scoped(&path(&[s("other")])).can_leave_out_children());
+ let inside = scoped(&path(&[s("process"), s("a")]));
+ assert!(!inside.can_leave_out_children());
+ assert!(inside.covers(&path(&[s("process"), s("a"), s("x")])));
+ assert!(!inside.selects_everything());
+ assert!(ComponentSelector::scoped_to(None, &path(&[s("process")])).is_none());
+ }
+}
diff --git a/rust/core/src/state/mod.rs b/rust/core/src/state/mod.rs
index 223d17f5..ee15d301 100644
--- a/rust/core/src/state/mod.rs
+++ b/rust/core/src/state/mod.rs
@@ -1,3 +1,4 @@
+pub mod component_selector;
pub mod stable_path;
pub mod target_state_path;
diff --git a/rust/core/src/state/stable_path.rs b/rust/core/src/state/stable_path.rs
index 1daffe76..36d41200 100644
--- a/rust/core/src/state/stable_path.rs
+++ b/rust/core/src/state/stable_path.rs
@@ -254,12 +254,45 @@ impl<'a> std::fmt::Display for StablePathRef<'a> {
}
for part in self.0.iter() {
f.write_str("/")?;
- part.fmt(f)?;
+ fmt_path_part(part, f)?;
}
Ok(())
}
}
+/// A part of a path as [`StableKey`]'s `Display` writes it, except that a
+/// symbol that is not a plain name is quoted (`@"cocoindex/mount_target"`),
+/// so that the path parses back.
+fn fmt_path_part(key: &StableKey, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match key {
+ StableKey::Symbol(s) if !is_bare_symbol(s) => {
+ f.write_str("@\"")?;
+ f.write_str(s.escape_default().to_string().as_str())?;
+ f.write_char('"')
+ }
+ StableKey::Array(a) => {
+ f.write_char('[')?;
+ for (i, part) in a.iter().enumerate() {
+ if i > 0 {
+ f.write_str(",")?;
+ }
+ fmt_path_part(part, f)?;
+ }
+ f.write_char(']')
+ }
+ _ => std::fmt::Display::fmt(key, f),
+ }
+}
+
+/// A symbol that a path writes as `@name`: printable ASCII with none of the
+/// characters that end a key or start a quote.
+fn is_bare_symbol(s: &str) -> bool {
+ !s.is_empty()
+ && !s.starts_with('"')
+ && s.chars()
+ .all(|c| c.is_ascii_graphic() && !matches!(c, '/' | ',' | '[' | ']' | '\\'))
+}
+
impl<'a> From<&'a [StableKey]> for StablePathRef<'a> {
fn from(value: &'a [StableKey]) -> Self {
StablePathRef(value)
@@ -341,6 +374,213 @@ impl StablePath {
}
}
+impl std::str::FromStr for StablePath {
+ type Err = Error;
+
+ /// Parses a path as [`Display`](std::fmt::Display) writes it, such as
+ /// `/@process/"docs/a.md"`: the text `cocoindex show` prints.
+ fn from_str(text: &str) -> Result<Self> {
+ let mut parser = KeyParser {
+ text,
+ chars: text.char_indices().peekable(),
+ };
+ let mut parts = Vec::new();
+ if text == "/" {
+ return Ok(StablePath::root());
+ }
+ while parser.chars.peek().is_some() {
+ parser.expect('/')?;
+ parts.push(parser.key()?);
+ }
+ if parts.is_empty() {
+ client_bail!("a component path starts with `/`, such as `/@process/\"a.md\"`");
+ }
+ Ok(StablePath(parts.into()))
+ }
+}
+
+struct KeyParser<'t> {
+ text: &'t str,
+ chars: std::iter::Peekable<std::str::CharIndices<'t>>,
+}
+
+impl<'t> KeyParser<'t> {
+ fn error(&mut self, what: &str) -> Error {
+ let at = self.chars.peek().map_or(self.text.len(), |(i, _)| *i);
+ client_error!(
+ "cannot parse component path `{}` at offset {at}: {what}. Write it as \
+ `cocoindex show` prints it, such as `/@process/\"a.md\"`",
+ self.text
+ )
+ }
+
+ fn expect(&mut self, c: char) -> Result<()> {
+ match self.chars.peek() {
+ Some((_, next)) if *next == c => {
+ self.chars.next();
+ Ok(())
+ }
+ _ => Err(self.error(&format!("expected `{c}`"))),
+ }
+ }
+
+ fn key(&mut self) -> Result<StableKey> {
+ match self.chars.peek().map(|(_, c)| *c) {
+ Some('"') => {
+ self.chars.next();
+ let s = self.quoted(false)?;
+ Ok(StableKey::Str(Arc::from(s)))
+ }
+ Some('b') if self.text[self.offset() + 1..].starts_with('"') => {
+ self.chars.next();
+ self.chars.next();
+ let s = self.quoted(true)?;
+ Ok(StableKey::Bytes(s.chars().map(|c| c as u8).collect()))
+ }
+ Some('[') => {
+ self.chars.next();
+ let mut items = Vec::new();
+ if self.chars.peek().is_some_and(|(_, c)| *c == ']') {
+ self.chars.next();
+ return Ok(StableKey::Array(items.into()));
+ }
+ loop {
+ items.push(self.key()?);
+ match self.chars.next().map(|(_, c)| c) {
+ Some(',') => {}
+ Some(']') => return Ok(StableKey::Array(items.into())),
+ _ => return Err(self.error("expected `,` or `]`")),
+ }
+ }
+ }
+ Some('@') => {
+ self.chars.next();
+ if self.chars.peek().is_some_and(|(_, c)| *c == '"') {
+ self.chars.next();
+ let name = self.quoted(false)?;
+ return Ok(StableKey::Symbol(Arc::from(name)));
+ }
+ let name = self.token();
+ if name.is_empty() {
+ return Err(self.error("expected a symbol name after `@`"));
+ }
+ Ok(StableKey::Symbol(Arc::from(name)))
+ }
+ Some('#') => {
+ self.chars.next();
+ let hex = self.token();
+ let mut bytes = [0u8; 16];
+ if hex.len() != 32 || !hex.is_ascii() {
+ return Err(self.error("expected 32 hex digits after `#`"));
+ }
+ for (i, byte) in bytes.iter_mut().enumerate() {
+ *byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)
+ .map_err(|_| self.error("expected 32 hex digits after `#`"))?;
+ }
+ Ok(StableKey::Fingerprint(utils::fingerprint::Fingerprint(
+ bytes,
+ )))
+ }
+ _ => {
+ let token = self.token();
+ match token {
+ "" => Err(self.error("expected a key")),
+ "null" => Ok(StableKey::Null),
+ "true" => Ok(StableKey::Bool(true)),
+ "false" => Ok(StableKey::Bool(false)),
+ _ => {
+ if let Ok(i) = token.parse::<i64>() {
+ Ok(StableKey::Int(i))
+ } else if let Ok(u) = uuid::Uuid::parse_str(token) {
+ Ok(StableKey::Uuid(u))
+ } else {
+ Err(self.error(&format!(
+ "`{token}` is not a key (quote a string, as in `\"{token}\"`, \
+ and write a symbol as `@{token}`)"
+ )))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ fn offset(&mut self) -> usize {
+ self.chars.peek().map_or(self.text.len(), |(i, _)| *i)
+ }
+
+ /// A bare token: up to the next `/`, `,` or `]`.
+ fn token(&mut self) -> &'t str {
+ let start = self.offset();
+ while self
+ .chars
+ .peek()
+ .is_some_and(|(_, c)| !matches!(c, '/' | ',' | ']'))
+ {
+ self.chars.next();
+ }
+ let end = self.offset();
+ let text = self.text;
+ &text[start..end]
+ }
+
+ /// The rest of a quoted string or byte string, after its opening quote,
+ /// undoing the escapes that `escape_default` writes. A byte string comes
+ /// back with one char per byte.
+ fn quoted(&mut self, bytes: bool) -> Result<String> {
+ let mut out = String::new();
+ loop {
+ let Some((_, c)) = self.chars.next() else {
+ return Err(self.error("unterminated quote"));
+ };
+ match c {
+ '"' => return Ok(out),
+ '\\' => {
+ let Some((_, e)) = self.chars.next() else {
+ return Err(self.error("unterminated escape"));
+ };
+ match e {
+ 't' => out.push('\t'),
+ 'r' => out.push('\r'),
+ 'n' => out.push('\n'),
+ '\'' | '"' | '\\' => out.push(e),
+ 'x' if bytes => {
+ let hex: String = (0..2)
+ .filter_map(|_| self.chars.next())
+ .map(|(_, c)| c)
+ .collect();
+ let byte = u8::from_str_radix(&hex, 16)
+ .map_err(|_| self.error("expected two hex digits after `\\x`"))?;
+ out.push(byte as char);
+ }
+ 'u' if !bytes => {
+ self.expect('{')?;
+ let mut hex = String::new();
+ loop {
+ match self.chars.next() {
+ Some((_, '}')) => break,
+ Some((_, h)) => hex.push(h),
+ None => return Err(self.error("unterminated `\\u{`")),
+ }
+ }
+ let ch = u32::from_str_radix(&hex, 16)
+ .ok()
+ .and_then(char::from_u32)
+ .ok_or_else(|| self.error("invalid `\\u{..}` escape"))?;
+ out.push(ch);
+ }
+ _ => return Err(self.error(&format!("unknown escape `\\{e}`"))),
+ }
+ }
+ c if bytes && !c.is_ascii() => {
+ return Err(self.error("a byte string holds ASCII only"));
+ }
+ c => out.push(c),
+ }
+ }
+ }
+}
+
impl<'a> From<StablePathRef<'a>> for StablePath {
fn from(value: StablePathRef<'a>) -> Self {
StablePath(value.0.to_owned().into())
@@ -381,6 +621,80 @@ impl<'a> storekey::Encode for StablePathPrefix<'a> {
#[cfg(test)]
mod tests {
+
+ #[test]
+ fn a_path_parses_back_from_its_display() {
+ use std::str::FromStr;
+ let paths = [
+ StablePath::root(),
+ StablePath(
+ vec![
+ StableKey::Symbol(Arc::from("process")),
+ StableKey::Symbol(Arc::from("cocoindex/mount_target")),
+ StableKey::Symbol(Arc::from("a,b]\"c\u{e9} d")),
+ StableKey::Str(Arc::from("docs/a \"b\".md\t\u{e9}\u{1F600}")),
+ StableKey::Array(vec![StableKey::Symbol(Arc::from("x/y"))].into()),
+ ]
+ .into(),
+ ),
+ StablePath(
+ vec![
+ StableKey::Null,
+ StableKey::Bool(true),
+ StableKey::Bool(false),
+ StableKey::Int(-42),
+ StableKey::Bytes(Arc::from(&b"a\x00/\"\xff"[..])),
+ StableKey::Uuid(uuid::Uuid::from_u128(
+ 0x1234_5678_9abc_def0_1234_5678_9abc_def0,
+ )),
+ StableKey::Array(
+ vec![
+ StableKey::Int(1),
+ StableKey::Str(Arc::from("x,]/")),
+ StableKey::Array(Vec::new().into()),
+ ]
+ .into(),
+ ),
+ StableKey::Fingerprint(utils::fingerprint::Fingerprint([7; 16])),
+ StableKey::Str(Arc::from("")),
+ ]
+ .into(),
+ ),
+ ];
+ for path in paths {
+ let text = path.to_string();
+ assert_eq!(StablePath::from_str(&text).unwrap(), path, "{text}");
+ }
+ let symbols = StablePath(
+ vec![
+ StableKey::Symbol(Arc::from("process_file")),
+ StableKey::Symbol(Arc::from("cocoindex/mount_target")),
+ ]
+ .into(),
+ );
+ assert_eq!(
+ symbols.to_string(),
+ "/@process_file/@\"cocoindex/mount_target\""
+ );
+ }
+
+ #[test]
+ fn a_path_that_is_not_as_displayed_does_not_parse() {
+ use std::str::FromStr;
+ for text in [
+ "",
+ "process",
+ "/process/a.md",
+ "/@",
+ "/\"a",
+ "/[1,2",
+ "/#12",
+ "/a//b",
+ "/1/",
+ ] {
+ assert!(StablePath::from_str(text).is_err(), "{text}");
+ }
+ }
use super::*;
use std::io::Cursor;
diff --git a/rust/core/src/state/stable_path_set.rs b/rust/core/src/state/stable_path_set.rs
index 0ef821b4..ee146e46 100644
--- a/rust/core/src/state/stable_path_set.rs
+++ b/rust/core/src/state/stable_path_set.rs
@@ -24,14 +24,14 @@ impl ChildStablePathSet {
StablePathSet::Directory(dir) => {
current = dir;
}
- StablePathSet::Component => {
+ StablePathSet::Component | StablePathSet::Skipped => {
client_bail!("{key} is not a directory in path {path}");
}
}
}
match current.children.entry(last.clone()) {
btree_map::Entry::Occupied(entry) => match entry.get() {
- StablePathSet::Component => already_declared_bail!(
+ StablePathSet::Component | StablePathSet::Skipped => already_declared_bail!(
"Child path {path} is mounted more than once in one run of its parent \
component. Each mount needs its own path: keep item keys unique within \
one mount_each() call, and give each call its own subpath"
@@ -52,10 +52,26 @@ impl ChildStablePathSet {
pub enum StablePathSet {
Directory(ChildStablePathSet),
Component,
+ /// The run mounted a component here and its selector left it out. The
+ /// mount counts as declared, as a mount the run executes does, but says
+ /// nothing about what the store holds at this path.
+ Skipped,
}
impl StablePathSet {
pub fn directory() -> Self {
Self::Directory(ChildStablePathSet::default())
}
+
+ /// Something at or below this node is a component the run executes.
+ pub(crate) fn has_executed_component(&self) -> bool {
+ match self {
+ Self::Directory(dir) => dir
+ .children
+ .values()
+ .any(StablePathSet::has_executed_component),
+ Self::Component => true,
+ Self::Skipped => false,
+ }
+ }
}
diff --git a/rust/core/src/state_store/app_store.rs b/rust/core/src/state_store/app_store.rs
index af89fd88..ddfdd9ff 100644
--- a/rust/core/src/state_store/app_store.rs
+++ b/rust/core/src/state_store/app_store.rs
@@ -669,6 +669,29 @@ impl AppStore {
Ok(())
}
+ /// Whether a target state strictly below `container` has an owner for
+ /// which `pred` holds. Owner rows of a container's descendants are
+ /// adjacent: their keys extend the container's own key, short of the
+ /// final terminator byte of its path.
+ pub async fn any_owner_below_in_txn(
+ &self,
+ txn: &mut WriteTxn<'_>,
+ container: &TargetStatePath,
+ mut pred: impl FnMut(&StablePath) -> bool,
+ ) -> Result<bool> {
+ let own_key = key_target_state_owner(container)?;
+ let prefix = &own_key[..own_key.len() - 1];
+ let mut found = false;
+ txn.for_each_prefix(self.db(), prefix, |raw_key, raw_value| {
+ if !found && raw_key != own_key.as_slice() {
+ let info: TargetStateOwnerInfo = from_msgpack_slice(raw_value)?;
+ found = pred(&info.component_path);
+ }
+ Ok(())
+ })?;
+ Ok(found)
+ }
+
pub async fn delete_target_state_owner(
&self,
txn: &mut WriteTxn<'_>,
diff --git a/rust/core/src/state_store/submit_session.rs b/rust/core/src/state_store/submit_session.rs
index 6aaa77f3..6acc2c9c 100644
--- a/rust/core/src/state_store/submit_session.rs
+++ b/rust/core/src/state_store/submit_session.rs
@@ -73,6 +73,7 @@ use cocoindex_utils::deser::from_msgpack_slice;
use cocoindex_utils::fingerprint::Fingerprint;
use crate::prelude::*;
+use crate::state::component_selector::{ComponentSelection, ComponentSelector};
use crate::state::db_schema::{
ChildExistenceInfo, StablePathEntryTrackingInfo, StablePathNodeType, StateKind,
};
@@ -169,6 +170,9 @@ pub struct PrecommitWritePlan {
/// For each preempted other-owner: their new tracking-info bytes
/// (with the preempted item removed by the engine).
pub preempted_owner_updates: BTreeMap<StablePath, Vec<u8>>,
+ /// The preempted owners the update does not run: their memos, and their
+ /// ancestors', are dropped with the takeover.
+ pub preempted_owners_left_out: Vec<StablePath>,
/// Readable names for the provider segments of the declared
/// target-state paths, keyed by lone segment fingerprint. Applied
/// write-once (existing entries left untouched) so inspection can
@@ -439,6 +443,22 @@ impl AppStore {
.write_tracking_info_raw(wtxn, &owner_path, &bytes)
.await?;
}
+ // An owner left out of the update no longer holds what
+ // its memo, and each ancestor's, say it declares: a hit
+ // in a later update would leave the target state to
+ // whoever took it, and delete it with them.
+ for owner_path in &plan.preempted_owners_left_out {
+ let mut memo_path = owner_path.as_ref();
+ loop {
+ app_store
+ .delete_component_memo_in_txn(wtxn, &memo_path.into())
+ .await?;
+ let Some((parent, _)) = memo_path.split_parent() else {
+ break;
+ };
+ memo_path = parent;
+ }
+ }
for (fp, segment_key) in &plan.segment_names {
app_store
.write_target_segment_name_if_missing(wtxn, *fp, segment_key)
@@ -586,6 +606,11 @@ impl AppStore {
/// at all (whole-component delete): every on-disk child is removed and
/// every Component leaf below it tombstoned, cascading the delete.
///
+/// `selector` is the selector the component's run is under, if any. The run
+/// did not decide about an on-disk child the selector does not cover, so that
+/// child is neither removed nor tombstoned (see [`remove_undeclared_child`]).
+/// Returns whether any such child stayed: the subtree is then not up to date.
+///
/// Used by [`AppStore::commit`]: the AppStore opens the commit txn,
/// then invokes the engine-supplied [`ExistenceReconciler`] which in
/// turn calls this function. Lives on the storage side because the
@@ -595,7 +620,9 @@ pub async fn reconcile_child_existence<'a>(
app_store: &AppStore,
component_path: &StablePath,
child_path_set: Option<&'a ChildStablePathSet>,
-) -> Result<()> {
+ selector: Option<&ComponentSelector>,
+) -> Result<bool> {
+ let mut kept_unselected = false;
let mut queue: VecDeque<Level<'a>> = VecDeque::new();
queue.push_back(Level {
path: component_path.clone(),
@@ -629,30 +656,32 @@ pub async fn reconcile_child_existence<'a>(
}
(None, Some(_)) => {
if let Some((key, info)) = existing_next.take() {
- app_store
- .delete_child_existence(wtxn, &level.path, &key)
- .await?;
- del_child(
+ kept_unselected |= remove_undeclared_child(
+ wtxn,
+ app_store,
+ selector,
&key,
&info,
&level.path,
component_path,
&mut queue,
&mut buffered_tombstones,
- )?;
+ )
+ .await?;
}
for (key, info) in existing_iter.by_ref() {
- app_store
- .delete_child_existence(wtxn, &level.path, &key)
- .await?;
- del_child(
+ kept_unselected |= remove_undeclared_child(
+ wtxn,
+ app_store,
+ selector,
&key,
&info,
&level.path,
component_path,
&mut queue,
&mut buffered_tombstones,
- )?;
+ )
+ .await?;
}
break;
}
@@ -670,17 +699,18 @@ pub async fn reconcile_child_existence<'a>(
let (key, info) = existing_next
.take()
.ok_or_else(|| internal_error!("invariance violation"))?;
- app_store
- .delete_child_existence(wtxn, &level.path, &key)
- .await?;
- del_child(
+ kept_unselected |= remove_undeclared_child(
+ wtxn,
+ app_store,
+ selector,
&key,
&info,
&level.path,
component_path,
&mut queue,
&mut buffered_tombstones,
- )?;
+ )
+ .await?;
existing_next = existing_iter.next();
}
Ordering::Equal => {
@@ -690,9 +720,26 @@ pub async fn reconcile_child_existence<'a>(
let (_, existing_info) = existing_next
.take()
.ok_or_else(|| internal_error!("invariance violation"))?;
+ // A skipped mount: whatever the store holds here stays.
+ if matches!(curr_path_set, StablePathSet::Skipped) {
+ curr_next = curr_iter.next();
+ existing_next = existing_iter.next();
+ continue;
+ }
let new_node_type = node_type_for(curr_path_set);
+ // Declared as a directory only because a selected path
+ // lies below, the component on disk is unselected: it
+ // stays what it is, with no tombstone, and the next run
+ // that covers it replaces it.
+ let keeps_unselected_component = existing_info.node_type
+ == StablePathNodeType::Component
+ && new_node_type == StablePathNodeType::Directory
+ && selector.is_some_and(|selector| {
+ !selector.covers(&level.path.concat_part(curr_key.clone()))
+ });
+ kept_unselected |= keeps_unselected_component;
- if existing_info.node_type != new_node_type {
+ if existing_info.node_type != new_node_type && !keeps_unselected_component {
app_store
.write_child_existence(
wtxn,
@@ -706,7 +753,9 @@ pub async fn reconcile_child_existence<'a>(
}
if let StablePathSet::Directory(curr_dir_set) = curr_path_set {
- if existing_info.node_type == StablePathNodeType::Component {
+ if existing_info.node_type == StablePathNodeType::Component
+ && !keeps_unselected_component
+ {
buffered_tombstones.push(
relative_to(&level.path, component_path)?
.concat_part(curr_key.clone()),
@@ -732,6 +781,11 @@ pub async fn reconcile_child_existence<'a>(
}
for (stable_key, path_set) in children_to_add {
+ // A mount the selector left out, or a directory of nothing else,
+ // leaves no trace in the store.
+ if !path_set.has_executed_component() {
+ continue;
+ }
let node_type = node_type_for(path_set);
app_store
.write_child_existence(
@@ -755,7 +809,7 @@ pub async fn reconcile_child_existence<'a>(
.await?;
}
}
- Ok(())
+ Ok(kept_unselected)
}
struct Level<'a> {
@@ -763,6 +817,60 @@ struct Level<'a> {
child_path_set: Option<&'a ChildStablePathSet>,
}
+/// An on-disk child the run did not declare: remove it, unless the run's
+/// selector says the run did not get to decide about it.
+///
+/// - Unselected: it stays, its row and everything below untouched. This is the
+/// source of "an unselected component is not treated as gone": it never gets
+/// a tombstone, so nothing deletes its target states.
+/// - Above a selected path: its row stays. A directory is walked, since selected
+/// components below it did go away. A component stays whole: what lies below
+/// it is its own to reconcile, and deleting it would delete unselected
+/// descendants too.
+///
+/// Returns whether the child stayed.
+#[allow(clippy::too_many_arguments)]
+async fn remove_undeclared_child<'a>(
+ wtxn: &mut WriteTxn<'_>,
+ app_store: &AppStore,
+ selector: Option<&ComponentSelector>,
+ stable_key: &StableKey,
+ info: &ChildExistenceInfo,
+ parent_path: &StablePath,
+ component_path: &StablePath,
+ queue: &mut VecDeque<Level<'a>>,
+ buffered_tombstones: &mut Vec<StablePath>,
+) -> Result<bool> {
+ if let Some(selector) = selector {
+ let path = parent_path.concat_part(stable_key.clone());
+ match selector.classify(&path) {
+ ComponentSelection::Selected => {}
+ ComponentSelection::Unselected => return Ok(true),
+ ComponentSelection::AncestorOfSelected => {
+ if info.node_type == StablePathNodeType::Directory {
+ queue.push_back(Level {
+ path,
+ child_path_set: None,
+ });
+ }
+ return Ok(true);
+ }
+ }
+ }
+ app_store
+ .delete_child_existence(wtxn, parent_path, stable_key)
+ .await?;
+ del_child(
+ stable_key,
+ info,
+ parent_path,
+ component_path,
+ queue,
+ buffered_tombstones,
+ )?;
+ Ok(false)
+}
+
fn del_child<'a>(
stable_key: &StableKey,
info: &ChildExistenceInfo,
@@ -789,7 +897,7 @@ fn del_child<'a>(
fn node_type_for(path_set: &StablePathSet) -> StablePathNodeType {
match path_set {
StablePathSet::Directory(_) => StablePathNodeType::Directory,
- StablePathSet::Component => StablePathNodeType::Component,
+ StablePathSet::Component | StablePathSet::Skipped => StablePathNodeType::Component,
}
}
diff --git a/rust/py/src/app.rs b/rust/py/src/app.rs
index 97dc1d5d..1526087b 100644
--- a/rust/py/src/app.rs
+++ b/rust/py/src/app.rs
@@ -6,6 +6,7 @@ use cocoindex_core::engine::{
runtime::get_runtime,
stats::{ProcessingStats, VersionedProcessingStats},
};
+use cocoindex_core::state::component_selector::ComponentSelector;
use pyo3::exceptions::PyRuntimeError;
use pyo3::types::PyDict;
use pyo3_async_runtimes::tokio::future_into_py;
@@ -13,7 +14,7 @@ use tokio::sync::watch;
use crate::{
component::PyComponentProcessor, deadline::PyDeadlineContext, environment::PyEnvironment,
- target_state_codec::PyTargetAction, value::PyStoredValue,
+ stable_path::PyStablePath, target_state_codec::PyTargetAction, value::PyStoredValue,
};
fn snapshot_to_py<'py>(
@@ -233,6 +234,10 @@ impl PyStatsGroupHandle {
}
}
+fn component_selector_from_py(paths: Vec<PyStablePath>) -> ComponentSelector {
+ ComponentSelector::new(paths.into_iter().map(|path| path.0))
+}
+
#[pyclass(name = "App")]
pub struct PyApp(pub Arc<App<PyEngineProfile>>);
@@ -259,7 +264,8 @@ impl PyApp {
Ok(Self(Arc::new(app)))
}
- #[pyo3(signature = (root_processor, full_reprocess, host_ctx, live=false, preview=false, *, deadline))]
+ #[pyo3(signature = (root_processor, full_reprocess, host_ctx, live=false, preview=false, *, deadline, component_selector=None))]
+ #[allow(clippy::too_many_arguments)]
pub fn update_async(
&self,
root_processor: PyComponentProcessor,
@@ -268,12 +274,14 @@ impl PyApp {
live: bool,
preview: bool,
deadline: PyDeadlineContext,
+ component_selector: Option<Vec<PyStablePath>>,
) -> PyResult<PyUpdateHandle> {
let app = self.0.clone();
let options = AppUpdateOptions {
full_reprocess,
live,
deadline: deadline.0,
+ component_selector: component_selector.map(component_selector_from_py),
};
let host_ctx = Arc::new(host_ctx);
let preview_collector = if preview {
@@ -290,7 +298,7 @@ impl PyApp {
Ok(uh)
}
- #[pyo3(signature = (root_processor, full_reprocess, host_ctx, report_to_stdout=false, refresh_interval_secs=None, live=false, preview=false, *, deadline))]
+ #[pyo3(signature = (root_processor, full_reprocess, host_ctx, report_to_stdout=false, refresh_interval_secs=None, live=false, preview=false, *, deadline, component_selector=None))]
#[allow(clippy::too_many_arguments)]
pub fn update(
&self,
@@ -303,12 +311,14 @@ impl PyApp {
live: bool,
preview: bool,
deadline: PyDeadlineContext,
+ component_selector: Option<Vec<PyStablePath>>,
) -> PyResult<Py<PyAny>> {
let app = self.0.clone();
let options = AppUpdateOptions {
full_reprocess,
live,
deadline: deadline.0,
+ component_selector: component_selector.map(component_selector_from_py),
};
let host_ctx = Arc::new(host_ctx);
let preview_collector = if preview {
diff --git a/rust/py/src/component.rs b/rust/py/src/component.rs
index 41975693..8884c599 100644
--- a/rust/py/src/component.rs
+++ b/rust/py/src/component.rs
@@ -8,7 +8,7 @@ use crate::{
},
prelude::*,
runtime::{PyAsyncContext, PyCallback, build_on_error},
- stable_path::PyStablePath,
+ stable_path::{PyStableKey, PyStablePath},
value::PyStoredValue,
};
@@ -226,6 +226,40 @@ pub fn use_mount_async<'py>(
})
}
+/// Whether the update's selector leaves out a mount at `stable_path`, so that
+/// the caller prepares nothing for it. See `ComponentProcessorContext::skips_mount`.
+#[pyfunction]
+pub fn skips_mount(
+ stable_path: PyStablePath,
+ comp_ctx: PyComponentProcessorContext,
+ fn_ctx: &PyFnCallContext,
+) -> PyResult<bool> {
+ comp_ctx
+ .0
+ .skips_mount(&fn_ctx.0, &stable_path.0)
+ .into_py_result()
+}
+
+/// The item keys a `mount_each` at `stable_path` can run: `None` for every
+/// key. See `ComponentProcessorContext::mount_each_keys`.
+#[pyfunction]
+pub fn mount_each_keys(
+ py: Python<'_>,
+ stable_path: PyStablePath,
+ comp_ctx: PyComponentProcessorContext,
+ fn_ctx: &PyFnCallContext,
+) -> PyResult<Option<Vec<Py<PyAny>>>> {
+ comp_ctx
+ .0
+ .mount_each_keys(&fn_ctx.0, &stable_path.0)
+ .map(|keys| {
+ keys.into_iter()
+ .map(|key| PyStableKey(key).into_pyobject(py).map(|b| b.unbind()))
+ .collect()
+ })
+ .transpose()
+}
+
#[pyfunction]
#[pyo3(signature = (processor, stable_path, comp_ctx, fn_ctx, handler_callback=None))]
pub fn mount_async<'py>(
diff --git a/rust/py/src/lib.rs b/rust/py/src/lib.rs
index 671f0592..44ca443b 100644
--- a/rust/py/src/lib.rs
+++ b/rust/py/src/lib.rs
@@ -47,6 +47,8 @@ fn core_module(m: &pyo3::Bound<'_, pyo3::types::PyModule>) -> pyo3::PyResult<()>
m.add_class::<component::PyComponentMountHandle>()?;
m.add_class::<component::PyComponentMountRunHandle>()?;
m.add_function(wrap_pyfunction!(component::mount_async, m)?)?;
+ m.add_function(wrap_pyfunction!(component::skips_mount, m)?)?;
+ m.add_function(wrap_pyfunction!(component::mount_each_keys, m)?)?;
m.add_function(wrap_pyfunction!(component::use_mount_async, m)?)?;
m.add_class::<context::PyComponentProcessorContext>()?;
diff --git a/rust/py/src/live_component.rs b/rust/py/src/live_component.rs
index 3e5cb5d8..6bf1aef6 100644
--- a/rust/py/src/live_component.rs
+++ b/rust/py/src/live_component.rs
@@ -16,6 +16,10 @@ pub struct PyLiveComponentController(pub Arc<LiveComponentController<PyEnginePro
#[pymethods]
impl PyLiveComponentController {
+ pub fn skips_subpath(&self, stable_path: PyStablePath) -> bool {
+ self.0.skips_subpath(&stable_path.0)
+ }
+
pub fn update_full_async<'py>(
&self,
py: Python<'py>,
@@ -96,6 +100,7 @@ impl PyLiveComponentController {
/// branch). Returns `(inner_controller, readiness_handle)` β€” caller
/// constructs a Python `LiveComponentOperator` for the inner instance,
/// then calls `inner_controller.start(instance.process_live(operator))`.
+ /// Returns `None` when the update's selector leaves the child out.
pub fn mount_inner_live_async<'py>(
&self,
py: Python<'py>,
@@ -107,9 +112,11 @@ impl PyLiveComponentController {
.mount_inner_live(stable_path.0)
.await
.into_py_result()?;
- let py_controller = PyLiveComponentController(Arc::new(result.controller));
- let py_handle = PyComponentMountHandle::from_handle(result.readiness_handle);
- Ok((py_controller, py_handle))
+ Ok(result.map(|result| {
+ let py_controller = PyLiveComponentController(Arc::new(result.controller));
+ let py_handle = PyComponentMountHandle::from_handle(result.readiness_handle);
+ (py_controller, py_handle)
+ }))
})
}
@@ -173,9 +180,13 @@ pub fn mount_live_async<'py>(
// Async phase: no borrows needed, all data is owned.
future_into_py(py, async move {
+ // `None`: the update's selector leaves the component out.
+ let Some(pending) = pending else {
+ return Ok(None);
+ };
let result = pending.complete().await.into_py_result()?;
let py_controller = PyLiveComponentController(Arc::new(result.controller));
let py_handle = PyComponentMountHandle::from_handle(result.readiness_handle);
- Ok((py_controller, py_handle))
+ Ok(Some((py_controller, py_handle)))
})
}
diff --git a/rust/py/src/stable_path.rs b/rust/py/src/stable_path.rs
index 582c035a..e7a19f08 100644
--- a/rust/py/src/stable_path.rs
+++ b/rust/py/src/stable_path.rs
@@ -124,6 +124,12 @@ impl PyStablePath {
Self(self.0.concat_part(part.0))
}
+ /// Parses a path as `to_string()` writes it.
+ #[staticmethod]
+ pub fn parse(text: &str) -> PyResult<Self> {
+ text.parse::<StablePath>().map(Self).into_py_result()
+ }
+
#[allow(
clippy::inherent_to_string,
reason = "Python API: `StablePath.to_string()`"
diff --git a/rust/sdk/cocoindex/src/app.rs b/rust/sdk/cocoindex/src/app.rs
index 48af73be..6b060b07 100644
--- a/rust/sdk/cocoindex/src/app.rs
+++ b/rust/sdk/cocoindex/src/app.rs
@@ -16,6 +16,7 @@ use cocoindex_core::engine::stats::{ProcessingStats, ProcessingStatsGroup, TERMI
use cocoindex_core::engine::target_state::{
TargetStateProvider as CoreTargetStateProvider, TargetStateProviderRegistry,
};
+use cocoindex_core::state::component_selector::ComponentSelector;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tokio::sync::watch;
@@ -670,13 +671,15 @@ impl App {
Fut: Future<Output = Result<T>> + Send + 'static,
T: Serialize + for<'de> Deserialize<'de> + Send + 'static,
{
+ let report_to_stdout = options.report_to_stdout;
+ let progress_refresh_interval = options.progress_refresh_interval;
let handle = self.start_update_with_options(options, f)?;
let processing_stats = handle.core.stats().clone();
- let result = if options.report_to_stdout {
+ let result = if report_to_stdout {
let value = show_progress(
handle.into_core(),
ProgressDisplayOptions::from_refresh_secs(
- options.progress_refresh_interval.map(|d| d.as_secs_f64()),
+ progress_refresh_interval.map(|d| d.as_secs_f64()),
),
)
.await
@@ -762,6 +765,7 @@ impl App {
full_reprocess: options.full_reprocess,
live: options.live,
deadline,
+ component_selector: options.component_selector,
};
// In preview mode the engine collects target actions into this shared
@@ -889,7 +893,7 @@ impl App {
}
/// Options for a Rust SDK app update.
-#[derive(Debug, Clone, Copy, Default)]
+#[derive(Debug, Clone, Default)]
pub struct UpdateOptions {
pub full_reprocess: bool,
pub live: bool,
@@ -907,6 +911,13 @@ pub struct UpdateOptions {
/// When `report_to_stdout` is set, refresh the stdout display at this
/// interval. `None` uses the engine's default cadence.
pub progress_refresh_interval: Option<Duration>,
+ /// Run only the selected components and what reaches them, leaving every
+ /// other component as it is (cf. Python's
+ /// `App.update(component_selector=...)`). This filters background mounts
+ /// (`Ctx::mount`, `Ctx::mount_each`, live components). Foreground children
+ /// (`Ctx::scope`, `use_mount!`, `use_mount_each!`) return values, so they
+ /// always run.
+ pub component_selector: Option<ComponentSelector>,
}
/// Options for [`Ctx::stats_group_with_options`](crate::Ctx::stats_group_with_options).
diff --git a/rust/sdk/cocoindex/src/cli/mod.rs b/rust/sdk/cocoindex/src/cli/mod.rs
index 8ca21a1c..5c0b351f 100644
--- a/rust/sdk/cocoindex/src/cli/mod.rs
+++ b/rust/sdk/cocoindex/src/cli/mod.rs
@@ -13,6 +13,7 @@ pub mod protocol;
use std::future::Future;
use std::io::Write;
use std::process::ExitCode;
+use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
@@ -21,6 +22,7 @@ use cocoindex_core::engine::stats::TERMINATED_VERSION;
use crate::app::{Environment, Progress, UpdateOptions};
use crate::error::{Error, Result};
use crate::registry::{self, AppEntry};
+use crate::{ComponentSelector, StablePath};
use protocol::{
AppInfo, ConfirmAction, Event, MARKER, Outcome, PROTOCOL_VERSION, PreviewKind, RunStatsWire,
encode,
@@ -120,6 +122,8 @@ struct ChildArgs {
full_reprocess: bool,
preview: bool,
reset: bool,
+ /// The paths `--select` names: run only these components and those below.
+ select: Vec<StablePath>,
db_only: bool,
/// Ask the CLI (`confirm` record, answer on stdin) before destroying state.
confirm: bool,
@@ -143,6 +147,7 @@ impl ChildArgs {
full_reprocess: false,
preview: false,
reset: false,
+ select: Vec::new(),
db_only: false,
confirm: false,
};
@@ -162,6 +167,13 @@ impl ChildArgs {
.ok_or_else(|| "--app needs a value".to_string())?;
parsed.app = Some(value.clone());
}
+ "--select" => {
+ let value = iter
+ .next()
+ .ok_or_else(|| "--select needs a value".to_string())?;
+ let path = StablePath::from_str(value).map_err(|err| err.to_string())?;
+ parsed.select.push(path);
+ }
"--live" => parsed.live = true,
"--full-reprocess" => parsed.full_reprocess = true,
"--preview" => parsed.preview = true,
@@ -174,6 +186,9 @@ impl ChildArgs {
if parsed.preview && (parsed.reset || parsed.live) {
return Err("--preview cannot be combined with --reset or --live".to_string());
}
+ if !parsed.select.is_empty() && parsed.reset {
+ return Err("--select and --reset cannot be used together.".to_string());
+ }
let flag_allowed = |flag: &str, ok: bool| {
if ok {
Ok(())
@@ -186,6 +201,7 @@ impl ChildArgs {
flag_allowed("--full-reprocess", !parsed.full_reprocess || is_update)?;
flag_allowed("--preview", !parsed.preview || is_update)?;
flag_allowed("--reset", !parsed.reset || is_update)?;
+ flag_allowed("--select", parsed.select.is_empty() || is_update)?;
flag_allowed("--db-only", !parsed.db_only || verb == Verb::Drop)?;
flag_allowed("--app", parsed.app.is_none() || verb != Verb::Ls)?;
flag_allowed(
@@ -438,6 +454,8 @@ async fn update_app(
full_reprocess: args.full_reprocess,
live: args.live,
preview: args.preview,
+ component_selector: (!args.select.is_empty())
+ .then(|| ComponentSelector::new(args.select.iter().cloned())),
..UpdateOptions::default()
};
let mut handle = app.start_update_with_options(options, entry.run)?;
@@ -558,6 +576,38 @@ mod tests {
assert!(!parsed.preview && !parsed.reset && !parsed.db_only);
}
+ #[test]
+ fn parses_repeated_select_paths() {
+ let parsed = ChildArgs::parse(&args(&[
+ "update",
+ "--select",
+ r#"/@process/"docs/a.md""#,
+ "--select",
+ r#"/"each"/3"#,
+ "--preview",
+ ]))
+ .unwrap();
+ let shown: Vec<String> = parsed.select.iter().map(ToString::to_string).collect();
+ assert_eq!(shown, [r#"/@process/"docs/a.md""#, r#"/"each"/3"#]);
+ assert!(parsed.preview);
+ }
+
+ #[test]
+ fn rejects_bad_or_misplaced_select() {
+ let err = ChildArgs::parse(&args(&["update", "--select", "process"])).unwrap_err();
+ assert!(err.contains("cannot parse component path"), "{err}");
+ let err = ChildArgs::parse(&args(&["update", "--select"])).unwrap_err();
+ assert!(err.contains("--select needs a value"), "{err}");
+ let err =
+ ChildArgs::parse(&args(&["update", "--select", r#"/"a""#, "--reset"])).unwrap_err();
+ assert!(
+ err.contains("--select and --reset cannot be used together"),
+ "{err}"
+ );
+ let err = ChildArgs::parse(&args(&["drop", "--select", r#"/"a""#])).unwrap_err();
+ assert!(err.contains("not valid for `drop`"));
+ }
+
#[test]
fn rejects_preview_with_reset_or_live() {
let err = ChildArgs::parse(&args(&["update", "--preview", "--reset"])).unwrap_err();
diff --git a/rust/sdk/cocoindex/src/ctx.rs b/rust/sdk/cocoindex/src/ctx.rs
index c4bbf35c..adf8ec5a 100644
--- a/rust/sdk/cocoindex/src/ctx.rs
+++ b/rust/sdk/cocoindex/src/ctx.rs
@@ -1058,7 +1058,13 @@ impl Ctx {
let fn_ctx = Arc::new(FnCallContext::default());
let pending = mount_live_prepare(comp_ctx, &fn_ctx, child_path, comp_ctx.live())
.map_err(|e| Error::engine(format!("{e}")))?;
+ // Before the return below: a skipped mount still counts as a mount of
+ // the calling function, so it is not memoized.
let _frame = self.frame_guard(fn_ctx);
+ let Some(pending) = pending else {
+ // The update's component selector leaves this component out.
+ return Ok(());
+ };
let result = pending
.complete()
.await
@@ -1230,7 +1236,13 @@ impl Ctx {
let fn_ctx = Arc::new(FnCallContext::default());
let pending = mount_live_prepare(comp_ctx, &fn_ctx, child_path.clone(), comp_ctx.live())
.map_err(|e| Error::engine(format!("{e}")))?;
+ // Before the return below: a skipped mount still counts as a mount of
+ // the calling function, so it is not memoized.
let _frame = self.frame_guard(fn_ctx);
+ let Some(pending) = pending else {
+ // The update's component selector leaves this component out.
+ return Ok(());
+ };
let result = pending
.complete()
.await
@@ -1308,6 +1320,15 @@ impl Ctx {
self.__mount_fp(key.into_stable_key(), None, f).await
}
+ /// The update's component selector leaves out a mount at `key`. `mount!`
+ /// asks before it computes the child's memo key, which is user code.
+ #[doc(hidden)]
+ pub fn __selector_leaves_out(&self, key: &StableKey) -> bool {
+ self.comp_ctx.as_ref().is_some_and(|comp_ctx| {
+ comp_ctx.selector_leaves_out(&self.child_path(comp_ctx, key.clone()))
+ })
+ }
+
/// Background mount with an explicit component-memo fingerprint. The
/// `mount!` macro calls this; [`Ctx::mount`] is the `memo = None`
/// (always-run) case.
@@ -1578,6 +1599,9 @@ impl Ctx {
/// All items are reported under one processor name, `mount_each`, in
/// update stats and `cocoindex show -l`.
///
+ /// When the update's `component_selector` leaves out every child here,
+ /// `items` is not read at all: neither `key_fn` nor `f` runs.
+ ///
/// # Errors
///
/// Returns an error when `key_fn` yields the same key twice, or when a
@@ -1711,11 +1735,30 @@ impl Ctx {
deadline: self.deadline,
});
};
+ // A selector that leaves out every child here: the source is not read
+ // at all, so no item, key or closure of the caller's runs.
+ let mount_each_keys = {
+ let fn_ctx = Arc::new(FnCallContext::default());
+ let _frame = parent.frame_guard(fn_ctx.clone());
+ comp_ctx.mount_each_keys(&fn_ctx, &parent.mount_base_path(comp_ctx))
+ };
+ if mount_each_keys.is_some_and(|keys| keys.is_empty()) {
+ return Ok(ComponentMountHandle {
+ inner: MountHandleInner::Core(Vec::new()),
+ deadline: self.deadline,
+ });
+ }
let mut handles = Vec::new();
while let Some((key, value)) = items.next().await {
parent.check_cancellation()?;
check_unique_key(&mut keys, key.clone())?;
- let memo = memo_of(&value)?;
+ // The memo key is user code, which a child the selector leaves out
+ // must not run. The mount below then skips the child itself.
+ let memo = if comp_ctx.selector_leaves_out(&parent.child_path(comp_ctx, key.clone())) {
+ None
+ } else {
+ memo_of(&value)?
+ };
let body = body.clone();
let handle = parent
.mount_background(comp_ctx, key, processor_name.clone(), memo, move |child| {
diff --git a/rust/sdk/cocoindex/src/lib.rs b/rust/sdk/cocoindex/src/lib.rs
index 892f8e23..d9fae008 100644
--- a/rust/sdk/cocoindex/src/lib.rs
+++ b/rust/sdk/cocoindex/src/lib.rs
@@ -186,6 +186,8 @@ pub use app::{
Progress, StatsGroupHandle, StatsGroupOptions, UpdateHandle, UpdateOptions,
};
pub use batched::Batched;
+pub use cocoindex_core::state::component_selector::ComponentSelector;
+pub use cocoindex_core::state::stable_path::StablePath;
pub use ctx::{ComponentMountHandle, ContextKey, Ctx};
pub use deps::{DataDep, LogicDep, PropagatedCallback};
pub use entity_resolution::{
diff --git a/rust/sdk/cocoindex/src/prelude.rs b/rust/sdk/cocoindex/src/prelude.rs
index 762ce2eb..198db6ef 100644
--- a/rust/sdk/cocoindex/src/prelude.rs
+++ b/rust/sdk/cocoindex/src/prelude.rs
@@ -55,6 +55,8 @@ pub use crate::{
PreviewValue, Progress, SchemaFields, StatsGroupHandle, StatsGroupOptions, UpdateHandle,
UpdateOptions,
};
+pub use cocoindex_core::state::component_selector::ComponentSelector;
+pub use cocoindex_core::state::stable_path::StablePath;
pub use crate::{app, function, lifespan, main, mount, mount_each, use_mount, use_mount_each};
diff --git a/rust/sdk/cocoindex/tests/component_selector.rs b/rust/sdk/cocoindex/tests/component_selector.rs
new file mode 100644
index 00000000..bb22cc0b
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/component_selector.rs
@@ -0,0 +1,1779 @@
+//! Sliced execution (`UpdateOptions.component_selector`) on every Rust SDK
+//! mount surface.
+
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use cocoindex::prelude::*;
+use cocoindex::{ComponentSelector, StablePath, async_trait, inspect};
+use tokio::sync::{Notify, mpsc};
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+type Log = Arc<Mutex<Vec<String>>>;
+
+fn new_log() -> Log {
+ Arc::new(Mutex::new(Vec::new()))
+}
+
+fn drain_sorted(log: &Log) -> Vec<String> {
+ let mut v = std::mem::take(&mut *log.lock().unwrap());
+ v.sort();
+ v
+}
+
+/// Which component bodies ran, provided through the environment so
+/// `#[cocoindex::function]` bodies can reach it.
+#[derive(Clone, Default)]
+struct RunLog(Log);
+
+fn ran(ctx: &Ctx, what: impl Into<String>) {
+ ctx.get_or_err::<RunLog>()
+ .unwrap()
+ .0
+ .lock()
+ .unwrap()
+ .push(what.into());
+}
+
+async fn temp_app(name: &str) -> (App, tempfile::TempDir, Log) {
+ let dir = tempfile::tempdir().unwrap();
+ let log = new_log();
+ let app = Environment::builder()
+ .db_path(dir.path().join(".cocoindex_db"))
+ .provide(RunLog(log.clone()))
+ .build()
+ .await
+ .unwrap()
+ .app(name)
+ .await
+ .unwrap();
+ (app, dir, log)
+}
+
+fn p(parts: &[StableKey]) -> StablePath {
+ parts
+ .iter()
+ .fold(StablePath::root(), |path, k| path.concat_part(k.clone()))
+}
+
+fn s(v: &str) -> StableKey {
+ StableKey::Str(Arc::from(v))
+}
+
+fn select(paths: impl IntoIterator<Item = StablePath>) -> UpdateOptions {
+ UpdateOptions {
+ component_selector: Some(ComponentSelector::new(paths)),
+ ..UpdateOptions::default()
+ }
+}
+
+fn key_str(key: &StableKey) -> String {
+ match key {
+ StableKey::Str(s) | StableKey::Symbol(s) => s.to_string(),
+ StableKey::Int(i) => i.to_string(),
+ other => format!("{other:?}"),
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+struct RowAction {
+ key: String,
+ value: Option<String>,
+}
+
+fn recording_sink(log: Log) -> TargetActionSink<RowAction> {
+ TargetActionSink::from_async_fn(move |actions: Vec<TargetAction<RowAction>>| {
+ let log = log.clone();
+ async move {
+ let mut log = log.lock().unwrap();
+ for action in actions {
+ let (verb, row) = match action {
+ TargetAction::Create(r) => ("create", r),
+ TargetAction::Update(r) => ("update", r),
+ TargetAction::Delete(r) => ("delete", r),
+ };
+ log.push(match row.value {
+ Some(v) => format!("{verb} {}={}", row.key, v),
+ None => format!("{verb} {}", row.key),
+ });
+ }
+ Ok(())
+ }
+ })
+}
+
+#[derive(Clone)]
+struct RowHandler {
+ sink: TargetActionSink<RowAction>,
+}
+
+impl TargetHandler<String> for RowHandler {
+ type TrackingRecord = String;
+ type Action = RowAction;
+
+ fn reconcile(
+ &self,
+ key: StableKey,
+ desired: Option<String>,
+ prev: Vec<String>,
+ prev_may_be_missing: bool,
+ ) -> Result<Option<TargetReconcileOutput<RowAction, String>>> {
+ let k = key_str(&key);
+ match desired {
+ Some(value) => {
+ if !prev_may_be_missing && !prev.is_empty() && prev.iter().all(|p| *p == value) {
+ return Ok(None);
+ }
+ let row = RowAction {
+ key: k,
+ value: Some(value.clone()),
+ };
+ let action = if prev.is_empty() {
+ TargetAction::Create(row)
+ } else {
+ TargetAction::Update(row)
+ };
+ Ok(Some(TargetReconcileOutput {
+ action,
+ sink: self.sink.clone(),
+ tracking_record: Some(value),
+ child_invalidation: None,
+ }))
+ }
+ None => {
+ if prev.is_empty() && !prev_may_be_missing {
+ return Ok(None);
+ }
+ Ok(Some(TargetReconcileOutput {
+ action: TargetAction::Delete(RowAction {
+ key: k,
+ value: None,
+ }),
+ sink: self.sink.clone(),
+ tracking_record: None,
+ child_invalidation: None,
+ }))
+ }
+ }
+ }
+}
+
+fn rows(ctx: &Ctx, sink_log: &Log) -> Result<TargetStateProvider<String>> {
+ register_root_target_states_provider(
+ ctx,
+ "selector_test/rows",
+ RowHandler {
+ sink: recording_sink(sink_log.clone()),
+ },
+ )
+}
+
+fn read(path: &std::path::Path) -> Option<String> {
+ std::fs::read_to_string(path).ok()
+}
+
+// ---------------------------------------------------------------------------
+// mount! / mount_each! / use_mount! / use_mount_each! (macros, memoized)
+// ---------------------------------------------------------------------------
+
+#[cocoindex::function]
+async fn write_one(ctx: &Ctx, name: String, version: u32, target: DirTarget) -> Result<()> {
+ ran(ctx, format!("write_one:{name}"));
+ target.declare_file(
+ ctx,
+ &format!("{name}.txt"),
+ format!("{name}@{version}").as_bytes(),
+ )
+}
+
+#[cocoindex::function]
+async fn write_item(ctx: &Ctx, name: String, version: u32, target: DirTarget) -> Result<()> {
+ ran(ctx, format!("write_item:{name}"));
+ target.declare_file(
+ ctx,
+ &format!("{name}.txt"),
+ format!("{name}@{version}").as_bytes(),
+ )
+}
+
+/// A foreground (use_mount!) component that mounts one background child.
+#[cocoindex::function]
+async fn group(ctx: &Ctx, version: u32, target: DirTarget) -> Result<u32> {
+ ran(ctx, "group");
+ cocoindex::mount!(
+ "inner",
+ write_one(ctx, "inner".to_string(), version, target.clone())
+ )
+ .await?;
+ Ok(version)
+}
+
+#[cocoindex::function]
+async fn used(ctx: &Ctx, name: String, version: u32) -> Result<String> {
+ ran(ctx, format!("used:{name}"));
+ Ok(format!("{name}@{version}"))
+}
+
+async fn macro_app(
+ app: &App,
+ out: std::path::PathBuf,
+ version: u32,
+ with_single: bool,
+ opts: UpdateOptions,
+) {
+ app.update_with_options(opts, move |ctx| async move {
+ let ctx = &ctx;
+ let target = DirTarget::mount(ctx, &out)?;
+ if with_single {
+ cocoindex::mount!(
+ "single",
+ write_one(ctx, "single".to_string(), version, target.clone())
+ )
+ .await?;
+ }
+ // Default key: the function name.
+ cocoindex::mount!(write_one(
+ ctx,
+ "default".to_string(),
+ version,
+ target.clone()
+ ))
+ .await?;
+ // Default prefix (function name), integer keys.
+ let items = vec![(1i64, "item1".to_string()), (2i64, "item2".to_string())];
+ cocoindex::mount_each!(items, |name| write_item(ctx, name, version, target.clone()))
+ .await?;
+ // Explicit prefix, string keys.
+ let items = vec![
+ ("x".to_string(), "x".to_string()),
+ ("y".to_string(), "y".to_string()),
+ ];
+ cocoindex::mount_each!("each", items, |name| write_item(
+ ctx,
+ name,
+ version,
+ target.clone()
+ ))
+ .await?;
+ let v = cocoindex::use_mount!(group(ctx, version, target.clone())).await?;
+ assert_eq!(v, version);
+ let items = vec![
+ ("u1".to_string(), "u1".to_string()),
+ ("u2".to_string(), "u2".to_string()),
+ ];
+ let values = cocoindex::use_mount_each!(items, |name| used(ctx, name, version)).await?;
+ assert_eq!(values.len(), 2);
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn macros_run_selected_skip_unselected_and_keep_their_target_states() {
+ let (app, dir, log) = temp_app("macros").await;
+ let out = dir.path().join("out");
+ macro_app(&app, out.clone(), 1, true, UpdateOptions::default()).await;
+ assert_eq!(drain_sorted(&log).len(), 10);
+
+ // The paths a Rust user derives from the macro rules: a fn-name default
+ // key is a `Str`, a `mount_each!` default prefix is the fn name, an
+ // integer item key is an `Int`.
+ let paths = inspect::list_stable_paths(&app).await.unwrap();
+ for expected in [
+ p(&[s("single")]),
+ p(&[s("write_one")]),
+ p(&[s("write_item"), StableKey::Int(2)]),
+ p(&[s("each"), s("y")]),
+ p(&[s("group"), s("inner")]),
+ ] {
+ assert!(paths.contains(&expected), "{expected} not in {paths:?}");
+ }
+
+ macro_app(
+ &app,
+ out.clone(),
+ 2,
+ true,
+ select([
+ p(&[s("write_item"), 2i64.into_stable_key()]),
+ p(&[s("each"), s("y")]),
+ p(&[s("group"), s("inner")]),
+ ]),
+ )
+ .await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec![
+ "group",
+ "used:u1",
+ "used:u2",
+ "write_item:item2",
+ "write_item:y",
+ "write_one:inner",
+ ]
+ );
+ assert_eq!(read(&out.join("single.txt")).as_deref(), Some("single@1"));
+ assert_eq!(read(&out.join("default.txt")).as_deref(), Some("default@1"));
+ assert_eq!(read(&out.join("item1.txt")).as_deref(), Some("item1@1"));
+ assert_eq!(read(&out.join("item2.txt")).as_deref(), Some("item2@2"));
+ assert_eq!(read(&out.join("x.txt")).as_deref(), Some("x@1"));
+ assert_eq!(read(&out.join("y.txt")).as_deref(), Some("y@2"));
+ assert_eq!(read(&out.join("inner.txt")).as_deref(), Some("inner@2"));
+
+ // "single" is no longer mounted; a selector that does not cover it keeps
+ // its file. The default-key component is selected by its `Str` fn name.
+ macro_app(&app, out.clone(), 3, false, select([p(&[s("write_one")])])).await;
+ let ran_now = drain_sorted(&log);
+ assert!(
+ ran_now.contains(&"write_one:default".to_string()),
+ "{ran_now:?}"
+ );
+ assert!(
+ !ran_now.contains(&"write_item:item1".to_string()),
+ "{ran_now:?}"
+ );
+ assert_eq!(read(&out.join("single.txt")).as_deref(), Some("single@1"));
+ assert_eq!(read(&out.join("default.txt")).as_deref(), Some("default@3"));
+
+ // A full update catches everything up and deletes "single".
+ macro_app(&app, out.clone(), 3, false, UpdateOptions::default()).await;
+ assert_eq!(read(&out.join("single.txt")), None);
+ assert_eq!(read(&out.join("item1.txt")).as_deref(), Some("item1@3"));
+ assert_eq!(read(&out.join("x.txt")).as_deref(), Some("x@3"));
+}
+
+/// `list_stable_paths` round-trips into a selector, including an integer key.
+#[tokio::test]
+async fn listed_paths_round_trip_into_a_selector() {
+ let (app, dir, log) = temp_app("round_trip").await;
+ let out = dir.path().join("out");
+ macro_app(&app, out.clone(), 1, true, UpdateOptions::default()).await;
+ drain_sorted(&log);
+ let listed: Vec<StablePath> = inspect::list_stable_paths(&app)
+ .await
+ .unwrap()
+ .into_iter()
+ .filter(|path| path.last() == Some(&StableKey::Int(1)))
+ .collect();
+ assert_eq!(listed.len(), 1, "{listed:?}");
+ macro_app(&app, out.clone(), 2, true, select(listed)).await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec!["group", "used:u1", "used:u2", "write_item:item1"]
+ );
+}
+
+/// An iterator that counts the items taken from it.
+struct Counted<I> {
+ inner: I,
+ taken: Arc<AtomicUsize>,
+}
+
+impl<I: Iterator> Iterator for Counted<I> {
+ type Item = I::Item;
+
+ fn next(&mut self) -> Option<I::Item> {
+ self.taken.fetch_add(1, Ordering::SeqCst);
+ self.inner.next()
+ }
+}
+
+fn counted<T>(items: Vec<T>, taken: &Arc<AtomicUsize>) -> Counted<std::vec::IntoIter<T>> {
+ Counted {
+ inner: items.into_iter(),
+ taken: taken.clone(),
+ }
+}
+
+async fn sources_app(
+ app: &App,
+ out: std::path::PathBuf,
+ version: u32,
+ taken: [Arc<AtomicUsize>; 3],
+ opts: UpdateOptions,
+) {
+ app.update_with_options(opts, move |ctx| async move {
+ let ctx = &ctx;
+ let target = DirTarget::mount(ctx, &out)?;
+ let [each_taken, macro_taken, closure_taken] = taken;
+ let items = vec![
+ ("x".to_string(), "x".to_string()),
+ ("y".to_string(), "y".to_string()),
+ ];
+ cocoindex::mount_each!("each", counted(items, &each_taken), |name| write_item(
+ ctx,
+ name,
+ version,
+ target.clone()
+ ))
+ .await?;
+ let items = vec![("m".to_string(), "m".to_string())];
+ cocoindex::mount_each!("macro", counted(items, &macro_taken), |name| write_item(
+ ctx,
+ name,
+ version,
+ target.clone()
+ ))
+ .await?;
+ let tgt = target.clone();
+ ctx.with_subpath("closure")
+ .mount_each(
+ counted(vec!["c".to_string()], &closure_taken),
+ |name| name.clone(),
+ move |c, name| {
+ let tgt = tgt.clone();
+ async move {
+ ran(&c, format!("closure:{name}"));
+ tgt.declare_file(
+ &c,
+ &format!("{name}.txt"),
+ format!("{name}@{version}").as_bytes(),
+ )
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+/// A `mount_each` whose every child the selector leaves out does not read its
+/// source at all; one with a selected child reads it and runs only that child.
+#[tokio::test]
+async fn a_mount_each_the_selector_leaves_out_never_reads_its_items() {
+ let (app, dir, log) = temp_app("unread_sources").await;
+ let out = dir.path().join("out");
+ let new_counters = || std::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));
+ let taken: [Arc<AtomicUsize>; 3] = new_counters();
+ sources_app(
+ &app,
+ out.clone(),
+ 1,
+ taken.clone(),
+ UpdateOptions::default(),
+ )
+ .await;
+ let read_all: Vec<usize> = taken.iter().map(|t| t.load(Ordering::SeqCst)).collect();
+ assert_eq!(read_all, [3, 2, 2]);
+ assert_eq!(
+ drain_sorted(&log),
+ vec!["closure:c", "write_item:m", "write_item:x", "write_item:y"]
+ );
+
+ let taken: [Arc<AtomicUsize>; 3] = new_counters();
+ sources_app(
+ &app,
+ out.clone(),
+ 2,
+ taken.clone(),
+ select([p(&[s("each"), s("y")])]),
+ )
+ .await;
+ let read_now: Vec<usize> = taken.iter().map(|t| t.load(Ordering::SeqCst)).collect();
+ assert_eq!(read_now, [3, 0, 0]);
+ assert_eq!(drain_sorted(&log), vec!["write_item:y"]);
+ assert_eq!(read(&out.join("x.txt")).as_deref(), Some("x@1"));
+ assert_eq!(read(&out.join("y.txt")).as_deref(), Some("y@2"));
+ assert_eq!(read(&out.join("m.txt")).as_deref(), Some("m@1"));
+ assert_eq!(read(&out.join("c.txt")).as_deref(), Some("c@1"));
+
+ // A full update reads everything again and catches the rest up.
+ sources_app(
+ &app,
+ out.clone(),
+ 2,
+ new_counters(),
+ UpdateOptions::default(),
+ )
+ .await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec!["closure:c", "write_item:m", "write_item:x"]
+ );
+ assert_eq!(read(&out.join("m.txt")).as_deref(), Some("m@2"));
+ assert_eq!(read(&out.join("c.txt")).as_deref(), Some("c@2"));
+}
+
+// ---------------------------------------------------------------------------
+// scope / with_subpath / stats_group / Ctx::mount / mount_target
+// ---------------------------------------------------------------------------
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+struct TableAction {
+ name: String,
+}
+
+struct TableHandler {
+ sink: TargetActionSink<TableAction>,
+}
+
+impl TargetHandler<()> for TableHandler {
+ type TrackingRecord = ();
+ type Action = TableAction;
+
+ fn reconcile(
+ &self,
+ key: StableKey,
+ desired: Option<()>,
+ prev: Vec<()>,
+ _prev_may_be_missing: bool,
+ ) -> Result<Option<TargetReconcileOutput<TableAction, ()>>> {
+ // Always emits for a declared table: its action is what readies the
+ // rows (as in tests/preview.rs).
+ Ok(desired.map(|()| {
+ let table = TableAction {
+ name: key_str(&key),
+ };
+ TargetReconcileOutput {
+ action: if prev.is_empty() {
+ TargetAction::Create(table)
+ } else {
+ TargetAction::Update(table)
+ },
+ sink: self.sink.clone(),
+ tracking_record: Some(()),
+ child_invalidation: None,
+ }
+ }))
+ }
+}
+
+fn table_sink(row_log: Log) -> TargetActionSink<TableAction> {
+ TargetActionSink::from_async_fn_with_child_handler(
+ move |_actions: Vec<TargetAction<TableAction>>| async move { Ok(()) },
+ move |_: &TableAction| {
+ Ok(ChildTargetDef::new::<String, _>(RowHandler {
+ sink: recording_sink(row_log.clone()),
+ }))
+ },
+ )
+}
+
+async fn closure_app(app: &App, sink_log: Log, version: u32, opts: UpdateOptions) {
+ app.update_with_options(opts, move |ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ let tables = register_root_target_states_provider(
+ &ctx,
+ "selector_test/tables",
+ TableHandler {
+ sink: table_sink(sink_log.clone()),
+ },
+ )?;
+ // mount_target: a foreground child; it always runs.
+ let table_rows: TargetStateProvider<String> =
+ mount_target(&ctx, tables.target_state("t", ())).await?;
+
+ let row_child = move |name: &'static str, provider: TargetStateProvider<String>| {
+ move |c: Ctx| async move {
+ ran(&c, name);
+ declare_target_state(&c, provider.target_state(name, format!("v{version}")))?;
+ Ok(())
+ }
+ };
+ ctx.mount("m1", row_child("m1", provider.clone())).await?;
+ ctx.mount("m2", row_child("m2", provider.clone())).await?;
+ // Rows of the mounted table, in background children.
+ ctx.mount("t1", row_child("t1", table_rows.clone())).await?;
+ ctx.mount("t2", row_child("t2", table_rows.clone())).await?;
+ // scope: foreground, always runs; its background children filter.
+ let pr = provider.clone();
+ let v = ctx
+ .scope("sc", move |c| async move {
+ ran(&c, "sc");
+ c.mount("a", row_child("sc/a", pr.clone())).await?;
+ c.mount("b", row_child("sc/b", pr.clone())).await?;
+ Ok(7u32)
+ })
+ .await?;
+ assert_eq!(v, 7);
+ // with_subpath: a directory level, not a component.
+ let sub = ctx.with_subpath("dir");
+ sub.mount("a", row_child("dir/a", provider.clone())).await?;
+ sub.mount("b", row_child("dir/b", provider.clone())).await?;
+ // stats_group: same component, derived context.
+ let pr = provider.clone();
+ ctx.stats_group("grp", move |c, _group| async move {
+ c.mount("g1", row_child("g1", pr.clone())).await?;
+ c.mount("g2", row_child("g2", pr.clone())).await?;
+ Ok(())
+ })
+ .await?;
+ // use_mount_each (closure form): always runs.
+ let pr = provider.clone();
+ ctx.use_mount_each(
+ vec!["ue1", "ue2"],
+ |n: &&str| n.to_string(),
+ move |c, n| {
+ let pr = pr.clone();
+ async move {
+ ran(&c, format!("ue:{n}"));
+ c.mount(
+ "deep",
+ row_child(if n == "ue1" { "ue1/deep" } else { "ue2/deep" }, pr),
+ )
+ .await?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn closure_surfaces_filter_background_mounts_at_every_level() {
+ let (app, _dir, log) = temp_app("closures").await;
+ let sink_log = new_log();
+ closure_app(&app, sink_log.clone(), 1, UpdateOptions::default()).await;
+ assert_eq!(drain_sorted(&log).len(), 15);
+ assert_eq!(drain_sorted(&sink_log).len(), 12);
+
+ closure_app(
+ &app,
+ sink_log.clone(),
+ 2,
+ select([
+ p(&[s("m2")]),
+ p(&[s("t1")]),
+ p(&[s("sc"), s("b")]),
+ p(&[s("dir"), s("a")]),
+ p(&[s("g2")]),
+ p(&[s("ue2"), s("deep")]),
+ ]),
+ )
+ .await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec![
+ "dir/a", "g2", "m2", "sc", "sc/b", "t1", "ue2/deep", "ue:ue1", "ue:ue2"
+ ]
+ );
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec![
+ "update dir/a=v2",
+ "update g2=v2",
+ "update m2=v2",
+ "update sc/b=v2",
+ "update t1=v2",
+ "update ue2/deep=v2",
+ ]
+ );
+
+ // A full update catches the rest up, and deletes nothing.
+ closure_app(&app, sink_log.clone(), 2, UpdateOptions::default()).await;
+ let caught_up = drain_sorted(&sink_log);
+ assert_eq!(caught_up.len(), 6, "{caught_up:?}");
+ assert!(
+ caught_up.iter().all(|a| a.starts_with("update ")),
+ "{caught_up:?}"
+ );
+}
+
+// ---------------------------------------------------------------------------
+// auto_refresh
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn auto_refresh_is_skipped_or_run_by_the_selector() {
+ let (app, _dir, log) = temp_app("auto_refresh").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, version: u32| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ for key in ["ar1", "ar2"] {
+ let provider = provider.clone();
+ ctx.auto_refresh(key, Duration::from_secs(3600), move |c| {
+ let provider = provider.clone();
+ async move {
+ ran(&c, key);
+ declare_target_state(
+ &c,
+ provider.target_state(key, format!("v{version}")),
+ )?;
+ // A background child below the auto_refresh component.
+ let pr = provider.clone();
+ c.mount("kid", move |k| async move {
+ ran(&k, format!("{key}/kid"));
+ declare_target_state(
+ &k,
+ pr.target_state(format!("{key}/kid"), format!("v{version}")),
+ )?;
+ Ok(())
+ })
+ .await?;
+ Ok(())
+ }
+ })
+ .await?;
+ }
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(sink_log.clone(), 1)).await.unwrap();
+ assert_eq!(drain_sorted(&log), vec!["ar1", "ar1/kid", "ar2", "ar2/kid"]);
+ drain_sorted(&sink_log);
+
+ // Selecting below an auto_refresh component runs it as an ancestor.
+ app.update_with_options(
+ select([p(&[s("ar2"), s("kid")])]),
+ body(sink_log.clone(), 2),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["ar2", "ar2/kid"]);
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec!["update ar2/kid=v2", "update ar2=v2"]
+ );
+}
+
+// ---------------------------------------------------------------------------
+// mount_live / mount_each_live / mount_each_live_component
+// ---------------------------------------------------------------------------
+
+/// A live component whose `process()` mounts one row child per `keys`.
+struct RowsLive {
+ name: &'static str,
+ provider: TargetStateProvider<String>,
+ keys: Vec<&'static str>,
+ version: u32,
+}
+
+#[async_trait]
+impl LiveComponent for RowsLive {
+ async fn process(&self, ctx: Ctx) -> Result<()> {
+ ran(&ctx, self.name);
+ let provider = self.provider.clone();
+ let (name, version) = (self.name, self.version);
+ ctx.mount_each(
+ self.keys.clone(),
+ |k: &&str| k.to_string(),
+ move |c, k| {
+ let provider = provider.clone();
+ async move {
+ ran(&c, format!("{name}/{k}"));
+ declare_target_state(
+ &c,
+ provider.target_state(format!("{name}/{k}"), format!("v{version}")),
+ )?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn mount_live_and_mount_each_live_component_follow_the_selector() {
+ let (app, _dir, log) = temp_app("mount_live").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, version: u32| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ ctx.mount_live(
+ "lc1",
+ RowsLive {
+ name: "lc1",
+ provider: provider.clone(),
+ keys: vec!["a", "b"],
+ version,
+ },
+ )
+ .await?;
+ ctx.mount_each_live_component(
+ vec!["e1", "e2"],
+ |n: &&str| n.to_string(),
+ |n| RowsLive {
+ name: n,
+ provider: provider.clone(),
+ keys: vec!["a"],
+ version,
+ },
+ )
+ .await?;
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(sink_log.clone(), 1)).await.unwrap();
+ assert_eq!(drain_sorted(&log).len(), 7);
+ drain_sorted(&sink_log);
+
+ app.update_with_options(
+ select([p(&[s("lc1"), s("b")]), p(&[s("e2")])]),
+ body(sink_log.clone(), 2),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["e2", "e2/a", "lc1", "lc1/b"]);
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec!["update e2/a=v2", "update lc1/b=v2"]
+ );
+
+ // Nothing selected below the root: no live component starts.
+ app.update_with_options(select([]), body(sink_log.clone(), 3))
+ .await
+ .unwrap();
+ assert!(drain_sorted(&log).is_empty());
+ assert!(drain_sorted(&sink_log).is_empty());
+}
+
+/// A scan-only view with integer keys.
+struct IntView {
+ items: Vec<(i64, String)>,
+}
+
+#[async_trait]
+impl LiveMapFeed<i64, String> for IntView {
+ async fn watch(&self, subscriber: LiveMapSubscriber<i64, String>) -> Result<()> {
+ subscriber.mark_ready().await;
+ std::future::pending::<()>().await;
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl LiveMapView<i64, String> for IntView {
+ async fn scan(&self) -> Result<Vec<(i64, String)>> {
+ Ok(self.items.clone())
+ }
+}
+
+/// `mount_each_live` stringifies its keys (`K: Display`), unlike `mount_each`,
+/// which keeps an integer key an `Int`. A selector built the way the
+/// `IntoStableKey` docs suggest for an integer key selects nothing.
+#[tokio::test]
+async fn mount_each_live_keys_are_strings_even_for_integer_keys() {
+ let (app, _dir, log) = temp_app("mount_each_live_keys").await;
+ let body = || {
+ move |ctx: Ctx| async move {
+ ctx.mount_each_live(
+ "feed",
+ IntView {
+ items: vec![(1, "one".into()), (2, "two".into())],
+ },
+ |c, v: String| async move {
+ ran(&c, v);
+ Ok(())
+ },
+ )
+ .await
+ }
+ };
+ app.update(body()).await.unwrap();
+ assert_eq!(drain_sorted(&log), vec!["one", "two"]);
+ let paths = inspect::list_stable_paths(&app).await.unwrap();
+ assert!(paths.contains(&p(&[s("feed"), s("1")])), "{paths:?}");
+ assert!(
+ !paths.contains(&p(&[s("feed"), StableKey::Int(1)])),
+ "{paths:?}"
+ );
+
+ app.update_with_options(
+ UpdateOptions {
+ full_reprocess: true,
+ ..select([p(&[s("feed"), 1i64.into_stable_key()])])
+ },
+ body(),
+ )
+ .await
+ .unwrap();
+ assert!(
+ drain_sorted(&log).is_empty(),
+ "an Int(1) selector matches nothing under mount_each_live"
+ );
+ app.update_with_options(
+ UpdateOptions {
+ full_reprocess: true,
+ ..select([p(&[s("feed"), s("1")])])
+ },
+ body(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["one"]);
+}
+
+// ---------------------------------------------------------------------------
+// Live operators: update / delete / update_full under a selector
+// ---------------------------------------------------------------------------
+
+struct Ops {
+ provider: TargetStateProvider<String>,
+ full_keys: Vec<&'static str>,
+ then_update: Vec<&'static str>,
+ then_delete: Vec<&'static str>,
+}
+
+#[async_trait]
+impl LiveComponent for Ops {
+ async fn process(&self, ctx: Ctx) -> Result<()> {
+ ran(&ctx, "ops");
+ let provider = self.provider.clone();
+ ctx.mount_each(
+ self.full_keys.clone(),
+ |k: &&str| k.to_string(),
+ move |c, k| {
+ let provider = provider.clone();
+ async move {
+ ran(&c, format!("full/{k}"));
+ declare_target_state(&c, provider.target_state(k, "full".to_string()))?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ }
+
+ async fn process_live(&self, operator: LiveComponentOperator) -> Result<()> {
+ operator.update_full().await?;
+ for k in &self.then_update {
+ let provider = self.provider.clone();
+ let k = *k;
+ operator
+ .update(k, move |c| async move {
+ ran(&c, format!("op/{k}"));
+ declare_target_state(&c, provider.target_state(k, "op".to_string()))?;
+ Ok(())
+ })
+ .await?;
+ }
+ for k in &self.then_delete {
+ operator.delete(k).await?;
+ }
+ operator.mark_ready().await;
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn operator_update_and_delete_skip_unselected_keys() {
+ let (app, _dir, log) = temp_app("operators").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, then_update: Vec<&'static str>, then_delete: Vec<&'static str>| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ ctx.mount_live(
+ "ops",
+ Ops {
+ provider,
+ full_keys: vec!["a", "b"],
+ then_update,
+ then_delete,
+ },
+ )
+ .await
+ }
+ };
+ app.update(body(sink_log.clone(), vec!["c", "d"], vec![]))
+ .await
+ .unwrap();
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec![
+ "create a=full",
+ "create b=full",
+ "create c=op",
+ "create d=op"
+ ]
+ );
+ drain_sorted(&log);
+
+ // Selected: a, c. update(d) and delete(b) are skipped; delete(a) runs.
+ app.update_with_options(
+ UpdateOptions {
+ full_reprocess: true,
+ ..select([p(&[s("ops"), s("a")]), p(&[s("ops"), s("c")])])
+ },
+ body(sink_log.clone(), vec!["c", "d"], vec!["a", "b"]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["full/a", "op/c", "ops"]);
+ // update_full's commit removes "c" (selected, and not declared by
+ // process(), as an unselective full pass would) before update(c) mounts it
+ // again; "d" (unselected) is kept, and so is "b" (delete skipped).
+ // full_reprocess re-emits "a".
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec!["create c=op", "delete a", "delete c", "update a=full"]
+ );
+
+ // A full run without operators: c, d no longer declared by process().
+ app.update(body(sink_log.clone(), vec![], vec![]))
+ .await
+ .unwrap();
+ let full = drain_sorted(&sink_log);
+ assert!(full.contains(&"create a=full".to_string()), "{full:?}");
+ assert!(full.contains(&"delete c".to_string()), "{full:?}");
+ assert!(full.contains(&"delete d".to_string()), "{full:?}");
+ assert!(!full.iter().any(|a| a.contains(" b")), "{full:?}");
+}
+
+/// A live component that turns channel messages into `operator.update`
+/// calls, and tells the test when each has synced.
+struct Events {
+ provider: TargetStateProvider<String>,
+ rx: Mutex<Option<mpsc::UnboundedReceiver<&'static str>>>,
+ synced: mpsc::UnboundedSender<&'static str>,
+ ready: Arc<Notify>,
+ dropped: Arc<AtomicBool>,
+}
+
+struct SetOnDrop(Arc<AtomicBool>);
+impl Drop for SetOnDrop {
+ fn drop(&mut self) {
+ self.0.store(true, Ordering::SeqCst);
+ }
+}
+
+#[async_trait]
+impl LiveComponent for Events {
+ async fn process(&self, ctx: Ctx) -> Result<()> {
+ ran(&ctx, "events");
+ Ok(())
+ }
+
+ async fn process_live(&self, operator: LiveComponentOperator) -> Result<()> {
+ let _guard = SetOnDrop(self.dropped.clone());
+ operator.update_full().await?;
+ operator.mark_ready().await;
+ self.ready.notify_one();
+ let mut rx = self.rx.lock().unwrap().take().unwrap();
+ while let Some(k) = rx.recv().await {
+ let provider = self.provider.clone();
+ operator
+ .update(k, move |c| async move {
+ ran(&c, format!("event/{k}"));
+ declare_target_state(&c, provider.target_state(k, "ev".to_string()))?;
+ Ok(())
+ })
+ .await?;
+ let _ = self.synced.send(k);
+ }
+ Ok(())
+ }
+}
+
+struct EventsHarness {
+ tx: mpsc::UnboundedSender<&'static str>,
+ synced: mpsc::UnboundedReceiver<&'static str>,
+ ready: Arc<Notify>,
+ dropped: Arc<AtomicBool>,
+}
+
+#[allow(clippy::type_complexity)]
+fn events_body(
+ sink_log: Log,
+) -> (
+ EventsHarness,
+ impl FnOnce(Ctx) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>,
+) {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let (synced_tx, synced) = mpsc::unbounded_channel();
+ let ready = Arc::new(Notify::new());
+ let dropped = Arc::new(AtomicBool::new(false));
+ let harness = EventsHarness {
+ tx,
+ synced,
+ ready: ready.clone(),
+ dropped: dropped.clone(),
+ };
+ let body = move |ctx: Ctx| -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>> {
+ Box::pin(async move {
+ let provider = rows(&ctx, &sink_log)?;
+ ctx.mount_live(
+ "live",
+ Events {
+ provider,
+ rx: Mutex::new(Some(rx)),
+ synced: synced_tx,
+ ready,
+ dropped,
+ },
+ )
+ .await
+ })
+ };
+ (harness, body)
+}
+
+fn live(opts: UpdateOptions) -> UpdateOptions {
+ UpdateOptions { live: true, ..opts }
+}
+
+/// Live mode under a selector: a later event on an unselected key is
+/// dropped for the whole update, while a selected key goes through.
+#[tokio::test]
+async fn live_events_on_unselected_keys_are_skipped_for_the_whole_update() {
+ let (app, _dir, log) = temp_app("live_selected_events").await;
+ let sink_log = new_log();
+ let (mut h, body) = events_body(sink_log.clone());
+ let handle = app
+ .start_update_with_options(live(select([p(&[s("live"), s("x")])])), body)
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(10), h.ready.notified())
+ .await
+ .unwrap();
+ h.tx.send("y").unwrap();
+ h.tx.send("x").unwrap();
+ for _ in 0..2 {
+ tokio::time::timeout(Duration::from_secs(10), h.synced.recv())
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_sorted(&log), vec!["event/x", "events"]);
+ assert_eq!(drain_sorted(&sink_log), vec!["create x=ev"]);
+ let _ = app.drop_state().await;
+ let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;
+}
+
+// ---------------------------------------------------------------------------
+// Concurrency: a selective update while a live update runs
+// ---------------------------------------------------------------------------
+
+/// Runs `second` while a live, non-selective update of the same app is
+/// running a live component at `/live`, then sends that live update an event.
+/// Returns (event processed by the live update, its process_live dropped,
+/// the live update's result if it finished: `Some(is_ok)`).
+async fn second_update_during_live(
+ name: &str,
+ second: UpdateOptions,
+) -> (bool, bool, Option<bool>) {
+ let (app, _dir, _log) = temp_app(name).await;
+ let sink_log = new_log();
+ let (mut h, body) = events_body(sink_log.clone());
+ let live_handle = app
+ .start_update_with_options(live(UpdateOptions::default()), body)
+ .unwrap();
+ tokio::time::timeout(Duration::from_secs(10), h.ready.notified())
+ .await
+ .unwrap();
+ // Sanity: the live update reacts before the second update.
+ h.tx.send("before").unwrap();
+ tokio::time::timeout(Duration::from_secs(10), h.synced.recv())
+ .await
+ .unwrap();
+
+ // The second update mounts its own `/live` (its own channel, unused).
+ let (_h2, body2) = events_body(sink_log.clone());
+ let other_body = move |ctx: Ctx| async move {
+ ctx.mount("other", move |_c| async move { Ok(()) }).await?;
+ body2(ctx).await
+ };
+ tokio::time::timeout(
+ Duration::from_secs(20),
+ app.update_with_options(second, other_body),
+ )
+ .await
+ .expect("second update hung")
+ .unwrap();
+
+ let sent = h.tx.send("after").is_ok();
+ let processed = sent
+ && tokio::time::timeout(Duration::from_secs(3), h.synced.recv())
+ .await
+ .ok()
+ .flatten()
+ .is_some();
+ let dropped = h.dropped.load(Ordering::SeqCst);
+ let finished = tokio::time::timeout(Duration::from_millis(500), live_handle.result())
+ .await
+ .ok()
+ .map(|result| result.is_ok());
+ let _ = app.drop_state().await;
+ (processed, dropped, finished)
+}
+
+#[tokio::test]
+async fn concurrent_selective_update_not_reaching_the_live_component_leaves_it_running() {
+ let outcome = second_update_during_live("conc_unreached", select([p(&[s("other")])])).await;
+ assert_eq!(outcome, (true, false, None));
+}
+
+/// An update that only runs through `/live`, on the way to a path below it, runs
+/// its own controller beside the running one.
+#[tokio::test]
+async fn concurrent_selective_update_through_the_live_component_leaves_it_running() {
+ let outcome =
+ second_update_during_live("conc_reached_below", select([p(&[s("live"), s("k")])])).await;
+ assert_eq!(
+ outcome,
+ (true, false, None),
+ "(event processed, process_live dropped, live update result)"
+ );
+}
+
+/// A preview applies nothing, so it never replaces what is running.
+#[tokio::test]
+async fn concurrent_preview_leaves_the_live_component_running() {
+ let outcome = second_update_during_live(
+ "conc_preview",
+ UpdateOptions {
+ preview: true,
+ ..UpdateOptions::default()
+ },
+ )
+ .await;
+ assert_eq!(outcome, (true, false, None));
+}
+
+/// A one-shot update that selects the live component runs its own instance
+/// beside the running one, as a plain one-shot update does.
+#[tokio::test]
+async fn concurrent_selective_update_selecting_the_live_component_leaves_it_running() {
+ let outcome = second_update_during_live("conc_reached_exact", select([p(&[s("live")])])).await;
+ assert_eq!(outcome, (true, false, None));
+}
+
+/// The same without any selector: a one-shot update leaves a running live
+/// update alone.
+#[tokio::test]
+async fn concurrent_full_update_reaching_the_live_component_leaves_it_running() {
+ let outcome = second_update_during_live("conc_full", UpdateOptions::default()).await;
+ assert_eq!(outcome, (true, false, None));
+}
+
+// ---------------------------------------------------------------------------
+// Preview with a selector
+// ---------------------------------------------------------------------------
+
+fn describe(actions: &[PreviewAction]) -> Vec<String> {
+ let mut v: Vec<String> = actions
+ .iter()
+ .map(|action| {
+ let (verb, value) = match action {
+ PreviewAction::Create(v) => ("create", v),
+ PreviewAction::Update(v) => ("update", v),
+ PreviewAction::Delete(v) => ("delete", v),
+ };
+ let row: RowAction = value.decode().unwrap();
+ format!("{verb} {}={}", row.key, row.value.unwrap_or_default())
+ })
+ .collect();
+ v.sort();
+ v
+}
+
+#[tokio::test]
+async fn preview_with_a_selector_plans_only_the_selected_and_persists_nothing() {
+ let (app, _dir, log) = temp_app("preview_selector").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, keys: Vec<&'static str>, version: u32| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ ctx.mount_each(
+ keys,
+ |k: &&str| k.to_string(),
+ move |c, k| {
+ let provider = provider.clone();
+ async move {
+ ran(&c, k);
+ declare_target_state(&c, provider.target_state(k, format!("v{version}")))?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(sink_log.clone(), vec!["a", "b", "c"], 1))
+ .await
+ .unwrap();
+ drain_sorted(&log);
+ drain_sorted(&sink_log);
+
+ // "c" is gone from the source and unselected: no delete is planned.
+ let handle = app
+ .start_update_with_options(
+ UpdateOptions {
+ preview: true,
+ ..select([p(&[s("a")])])
+ },
+ body(sink_log.clone(), vec!["a", "b"], 2),
+ )
+ .unwrap();
+ let actions = handle.preview_actions().await.unwrap();
+ assert_eq!(describe(&actions), vec!["update a=v2"]);
+ assert_eq!(drain_sorted(&log), vec!["a"]);
+ assert!(drain_sorted(&sink_log).is_empty());
+
+ // Nothing persisted: a full update plans every change itself.
+ app.update(body(sink_log.clone(), vec!["a", "b"], 2))
+ .await
+ .unwrap();
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec!["delete c", "update a=v2", "update b=v2"]
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Memoized children under a selector
+// ---------------------------------------------------------------------------
+
+static MEMO_RUNS: AtomicUsize = AtomicUsize::new(0);
+
+#[cocoindex::function]
+async fn memo_parent(ctx: &Ctx, version: u32, target: DirTarget) -> Result<()> {
+ MEMO_RUNS.fetch_add(1, Ordering::SeqCst);
+ for name in ["pa", "pb"] {
+ let target = target.clone();
+ ctx.mount(name, move |c| async move {
+ ran(&c, name);
+ target.declare_file(
+ &c,
+ &format!("{name}.txt"),
+ format!("{name}@{version}").as_bytes(),
+ )
+ })
+ .await?;
+ }
+ Ok(())
+}
+
+/// A memoized ancestor of a selected path drops its memo under the selector;
+/// the next unselective update must run it again and catch up the child the
+/// selective update skipped.
+#[tokio::test]
+async fn memoized_ancestor_runs_again_after_a_selective_update() {
+ let (app, dir, log) = temp_app("memo_ancestor").await;
+ let out = dir.path().join("out");
+ let body = |out: std::path::PathBuf, version: u32| {
+ move |ctx: Ctx| async move {
+ let ctx = &ctx;
+ let target = DirTarget::mount(ctx, &out)?;
+ cocoindex::mount!(memo_parent(ctx, version, target)).await?;
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(out.clone(), 1)).await.unwrap();
+ assert_eq!(drain_sorted(&log), vec!["pa", "pb"]);
+ // Unchanged: memo hit.
+ app.update(body(out.clone(), 1)).await.unwrap();
+ assert!(drain_sorted(&log).is_empty());
+
+ // New version, only pa selected.
+ app.update_with_options(
+ select([p(&[s("memo_parent"), s("pa")])]),
+ body(out.clone(), 2),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["pa"]);
+ assert_eq!(read(&out.join("pb.txt")).as_deref(), Some("pb@1"));
+
+ // Same version 2, no selector: must not hit a stale memo.
+ app.update(body(out.clone(), 2)).await.unwrap();
+ assert_eq!(drain_sorted(&log), vec!["pa", "pb"]);
+ assert_eq!(read(&out.join("pb.txt")).as_deref(), Some("pb@2"));
+}
+
+// ---------------------------------------------------------------------------
+// full_reprocess with a selector: what it reaches
+// ---------------------------------------------------------------------------
+
+/// A memoized function standing in for a paid call (an embedding, an LLM).
+#[cocoindex::function(memo)]
+async fn expensive(ctx: &Ctx, name: String) -> Result<String> {
+ ran(ctx, format!("expensive:{name}"));
+ Ok(name.to_uppercase())
+}
+
+#[cocoindex::function]
+async fn embed(ctx: &Ctx, name: String) -> Result<String> {
+ ran(ctx, format!("embed:{name}"));
+ expensive(ctx, name).await
+}
+
+#[cocoindex::function]
+async fn touch(ctx: &Ctx, name: String) -> Result<()> {
+ ran(ctx, format!("touch:{name}"));
+ Ok(())
+}
+
+async fn embed_app(app: &App, opts: UpdateOptions) {
+ app.update_with_options(opts, move |ctx| async move {
+ let ctx = &ctx;
+ cocoindex::mount!("target", touch(ctx, "target".to_string())).await?;
+ let files = vec![
+ ("f1".to_string(), "f1".to_string()),
+ ("f2".to_string(), "f2".to_string()),
+ ];
+ let out = cocoindex::use_mount_each!(files, |name| embed(ctx, name)).await?;
+ assert_eq!(out, vec!["F1".to_string(), "F2".to_string()]);
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+/// Docs: "Add `full_reprocess=True` to force the selected components to run:
+/// it applies only to them and to the ancestors that reach them." An
+/// unselected `use_mount_each!` child is neither, yet it re-executes, and so
+/// does every memoized function it calls.
+#[tokio::test]
+async fn selective_full_reprocess_leaves_unselected_use_mount_children_alone() {
+ let (app, _dir, log) = temp_app("full_reprocess_reach").await;
+ embed_app(&app, UpdateOptions::default()).await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec![
+ "embed:f1",
+ "embed:f2",
+ "expensive:f1",
+ "expensive:f2",
+ "touch:target"
+ ]
+ );
+
+ embed_app(
+ &app,
+ UpdateOptions {
+ full_reprocess: true,
+ ..select([p(&[s("target")])])
+ },
+ )
+ .await;
+ assert_eq!(
+ drain_sorted(&log),
+ vec!["touch:target"],
+ "only the selected component (and the root) should re-execute"
+ );
+}
+
+/// After a selective update without full_reprocess, nothing about an
+/// unselected `use_mount` child that hit its memo changes: the next plain
+/// update hits it again.
+#[tokio::test]
+async fn selective_update_keeps_the_memo_of_an_unchanged_use_mount_child() {
+ let (app, _dir, log) = temp_app("use_mount_memo_kept").await;
+ embed_app(&app, UpdateOptions::default()).await;
+ drain_sorted(&log);
+ embed_app(&app, select([p(&[s("target")])])).await;
+ let selective = drain_sorted(&log);
+ embed_app(&app, UpdateOptions::default()).await;
+ assert_eq!((selective, drain_sorted(&log)), (vec![], vec![]));
+}
+
+// ---------------------------------------------------------------------------
+// Two selective updates in parallel on disjoint slices
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn parallel_selective_updates_on_disjoint_slices_both_apply_and_delete_nothing() {
+ let (app, _dir, _log) = temp_app("parallel_slices").await;
+ let sink_log = new_log();
+ // Both updates are in flight at once; the root's build permit orders
+ // their root runs, so a barrier across them would deadlock.
+ let body = |sink_log: Log, version: u32| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ let keys: Vec<&'static str> = vec!["a", "b", "c", "d"];
+ ctx.mount_each(
+ keys,
+ |k: &&str| k.to_string(),
+ move |c, k| {
+ let provider = provider.clone();
+ async move {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ declare_target_state(&c, provider.target_state(k, format!("v{version}")))?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(sink_log.clone(), 1)).await.unwrap();
+ drain_sorted(&sink_log);
+
+ let one = app.update_with_options(select([p(&[s("a")])]), body(sink_log.clone(), 2));
+ let two = app.update_with_options(select([p(&[s("c")])]), body(sink_log.clone(), 3));
+ let (r1, r2) = tokio::time::timeout(Duration::from_secs(20), async { tokio::join!(one, two) })
+ .await
+ .expect("parallel selective updates hung");
+ r1.unwrap();
+ r2.unwrap();
+ assert_eq!(drain_sorted(&sink_log), vec!["update a=v2", "update c=v3"]);
+
+ // A plain update after: only b, d change, nothing is deleted.
+ app.update(body(sink_log.clone(), 4)).await.unwrap();
+ assert_eq!(
+ drain_sorted(&sink_log),
+ vec!["update a=v4", "update b=v4", "update c=v4", "update d=v4"]
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Path construction: what a Rust user can and cannot build
+// ---------------------------------------------------------------------------
+
+/// The shared docs prose says "a mount without a subpath adds the `Symbol` of
+/// the function's name". In Rust, `mount!`/`use_mount!`/`mount_each!` add a
+/// `Str` (cocoindex_macros `expand_single_mount`): a selector built from the
+/// docs selects nothing.
+#[tokio::test]
+async fn a_mount_key_is_a_str_in_rust_so_a_symbol_path_selects_nothing() {
+ let (app, dir, log) = temp_app("symbol_vs_str").await;
+ let out = dir.path().join("out");
+ macro_app(&app, out.clone(), 1, true, UpdateOptions::default()).await;
+ drain_sorted(&log);
+ macro_app(
+ &app,
+ out.clone(),
+ 2,
+ true,
+ select([p(&[StableKey::Symbol(Arc::from("write_one"))])]),
+ )
+ .await;
+ let ran_now = drain_sorted(&log);
+ assert!(
+ !ran_now.contains(&"write_one:default".to_string()),
+ "{ran_now:?}"
+ );
+ assert_eq!(read(&out.join("default.txt")).as_deref(), Some("default@1"));
+}
+
+// ---------------------------------------------------------------------------
+// Ancestors gone, new items, nested live components
+// ---------------------------------------------------------------------------
+
+#[tokio::test]
+async fn new_items_follow_the_selector_and_a_gone_ancestor_stays_whole() {
+ let (app, _dir, _log) = temp_app("gone_ancestor").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, groups: Vec<&'static str>, kids: Vec<&'static str>| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ for g in groups {
+ let provider = provider.clone();
+ let kids = kids.clone();
+ ctx.mount(g, move |c| async move {
+ c.mount_each(
+ kids,
+ |k: &&str| k.to_string(),
+ move |cc, k| {
+ let provider = provider.clone();
+ async move {
+ declare_target_state(
+ &cc,
+ provider.target_state(format!("{g}/{k}"), "v".to_string()),
+ )?;
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ })
+ .await?;
+ }
+ Ok::<(), Error>(())
+ }
+ };
+ app.update(body(sink_log.clone(), vec!["g1", "g2"], vec!["a", "b"]))
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&sink_log).len(), 4);
+
+ // New kid "c": created only where selected.
+ app.update_with_options(
+ select([p(&[s("g1"), s("c")])]),
+ body(sink_log.clone(), vec!["g1", "g2"], vec!["a", "b", "c"]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&sink_log), vec!["create g1/c=v"]);
+
+ // g2 gone from the source, a path below it selected: g2 stays whole.
+ app.update_with_options(
+ select([p(&[s("g2"), s("a")])]),
+ body(sink_log.clone(), vec!["g1"], vec!["a", "b", "c"]),
+ )
+ .await
+ .unwrap();
+ assert!(drain_sorted(&sink_log).is_empty());
+
+ // A selector covering g2 deletes it.
+ app.update_with_options(
+ select([p(&[s("g2")])]),
+ body(sink_log.clone(), vec!["g1"], vec!["a", "b", "c"]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&sink_log), vec!["delete g2/a", "delete g2/b"]);
+}
+
+/// A live component whose `process()` mounts two live components.
+struct Outer {
+ provider: TargetStateProvider<String>,
+ version: u32,
+}
+
+#[async_trait]
+impl LiveComponent for Outer {
+ async fn process(&self, ctx: Ctx) -> Result<()> {
+ ran(&ctx, "outer");
+ for name in ["in1", "in2"] {
+ ctx.mount_live(
+ name,
+ RowsLive {
+ name,
+ provider: self.provider.clone(),
+ keys: vec!["x", "y"],
+ version: self.version,
+ },
+ )
+ .await?;
+ }
+ Ok(())
+ }
+}
+
+#[tokio::test]
+async fn nested_live_components_follow_the_selector_in_update_and_preview() {
+ let (app, _dir, log) = temp_app("nested_live").await;
+ let sink_log = new_log();
+ let body = |sink_log: Log, version: u32| {
+ move |ctx: Ctx| async move {
+ let provider = rows(&ctx, &sink_log)?;
+ ctx.mount_live("outer", Outer { provider, version }).await
+ }
+ };
+ app.update(body(sink_log.clone(), 1)).await.unwrap();
+ assert_eq!(drain_sorted(&log).len(), 7);
+ drain_sorted(&sink_log);
+
+ let selector = || select([p(&[s("outer"), s("in2"), s("y")])]);
+ let actions = app
+ .start_update_with_options(
+ UpdateOptions {
+ preview: true,
+ ..selector()
+ },
+ body(sink_log.clone(), 2),
+ )
+ .unwrap()
+ .preview_actions()
+ .await
+ .unwrap();
+ assert_eq!(describe(&actions), vec!["update in2/y=v2"]);
+ assert_eq!(drain_sorted(&log), vec!["in2", "in2/y", "outer"]);
+ assert!(drain_sorted(&sink_log).is_empty());
+
+ app.update_with_options(selector(), body(sink_log.clone(), 2))
+ .await
+ .unwrap();
+ assert_eq!(drain_sorted(&log), vec!["in2", "in2/y", "outer"]);
+ assert_eq!(drain_sorted(&sink_log), vec!["update in2/y=v2"]);
+}
+
+// ---------------------------------------------------------------------------
+// A memoized function that mounts a live component the selector skips
+// ---------------------------------------------------------------------------
+
+/// A memoized function that starts an auto_refresh component. Mounting a
+/// child makes the function's memo unusable (`has_child_components`), or a
+/// later hit would skip the mount and the child would be taken as gone.
+#[cocoindex::function(memo)]
+async fn start_refresh(ctx: &Ctx, version: u32, target: DirTarget) -> Result<()> {
+ ran(ctx, "start_refresh");
+ ctx.auto_refresh("ar", Duration::from_secs(3600), move |c| {
+ let target = target.clone();
+ async move {
+ ran(&c, "ar");
+ target.declare_file(&c, "ar.txt", format!("ar@{version}").as_bytes())
+ }
+ })
+ .await
+}
+
+#[cocoindex::function(memo)]
+async fn start_mount(ctx: &Ctx, version: u32, target: DirTarget) -> Result<()> {
+ ran(ctx, "start_mount");
+ ctx.mount("bg", move |c| async move {
+ ran(&c, "bg");
+ target.declare_file(&c, "bg.txt", format!("bg@{version}").as_bytes())
+ })
+ .await?;
+ Ok(())
+}
+
+async fn memo_mount_app(
+ app: &App,
+ out: std::path::PathBuf,
+ live: bool,
+ opts: UpdateOptions,
+) -> Result<()> {
+ app.update_with_options(opts, move |ctx| async move {
+ let ctx = &ctx;
+ let target = DirTarget::mount(ctx, &out)?;
+ if live {
+ start_refresh(ctx, 1, target.clone()).await?;
+ } else {
+ start_mount(ctx, 1, target.clone()).await?;
+ }
+ ctx.mount("other", |_c| async move { Ok(()) }).await?;
+ Ok(())
+ })
+ .await
+}
+
+const MEMO_MOUNT_ERROR: &str = "mounted child components";
+
+/// `Ctx::mount` in a memoized function is rejected whether or not the
+/// selector skips the child: its mount frame joins the function's frame
+/// before the engine's skip.
+#[tokio::test]
+async fn memoized_fn_mounting_a_skipped_background_child_is_still_rejected() {
+ let (app, dir, _log) = temp_app("memo_fn_skipped_bg").await;
+ let out = dir.path().join("out");
+ let plain = memo_mount_app(&app, out.clone(), false, UpdateOptions::default()).await;
+ assert!(plain.unwrap_err().to_string().contains(MEMO_MOUNT_ERROR));
+ let sliced = memo_mount_app(&app, out.clone(), false, select([p(&[s("other")])])).await;
+ assert!(sliced.unwrap_err().to_string().contains(MEMO_MOUNT_ERROR));
+}
+
+/// The same with `Ctx::auto_refresh` (and so `mount_live`, `mount_each_live`,
+/// `mount_each_live_component`): on the selector's skip it returns before
+/// joining its mount frame (`frame_guard`), so the function is not rejected
+/// and its memo is stored. Every later plain update then hits that memo:
+/// the error is masked for good and `/ar` never mounts. Python rejects this
+/// case (`test_memoized_function_that_mounts_is_rejected_even_if_its_mounts_are_skipped`).
+#[tokio::test]
+async fn memoized_fn_mounting_a_skipped_live_component_is_still_rejected() {
+ let (app, dir, log) = temp_app("memo_fn_skipped_live").await;
+ let out = dir.path().join("out");
+ let plain = memo_mount_app(&app, out.clone(), true, UpdateOptions::default()).await;
+ assert!(plain.unwrap_err().to_string().contains(MEMO_MOUNT_ERROR));
+ drain_sorted(&log);
+
+ let sliced = memo_mount_app(&app, out.clone(), true, select([p(&[s("other")])])).await;
+ let after = memo_mount_app(&app, out.clone(), true, UpdateOptions::default()).await;
+ let ran_after = drain_sorted(&log);
+ assert!(
+ sliced
+ .as_ref()
+ .is_err_and(|e| e.to_string().contains(MEMO_MOUNT_ERROR)),
+ "selective update accepted the memoized fn: {sliced:?}; the plain update after: \
+ {after:?}, ran {ran_after:?}, ar.txt {:?}",
+ read(&out.join("ar.txt"))
+ );
+}
diff --git a/rust/sdk/cocoindex/tests/component_selector_memo_key.rs b/rust/sdk/cocoindex/tests/component_selector_memo_key.rs
new file mode 100644
index 00000000..9554c6a6
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/component_selector_memo_key.rs
@@ -0,0 +1,86 @@
+//! A child that the update's component selector leaves out runs no user code:
+//! `mount_each!` and `mount!` compute no component-memo key for it (the key is
+//! `MemoInput::write_memo_key` over its arguments).
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use cocoindex::memo::{MemoInput, MemoKeyWriter};
+use cocoindex::prelude::*;
+use cocoindex::{ComponentSelector, StablePath};
+
+static KEYS: AtomicUsize = AtomicUsize::new(0);
+static RUNS: AtomicUsize = AtomicUsize::new(0);
+
+#[derive(Clone)]
+struct Counted(String);
+
+#[cocoindex::async_trait]
+impl MemoInput for Counted {
+ fn write_memo_key(&self, writer: &mut MemoKeyWriter<'_>) -> Result<()> {
+ KEYS.fetch_add(1, Ordering::SeqCst);
+ writer.write(&self.0)
+ }
+
+ fn has_memo_state(&self) -> bool {
+ false
+ }
+}
+
+#[cocoindex::function]
+async fn leaf(_ctx: &Ctx, item: Counted) -> Result<()> {
+ let _ = item;
+ RUNS.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+}
+
+async fn run(app: &App, opts: UpdateOptions) {
+ app.update_with_options(opts, move |ctx| async move {
+ let ctx = &ctx;
+ let items: Vec<(String, Counted)> = (0..100)
+ .map(|i| (format!("k{i}"), Counted(format!("v{i}"))))
+ .collect();
+ cocoindex::mount_each!("items", items, |item| leaf(ctx, item)).await?;
+ for i in 0..20 {
+ let key = format!("single{i}");
+ cocoindex::mount!(key, leaf(ctx, Counted(format!("s{i}")))).await?;
+ }
+ Ok(())
+ })
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn unselected_children_compute_no_memo_key() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = App::builder("selector_memo_key")
+ .db_path(dir.path().join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap();
+ run(&app, UpdateOptions::default()).await;
+ KEYS.store(0, Ordering::SeqCst);
+ RUNS.store(0, Ordering::SeqCst);
+
+ let selected = StablePath::root()
+ .concat_part(StableKey::Str(Arc::from("items")))
+ .concat_part(StableKey::Str(Arc::from("k7")));
+ run(
+ &app,
+ UpdateOptions {
+ component_selector: Some(ComponentSelector::new([selected])),
+ full_reprocess: true,
+ ..UpdateOptions::default()
+ },
+ )
+ .await;
+ let runs = RUNS.load(Ordering::SeqCst);
+ let keys = KEYS.load(Ordering::SeqCst);
+ assert_eq!(runs, 1, "only the selected child runs");
+ // Only the selected child computes its key.
+ assert_eq!(
+ keys, 1,
+ "memo keys computed for {keys} children, though 119 are unselected"
+ );
+}
diff --git a/rust/sdk/cocoindex/tests/pipeline.rs b/rust/sdk/cocoindex/tests/pipeline.rs
index c7e61154..00bcdf01 100644
--- a/rust/sdk/cocoindex/tests/pipeline.rs
+++ b/rust/sdk/cocoindex/tests/pipeline.rs
@@ -2584,6 +2584,76 @@ async fn ctx_mount_each() {
.unwrap();
}
+/// The Rust SDK takes the same selector as Python: an unselected background
+/// mount (`ctx.mount`, for the first key here, or `ctx.mount_each`) does not run
+/// and is not treated as gone.
+#[tokio::test]
+async fn component_selector_runs_only_the_selected_background_mounts() {
+ use cocoindex::{ComponentSelector, StableKey, StablePath, UpdateOptions};
+ use std::sync::{Arc, Mutex};
+
+ async fn run(
+ app: &App,
+ mounted: &'static [&'static str],
+ selector: Option<ComponentSelector>,
+ ) -> Vec<String> {
+ let ran = Arc::new(Mutex::new(Vec::new()));
+ let recorded = ran.clone();
+ app.update_with_options(
+ UpdateOptions {
+ component_selector: selector,
+ ..UpdateOptions::default()
+ },
+ move |ctx| async move {
+ let (singles, each) = mounted.split_at(1);
+ for key in singles {
+ let ran = recorded.clone();
+ ctx.mount(key, move |_ctx| async move {
+ ran.lock().unwrap().push(key.to_string());
+ Ok(())
+ })
+ .await?;
+ }
+ let each: Vec<String> = each.iter().map(|key| key.to_string()).collect();
+ ctx.mount_each(
+ each,
+ |key: &String| key.clone(),
+ move |_ctx, key: String| {
+ let ran = recorded.clone();
+ async move {
+ ran.lock().unwrap().push(key);
+ Ok(())
+ }
+ },
+ )
+ .await?;
+ Ok(())
+ },
+ )
+ .await
+ .unwrap();
+ let mut names = ran.lock().unwrap().clone();
+ names.sort();
+ names
+ }
+
+ let (app, _dir) = temp_app("component_selector").await;
+ assert_eq!(run(&app, &["a", "b"], None).await, ["a", "b"]);
+
+ let select_a =
+ || ComponentSelector::new([StablePath::root().concat_part(StableKey::Str(Arc::from("a")))]);
+ assert_eq!(run(&app, &["a", "b"], Some(select_a())).await, ["a"]);
+ let select_b =
+ || ComponentSelector::new([StablePath::root().concat_part(StableKey::Str(Arc::from("b")))]);
+ assert_eq!(run(&app, &["a", "b"], Some(select_b())).await, ["b"]);
+ // "b" is no longer mounted, and the selector leaves it alone.
+ assert_eq!(run(&app, &["a"], Some(select_a())).await, ["a"]);
+ assert_eq!(
+ run(&app, &["a", "b"], Some(ComponentSelector::new([]))).await,
+ Vec::<String>::new()
+ );
+}
+
#[tokio::test]
async fn ctx_mount_each_independent_memo() {
use std::sync::Arc;
diff --git a/rust/sdk/cocoindex_macros/src/lib.rs b/rust/sdk/cocoindex_macros/src/lib.rs
index e3a1a661..9e1c3f0a 100644
--- a/rust/sdk/cocoindex_macros/src/lib.rs
+++ b/rust/sdk/cocoindex_macros/src/lib.rs
@@ -1555,7 +1555,7 @@ fn parse_grouped_call(expr: &Expr) -> syn::Result<(Path, Vec<Expr>)> {
/// `key` (any `cocoindex::IntoStableKey`) if given, else the function's name.
#[proc_macro]
pub fn use_mount(input: TokenStream) -> TokenStream {
- expand_single_mount(input, "use_mount", quote! { __use_mount_fp })
+ expand_single_mount(input, "use_mount", quote! { __use_mount_fp }, false)
}
/// `mount!(my_fn(ctx, a, b))` or `mount!(key, my_fn(ctx, a, b))`.
@@ -1569,12 +1569,17 @@ pub fn use_mount(input: TokenStream) -> TokenStream {
/// `key` if given, else the function's name.
#[proc_macro]
pub fn mount(input: TokenStream) -> TokenStream {
- expand_single_mount(input, "mount", quote! { __mount_fp })
+ expand_single_mount(input, "mount", quote! { __mount_fp }, true)
}
/// Shared expansion of `use_mount!` and `mount!`: the same grouped-call
/// parse and component-memo fingerprint, dispatched to `Ctx::<method>`.
-fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) -> TokenStream {
+fn expand_single_mount(
+ input: TokenStream,
+ name: &str,
+ method: TokenStream2,
+ may_be_left_out: bool,
+) -> TokenStream {
let parsed = parse_macro_input!(input with Punctuated::<Expr, Token![,]>::parse_terminated);
let elems: Vec<Expr> = parsed.into_iter().collect();
let (key_expr, call) = match elems.as_slice() {
@@ -1616,20 +1621,37 @@ fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) ->
},
};
- quote! {{
- use ::cocoindex::mount::{ComponentArgViaMemoInput as _, ComponentArgViaSerialize as _};
- let __coco_parent = &(#ctx_arg);
- #(#arg_binds)*
- let __coco_memo = ::cocoindex::mount::component_memo(
+ let memo_expr = quote! {
+ ::cocoindex::mount::component_memo(
::core::module_path!(),
::core::stringify!(#fn_ident),
#hash_path,
::std::vec![ #(#fp_parts),* ],
- )?;
+ )?
+ };
+ // A background child the selector leaves out computes no memo key: that is
+ // user code. A `use_mount!` child always runs, so it always needs one.
+ let memo_tokens = if may_be_left_out {
+ quote! {
+ if __coco_parent.__selector_leaves_out(&__coco_key) {
+ ::core::option::Option::None
+ } else {
+ ::core::option::Option::Some(#memo_expr)
+ }
+ }
+ } else {
+ quote! { ::core::option::Option::Some(#memo_expr) }
+ };
+
+ quote! {{
+ use ::cocoindex::mount::{ComponentArgViaMemoInput as _, ComponentArgViaSerialize as _};
+ let __coco_parent = &(#ctx_arg);
+ #(#arg_binds)*
let __coco_key: ::cocoindex::StableKey = #key_tokens;
+ let __coco_memo = #memo_tokens;
__coco_parent.#method(
__coco_key,
- ::core::option::Option::Some(__coco_memo),
+ __coco_memo,
move |__coco_child| async move {
#path(&__coco_child, #(#arg_idents),*).await
},
@@ -1646,7 +1668,9 @@ fn expand_single_mount(input: TokenStream, name: &str, method: TokenStream2) ->
/// `coco.mount_each`: evaluates to a `Result<ComponentMountHandle>` whose
/// `ready().await` waits until every child's target states are synced; the
/// children are mounted as `items` is consumed, and `my_fn` returns
-/// `Result<()>`. `use_mount_each!` is the form that returns the values.
+/// `Result<()>`. When the update's `component_selector` leaves out every
+/// child under the prefix, `items` is not read at all. `use_mount_each!` is
+/// the form that returns the values.
///
/// The closure binds the item's **value**; inside the call, `ctx` β†’ child
/// scope, the bound `item` β†’ that value, and any other arguments are captured