Skip to content

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

fix(core): a selected key gone below a replaced component is deleted (#2869)

Jiangzhou487be4413fad
diff --git a/docs/src/content/docs/programming_guide/app.mdx b/docs/src/content/docs/programming_guide/app.mdx
index 6b8faf85..f03fda6a 100644
--- a/docs/src/content/docs/programming_guide/app.mdx
+++ b/docs/src/content/docs/programming_guide/app.mdx
@@ -307,7 +307,7 @@ Details to rely on:
- 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.
+- **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. So is a selected path below a directory, such as the path of a `mount_each()`, that the update mounts where a component used to be. The old component itself stays until an update covers it.
- **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 the selective update would take: those of the components that run (the selected ones, plus any changes to the own target states of the ancestors and `use_mount` children that run), and the deletions of the selected components that are no longer mounted, by the rules above. As in any preview, a failure that happens only when a sink applies its actions shows up only in the update.
diff --git a/python/tests/core/test_component_selector_pushdown.py b/python/tests/core/test_component_selector_pushdown.py
index 5afb59f3..2314752c 100644
--- a/python/tests/core/test_component_selector_pushdown.py
+++ b/python/tests/core/test_component_selector_pushdown.py
@@ -127,6 +127,52 @@ def test_a_selected_key_the_source_no_longer_holds_is_deleted() -> None:
assert _stored() == {"other:o": "o"}
[email protected]("items_factory", [_Items, _ListedOnly])
+def test_a_selected_key_gone_where_a_component_was_is_deleted(
+ items_factory: Any,
+) -> None:
+ """A component at the mount_each's path, now replaced by it: a selected key
+ the source no longer holds is deleted whether the source is read by key or
+ listed, and the old component, which the selector does not cover, stays
+ until a plain update. (Fuzz seed 377: read by key, it used to stay whole.)"""
+
+ @coco.fn
+ async def old_items() -> None:
+ for key, value in _source.items():
+ await coco.mount(coco.component_subpath(key), _item, value, "")
+
+ replaced = [False]
+
+ @coco.fn
+ async def main() -> None:
+ if replaced[0]:
+ await coco.mount_each(
+ coco.component_subpath("items"), _item, items_factory(), ""
+ )
+ else:
+ await coco.mount(coco.component_subpath("items"), old_items)
+
+ app = coco.App(
+ coco.AppConfig(
+ name=f"test_pushdown_replaced_{items_factory.__name__}",
+ environment=coco_env,
+ ),
+ main,
+ )
+ _source.update({"a": "a1", "b": "b1"})
+ app.update_blocking()
+
+ replaced[0] = True
+ del _source["a"]
+ _runs.clear()
+ app.update_blocking(component_selector=[_path("items", "a")])
+
+ assert _runs == []
+ assert _stored() == {"b1": "b1"}
+ app.update_blocking()
+ assert _stored() == {"b1": "b1"}
+
+
def test_a_selected_path_below_an_item_reads_that_item() -> None:
app = _app("deeper")
_source.update({"a": "a1", "b": "b1"})
diff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rs
index eb3345a7..ba3789ec 100644
--- a/rust/core/src/engine/context.rs
+++ b/rust/core/src/engine/context.rs
@@ -1589,15 +1589,33 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {
/// 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.
+ ///
+ /// With keys to run, the run also declares `path` a directory, as listing
+ /// the source and skipping the other keys would, whether or not the source
+ /// still holds the keys it reads. A selected key that is gone is then
+ /// deleted even where a component used to be at `path`; that component
+ /// stays until a run covers it.
pub fn mount_each_keys(
&self,
fn_ctx: &FnCallContext,
path: &StablePath,
- ) -> Option<Vec<StableKey>> {
- let keys = self.component_selector()?.selected_child_keys(path)?;
+ ) -> Result<Option<Vec<StableKey>>> {
+ let Some(keys) = self
+ .component_selector()
+ .and_then(|selector| selector.selected_child_keys(path))
+ else {
+ return Ok(None);
+ };
fn_ctx.update(|inner| inner.has_child_components = true);
self.mark_left_out_children();
- Some(keys)
+ if !keys.is_empty() {
+ let sub_path = path.as_ref().strip_parent(self.stable_path().as_ref())?;
+ self.update_building_state(|building_state| {
+ building_state.child_path_set.declare_directory(sub_path);
+ Ok(())
+ })?;
+ }
+ Ok(Some(keys))
}
pub fn live(&self) -> bool {
diff --git a/rust/core/src/state/stable_path_set.rs b/rust/core/src/state/stable_path_set.rs
index ee146e46..084c82e7 100644
--- a/rust/core/src/state/stable_path_set.rs
+++ b/rust/core/src/state/stable_path_set.rs
@@ -47,6 +47,23 @@ impl ChildStablePathSet {
}
}
}
+
+ /// Declare `path` a directory, with whatever it holds so far, as a mount
+ /// of children under it does. A component at or above `path` already
+ /// declared stays as it is: a child mounted under it reports the clash.
+ pub fn declare_directory(&mut self, path: StablePathRef) {
+ let mut current = self;
+ for key in path.iter() {
+ match current
+ .children
+ .entry(key.clone())
+ .or_insert_with(StablePathSet::directory)
+ {
+ StablePathSet::Directory(dir) => current = dir,
+ StablePathSet::Component | StablePathSet::Skipped => return,
+ }
+ }
+ }
}
pub enum StablePathSet {
diff --git a/rust/py/src/component.rs b/rust/py/src/component.rs
index 8884c599..bf3ce03b 100644
--- a/rust/py/src/component.rs
+++ b/rust/py/src/component.rs
@@ -252,6 +252,7 @@ pub fn mount_each_keys(
comp_ctx
.0
.mount_each_keys(&fn_ctx.0, &stable_path.0)
+ .into_py_result()?
.map(|keys| {
keys.into_iter()
.map(|key| PyStableKey(key).into_pyobject(py).map(|b| b.unbind()))
diff --git a/rust/sdk/cocoindex/src/ctx.rs b/rust/sdk/cocoindex/src/ctx.rs
index 44ec7465..752cf359 100644
--- a/rust/sdk/cocoindex/src/ctx.rs
+++ b/rust/sdk/cocoindex/src/ctx.rs
@@ -1740,7 +1740,7 @@ impl Ctx {
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))
+ 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 {