Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(core): a preview lists the deletes of components no longer mounted (#2861)
Jiangzhoudeb02ebdff9c
diff --git a/AGENTS.md b/AGENTS.mdindex b228dc04..4c797729 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -343,7 +343,7 @@ List every image a test's containers use in its `requires_docker(...)` marker. `- All LMDB writes must go through `AppStore::run_txn`, which runs persisting bodies on the single-writer batcher (`Storage::run_txn`, private to `state_store`) and a preview's bodies against a read snapshot.- Do not open a heed write txn directly or wrap the env in a separate mutex/semaphore β bypassing the batcher loses fsync coalescing and regresses concurrent-submit throughput by 10-100Γ.- LMDB has no savepoints. If a sub-operation needs to "abort" without failing its caller, handle it at the body level (e.g. return a sentinel result without writing). A body that returns `Err` fails only its own caller: the batcher drops its writes by aborting the txn and re-running the bodies ahead of it, so every body must be safe to re-run.-- A preview writes nothing to the state store, and write paths do not check for a preview to achieve that: a preview run's `ComponentProcessorContext::app_store()` (inherited by every context of the operation, live components included) is an `AppStore::discarding_writes()` handle. Its bodies run one at a time, as a batch's do, on a blocking thread against a read snapshot plus an in-memory overlay of the run's own writes to its app's database instead of the write batcher, and a preview runs its commit into that handle too, so the run reads its writes back and plans exactly as an update would, and nothing reaches LMDB. The overlay keeps no function-memo value a preview writes (a later run in the same preview reads the memo the store holds, if any, and recomputes otherwise); it does keep tracking records, owner and existence rows, component memos and user states. A preview reserves ids in a range of its own, from `FIRST_ID_OF_A_RUN_THAT_PERSISTS_NOTHING`, so they never meet a persisting run's. Reach the store through that context handle; `AppContext::persisting_app_store()` (crate-private) is for deriving a root run's handle and for inspection. The one deliberate exception is `AppContext::next_id`, whose sequencer owns the app's persisting store and reserves user ids in a preview too (ids are opaque, and a gap costs nothing).+- A preview writes nothing to the state store, and write paths do not check for a preview to achieve that: a preview run's `ComponentProcessorContext::app_store()` (inherited by every context of the operation, live components included) is an `AppStore::discarding_writes()` handle. Its bodies run one at a time, as a batch's do, on a blocking thread against a read snapshot plus an in-memory overlay of the run's own writes to its app's database instead of the write batcher, and a preview runs its commit into that handle too, the deletes of the child components it no longer mounts included, so the run reads its writes back and plans exactly as an update would, and nothing reaches LMDB. The overlay keeps no function-memo value a preview writes (a later run in the same preview reads the memo the store holds, if any, and recomputes otherwise); it does keep tracking records, owner and existence rows, component memos and user states. A preview reserves ids in a range of its own, from `FIRST_ID_OF_A_RUN_THAT_PERSISTS_NOTHING`, so they never meet a persisting run's. Reach the store through that context handle; `AppContext::persisting_app_store()` (crate-private) is for deriving a root run's handle and for inspection. The one deliberate exception is `AppContext::next_id`, whose sequencer owns the app's persisting store and reserves user ids in a preview too (ids are opaque, and a gap costs nothing).- An LMDB write txn must begin and end (commit or abort) on the same OS thread: the writer lock is thread-owned and LMDB ignores a failed release, so a txn that migrates between runtime workers blocks every later writer for good. heed marks `RwTxn` as `Send` regardless, so the compiler won't catch it. The batcher behind `AppStore::run_txn` runs each batch on one blocking thread for this reason; never hold a write txn across an `.await` on the multi-thread runtime.### Sync vs Asyncdiff --git a/docs/src/content/docs/programming_guide/app.mdx b/docs/src/content/docs/programming_guide/app.mdxindex 491c878c..59382943 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.+- `preview` option computes the target actions without applying them, and returns them in place of the main function's value. See [Previewing an update](#previewing-an-update).- `component_selector` option runs only the components you name. See [Updating part of an app](#updating-part-of-an-app).</Lang>@@ -186,7 +187,7 @@ let result = app.update_blocking(app_main)?;- `live` keeps the app running after the initial scan so live components can continue watching for changes. See [Live Mode](./live_mode).- `report_to_stdout` prints periodic progress updates during execution. `progress_refresh_interval` sets the refresh interval.- `full_reprocess` reprocesses everything, bypassing all memoization: every component **and** every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost β this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function's work, bump its [`version`](./function#version) instead.-- `preview` computes the target actions without applying them.+- `preview` computes the target actions without applying them. See [Previewing an update](#previewing-an-update).- `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).@@ -231,6 +232,12 @@ 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>+### Previewing an update++A preview runs the update without applying it, and returns the actions the update would take on its targets: <Lang only="python">`app.update(preview=True)`</Lang><Lang only="rust">`app.preview(app_main)`</Lang>, or `cocoindex update --preview` from the command line. It lists every action the update takes, including the deletion of the target states of the components the app no longer mounts, down their whole subtree: the outputs of a deleted source file, or of a child whose key changed. It writes nothing to the targets or to CocoIndex's records, so as long as the sources stay the same, the next update, or the next preview, plans the same actions again.++A failure that happens only when a sink applies its actions, such as a database rejecting a row, shows up only in the update.+### Updating part of an appPass `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.@@ -303,7 +310,7 @@ Details to rely on:- **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.+- **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.- **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.diff --git a/python/tests/core/test_component_selector.py b/python/tests/core/test_component_selector.pyindex 217cca2e..9db8f879 100644--- a/python/tests/core/test_component_selector.py+++ b/python/tests/core/test_component_selector.py@@ -41,6 +41,12 @@ def _planned(actions: Any) -> dict[str, Any]:return {key: value.data for key, value in actions}+def _planned_deletes(actions: Any) -> set[str]:+ """The keys of the planned actions, each of which must be a delete."""+ assert all(coco.is_non_existence(value) for _, value in actions)+ return {key for key, _ in actions}++def _declare(key: Any, value: Any) -> None:coco.declare_target_state(GlobalDictTarget.target_state(str(key), value))@@ -361,12 +367,16 @@ def test_ancestor_no_longer_mounted_keeps_its_whole_subtree() -> None:_run_all_then_clear_log(app)mounted[0] = False- app.update_blocking(- component_selector=[coco.ROOT_PATH / "parent" / "kids" / "a"],- )+ selector = [coco.ROOT_PATH / "parent" / "kids" / "a"]+ assert app.update_blocking(preview=True, component_selector=selector) == []+ assert _runs == []+ app.update_blocking(component_selector=selector)assert _runs == []assert _stored() == {"a": 1, "b": 1}+ assert _planned_deletes(app.update_blocking(preview=True)) == {"a", "b"}+ assert _stored() == {"a": 1, "b": 1}+app.update_blocking()assert _stored() == {}@@ -383,7 +393,12 @@ def test_selected_gone_under_a_directory_is_deleted_and_its_sibling_kept() -> No_run_all_then_clear_log(app)_source.clear()- app.update_blocking(component_selector=[coco.ROOT_PATH / "dir" / "deep" / "a"])+ selector = [coco.ROOT_PATH / "dir" / "deep" / "a"]+ actions = app.update_blocking(preview=True, component_selector=selector)+ assert _planned_deletes(actions) == {"a"}+ assert _stored() == {"a": 1, "b": 1}++ app.update_blocking(component_selector=selector)assert _stored() == {"b": 1}@@ -749,18 +764,28 @@ def test_preview_of_an_unselected_deleted_item_plans_nothing() -> None: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)+def test_preview_plans_the_deletes_the_selected_update_makes() -> None:+ # "a" and "c" are gone; only "a" is selected, so only its delete is planned.+ _source.update(a=1, b=1, c=1)app = _app("preview_selected_deleted")_run_all_then_clear_log(app)+ paths_before = {str(p) for p in list_stable_paths_sync(app)}+ GlobalDictTarget.store.metrics.clear()del _source["a"]- actions = app.update_blocking(preview=True, component_selector=[_items_path("a")])+ del _source["c"]+ selector = [_items_path("a"), _items_path("b")]+ actions = app.update_blocking(preview=True, component_selector=selector)- assert actions == []- assert _stored() == {"a": 1}+ assert _planned_deletes(actions) == {"a"}+ assert _stored() == {"a": 1, "b": 1, "c": 1}+ assert {str(p) for p in list_stable_paths_sync(app)} == paths_before+ assert GlobalDictTarget.store.metrics.collect() == {}++ # The sliced update makes exactly the planned deletes.+ app.update_blocking(component_selector=selector)+ assert GlobalDictTarget.store.metrics.collect() == {"delete": 1, "sink": 1}+ assert _stored() == {"b": 1, "c": 1}def test_preview_includes_the_own_changes_of_the_ancestors_that_run() -> None:@@ -874,9 +899,14 @@ def test_tombstone_left_by_a_failed_delete_waits_for_a_run_that_covers_it() -> Nassert _stored() == {"a": 1, "b": 1}# This run's GC sweep leaves the tombstone: "b" is not selected.+ assert (+ app.update_blocking(preview=True, component_selector=[_items_path("a")]) == []+ )app.update_blocking(component_selector=[_items_path("a")])assert _stored() == {"a": 1, "b": 1}+ actions = app.update_blocking(preview=True, component_selector=[_items_path("b")])+ assert _planned_deletes(actions) == {"b"}app.update_blocking(component_selector=[_items_path("b")])assert _stored() == {"a": 1}diff --git a/python/tests/core/test_live_component.py b/python/tests/core/test_live_component.pyindex f76be621..26eedbfe 100644--- a/python/tests/core/test_live_component.py+++ b/python/tests/core/test_live_component.py@@ -783,9 +783,9 @@ class _DeleteOnRequestLiveComponent:def test_live_component_delete_in_preview_applies_nothing() -> None:- """In a preview, operator.delete() neither deletes the child nor leaves a- tombstone, and (like the deletes of components an update no longer mounts)- it is not previewed: the next real update keeps the child."""+ """In a preview, operator.delete() plans the deletion of the child's target+ states, but neither deletes the child nor leaves a tombstone: the next real+ update keeps the child."""GlobalDictTarget.store.clear()_source_data.clear()_DeleteOnRequestLiveComponent.delete_b = False@@ -811,8 +811,11 @@ def test_live_component_delete_in_preview_applies_nothing() -> None:actions = app.update_blocking(preview=True)finally:_DeleteOnRequestLiveComponent.delete_b = False- # Neither applied nor planned.- assert actions == []+ # Planned, not applied.+ assert actions is not None+ assert [(key, coco.is_non_existence(value)) for key, value in actions] == [+ ("b", True)+ ]assert set(GlobalDictTarget.store.data) == {"a", "b"}assert GlobalDictTarget.store.metrics.collect() == {}diff --git a/python/tests/core/test_preview_deletes.py b/python/tests/core/test_preview_deletes.pynew file mode 100644index 00000000..25408181--- /dev/null+++ b/python/tests/core/test_preview_deletes.py@@ -0,0 +1,219 @@+"""A preview lists what an update does for the components it no longer mounts:+the deletion of their target states, down their whole subtree. It applies none+of it and writes nothing, and the update that follows does exactly that."""++from __future__ import annotations++from typing import Any++import pytest++import cocoindex as coco+import cocoindex.inspect as coco_inspect++from tests import common+from tests.common.target_states import (+ DictDataWithPrev,+ DictsTarget,+ GlobalDictTarget,+ split_dicts_actions,+)++coco_env = common.create_test_env(__file__)++# Item name -> {child key -> value}.+_source: dict[str, dict[str, int]] = {}++[email protected](autouse=True)+def _reset() -> None:+ GlobalDictTarget.store.clear()+ GlobalDictTarget.store.sink_exception = False+ DictsTarget.store.clear()+ _source.clear()+++async def _child(key: str, value: int) -> None:+ coco.declare_target_state(GlobalDictTarget.target_state(key, value))+++async def _item(name: str, children: dict[str, int]) -> None:+ coco.declare_target_state(GlobalDictTarget.target_state(name, len(children)))+ for key, value in children.items():+ await coco.mount(coco.component_subpath(key), _child, f"{name}/{key}", value)+++async def _main() -> None:+ for name, children in _source.items():+ await coco.mount(coco.component_subpath("items", name), _item, name, children)+++def _app(name: str, main: Any = _main) -> coco.App[Any, Any]:+ return coco.App(+ coco.AppConfig(name=f"test_preview_deletes_{name}", environment=coco_env),+ main,+ )+++def _stored() -> dict[str, Any]:+ return {k: v.data for k, v in GlobalDictTarget.store.data.items()}+++def _planned(actions: Any) -> dict[str, Any]:+ """Each planned action by key: the new value, or `None` for a delete."""+ planned: dict[str, Any] = {}+ for key, value in actions:+ assert key not in planned+ planned[key] = None if coco.is_non_existence(value) else value.data+ return planned+++def _snapshot(app: coco.App[Any, Any]) -> tuple[Any, ...]:+ """What a preview must leave as it is: the target and CocoIndex's records."""+ return (+ _stored(),+ sorted(str(p) for p in coco_inspect.list_stable_paths_sync(app)),+ {k: str(v) for k, v in common.list_target_state_owners_sync(app).items()},+ )+++def _applies_exactly(app: coco.App[Any, Any], planned: dict[str, Any]) -> None:+ """The next update applies exactly the planned actions."""+ before = _stored()+ GlobalDictTarget.store.metrics.clear()+ app.update_blocking()+ metrics = GlobalDictTarget.store.metrics.collect()+ deletes = {k for k, v in planned.items() if v is None}+ upserts = {k: v for k, v in planned.items() if v is not None}+ assert metrics.get("delete", 0) == len(deletes)+ assert metrics.get("upsert", 0) == len(upserts)+ expected = {k: v for k, v in before.items() if k not in deletes} | upserts+ assert _stored() == expected+++def test_preview_lists_the_deletes_of_a_removed_item_and_its_subtree() -> None:+ _source.update(a={"x": 1}, b={"x": 2, "y": 3})+ app = _app("removed_item")+ app.update_blocking()+ snapshot = _snapshot(app)+ GlobalDictTarget.store.metrics.clear()++ del _source["b"]+ planned = _planned(app.update_blocking(preview=True))++ assert planned == {"b": None, "b/x": None, "b/y": None}+ # Nothing applied, nothing recorded.+ assert GlobalDictTarget.store.metrics.collect() == {}+ assert _snapshot(app) == snapshot+ # So a second preview plans the same deletes again.+ assert _planned(app.update_blocking(preview=True)) == planned++ _applies_exactly(app, planned)+ assert _stored() == {"a": 1, "a/x": 1}+++async def test_async_preview_lists_the_deletes_of_a_removed_item() -> None:+ _source.update(a={}, b={"x": 2})+ app = _app("removed_item_async")+ await app.update()++ del _source["b"]+ planned = _planned(await app.update(preview=True))++ assert planned == {"b": None, "b/x": None}+ assert _stored() == {"a": 0, "b": 1, "b/x": 2}+++def test_preview_lists_the_subtree_of_a_renamed_child_key() -> None:+ _source.update(a={"x": 1, "y": 2})+ app = _app("renamed_key")+ app.update_blocking()+ snapshot = _snapshot(app)++ _source["a"] = {"x": 1, "z": 2}+ planned = _planned(app.update_blocking(preview=True))++ assert planned == {"a/y": None, "a/z": 2}+ assert _snapshot(app) == snapshot++ _applies_exactly(app, planned)+++def test_preview_lists_the_deletes_of_everything_when_nothing_is_mounted() -> None:+ _source.update(a={"x": 1}, b={})+ app = _app("all_removed")+ app.update_blocking()+ snapshot = _snapshot(app)++ _source.clear()+ planned = _planned(app.update_blocking(preview=True))++ assert planned == {"a": None, "a/x": None, "b": None}+ assert _snapshot(app) == snapshot++ _applies_exactly(app, planned)+ assert coco_inspect.list_stable_paths_sync(app) == [coco.ROOT_PATH]+++def test_preview_lists_the_delete_of_a_removed_container() -> None:+ @coco.fn+ async def container(name: str, entries: dict[str, int]) -> None:+ provider = await coco.mount_target(DictsTarget.dict_target(name))+ for key, value in entries.items():+ coco.declare_target_state(provider.target_state(key, value))++ containers: dict[str, dict[str, int]] = {"D1": {"a": 1}, "D2": {"b": 2}}++ @coco.fn+ async def main() -> None:+ for name, entries in containers.items():+ await coco.mount(coco.component_subpath(name), container, name, entries)++ app = _app("removed_container", main)+ app.update_blocking()+ DictsTarget.store.metrics.clear()++ del containers["D2"]+ planned = split_dicts_actions(app.update_blocking(preview=True))++ # A declared container's action is listed on every run (see+ # `test_preview_child_target_providers`); the gone one's is a delete.+ assert {n: a.action for n, a in planned.containers.items()} == {+ "D1": None,+ "D2": "delete",+ }+ # Its entries go with it: no action of their own.+ assert planned.entries == {}+ assert set(DictsTarget.store.data) == {"D1", "D2"}+ assert DictsTarget.store.metrics.collect() == {}++ app.update_blocking()+ assert DictsTarget.store.data == {+ "D1": {"a": DictDataWithPrev(data=1, prev=[], prev_may_be_missing=True)}+ }+++def test_preview_of_a_delete_that_fails_only_in_the_sink_succeeds() -> None:+ # The stated limit: a failure that happens only when a sink applies its+ # actions shows up only in the update.+ _source.update(a={}, b={})+ app = _app("sink_failure")+ app.update_blocking()++ del _source["b"]+ GlobalDictTarget.store.sink_exception = True+ try:+ assert _planned(app.update_blocking(preview=True)) == {"b": None}+ app.update_blocking()+ assert _stored() == {"a": 0, "b": 0}+ finally:+ GlobalDictTarget.store.sink_exception = False++ # The delete the update owes is previewed again, then applied.+ assert _planned(app.update_blocking(preview=True)) == {"b": None}+ app.update_blocking()+ assert _stored() == {"a": 0}diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rsindex a6b857b0..caf30d3e 100644--- a/rust/core/src/engine/component.rs+++ b/rust/core/src/engine/component.rs@@ -1856,12 +1856,14 @@ impl<Prof: EngineProfile> Component<Prof> {host_ctx: Arc<Prof::HostCtx>,on_error: Option<OnError>,) -> ComponentProcessorContext<Prof> {+ // A delete that a preview launches previews too.+ let preview_collector = parent_ctx.and_then(|parent| parent.preview_collector().cloned());ComponentProcessorContext::new(self.clone(),parent_ctx.cloned(),processing_stats,host_ctx,- ComponentProcessingAction::new_delete(providers, on_error),+ ComponentProcessingAction::new_delete(providers, on_error, preview_collector),)}}@@ -3391,6 +3393,120 @@ mod tests {assert_eq!(container_apply_calls.load(Ordering::SeqCst), 1);}+ /// A root that registers a root provider routed to `sink` and, with+ /// `with_kid`, mounts a child `kid` declaring `NUM_KID_ROWS` target states+ /// through it, which the handler deletes once the child is gone.+ fn root_with_kid(sink: TargetActionSinkKeeper<TestProfile>, with_kid: bool) -> TestProcessor {+ const NUM_KID_ROWS: i64 = 2;+ let new_processor = |name: &str| {+ TestProcessor::new(+ name,+ Fingerprint::from(&format!("root_with_kid/{name}")).unwrap(),+ Arc::new(AtomicBool::new(false)),+ false,+ )+ .without_memo()+ };+ let kid = new_processor("kid");+ let kid = Mutex::new(Some(kid));+ new_processor("root").with_on_process(Arc::new(move |ctx| {+ let sink = sink.clone();+ let kid = kid.lock().unwrap().take();+ Box::pin(async move {+ let rows = register_root_target_state_provider(+ &ctx,+ "rows".to_string(),+ CountingHandler {+ reconcile_calls: Default::default(),+ sink,+ reject: false,+ change_only: true,+ plans_deletes: true,+ },+ )?;+ if with_kid {+ let kid = kid.unwrap().with_on_process(Arc::new(move |ctx| {+ let rows = rows.clone();+ Box::pin(async move {+ for i in 0..NUM_KID_ROWS {+ declare_target_state(+ &ctx,+ &FnCallContext::default(),+ rows.clone(),+ StableKey::Int(i),+ (),+ )?;+ }+ Ok(TestData(b"kid".to_vec()))+ })+ }));+ ctx.component()+ .mount_child(&FnCallContext::new(true), key_path(ctx.component(), "kid"))?+ .use_mount(&ctx, kid, DeadlineContext::NONE)+ .await?+ .result(Some(&ctx))+ .await?;+ }+ Ok(TestData(b"ret".to_vec()))+ })+ }))+ }++ /// A preview plans the deletion of the target states of a child component+ /// that the run no longer mounts, applies none of it and writes nothing;+ /// the update after it applies the deletion.+ #[tokio::test]+ async fn preview_plans_the_deletes_of_a_child_no_longer_mounted() {+ let (app, _dir) = test_app("preview_gone_child").await;+ let apply_calls = Arc::new(AtomicUsize::new(0));+ let sink = TargetActionSinkKeeper::new(NoopSink {+ apply_calls: apply_calls.clone(),+ ..Default::default()+ });+ let update = |with_kid: bool, collector: Option<PreviewActionCollector<TestProfile>>| {+ let (handle, _) = app+ .update(+ root_with_kid(sink.clone(), with_kid),+ AppUpdateOptions::default(),+ Arc::new(()),+ collector,+ )+ .unwrap();+ handle.result()+ };+ update(true, None).await.unwrap();+ assert_eq!(apply_calls.load(Ordering::SeqCst), 1);++ let contents_before = app_store_contents(&app).await;+ for _ in 0..2 {+ let collector = PreviewActionCollector::<TestProfile>::default();+ update(false, Some(collector.clone())).await.unwrap();+ assert_eq!(+ collector.lock().unwrap().len(),+ 2,+ "one deletion per target state of the gone child"+ );+ assert_eq!(+ apply_calls.load(Ordering::SeqCst),+ 1,+ "preview applies nothing"+ );+ assert!(+ app_store_contents(&app).await == contents_before,+ "preview must not write to the state store"+ );+ }++ update(false, None).await.unwrap();+ assert_eq!(apply_calls.load(Ordering::SeqCst), 2);+ let collector = PreviewActionCollector::<TestProfile>::default();+ update(false, Some(collector.clone())).await.unwrap();+ assert!(+ collector.lock().unwrap().is_empty(),+ "nothing left to delete"+ );+ }+/// A preview that runs a live component writes nothing: not the marker/// the component commits (which it still reads back), not the existence/// rows and tombstone of the children it updates and deletes, and notdiff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rsindex 8919f9f6..eb3345a7 100644--- a/rust/core/src/engine/context.rs+++ b/rust/core/src/engine/context.rs@@ -919,6 +919,9 @@ pub(crate) struct ComponentDeleteContext<Prof: EngineProfile> {////// See `specs/core/error_handling.md` for the unified principle.pub on_error: Option<crate::engine::component::OnError>,+ /// The preview collector of the run that launched this delete: in a+ /// preview, the delete plans its actions into it instead of applying them.+ pub preview_collector: Option<PreviewActionCollector<Prof>>,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -966,12 +969,23 @@ impl<Prof: EngineProfile> ComponentProcessingAction<Prof> {pub fn new_delete(providers: rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,on_error: Option<crate::engine::component::OnError>,+ preview_collector: Option<PreviewActionCollector<Prof>>,) -> Self {Self::Delete(ComponentDeleteContext {providers,on_error,+ preview_collector,})}++ /// The collector of a preview run's actions: a build's, or a delete's that+ /// the preview launched for a component it no longer mounts.+ fn preview_collector(&self) -> Option<&PreviewActionCollector<Prof>> {+ match self {+ Self::Build(build_ctx) => build_ctx.preview_collector.as_ref(),+ Self::Delete(delete_ctx) => delete_ctx.preview_collector.as_ref(),+ }+ }}struct ComponentProcessorContextInner<Prof: EngineProfile> {@@ -1059,19 +1073,14 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {// store, or in a preview one handle whose writes never persist.let app_store = match &parent_context {Some(parent) => parent.app_store().clone(),- None => match &processing_action {- ComponentProcessingAction::Build(build_ctx)- if build_ctx.preview_collector.is_some() =>- {- component- .app_ctx()- .persisting_app_store()- .discarding_writes()- }- ComponentProcessingAction::Build(_) | ComponentProcessingAction::Delete(_) => {- component.app_ctx().persisting_app_store().clone()+ None => {+ let persisting_app_store = component.app_ctx().persisting_app_store();+ if processing_action.preview_collector().is_some() {+ persisting_app_store.discarding_writes()+ } else {+ persisting_app_store.clone()}- },+ }};Self::from_parts(component,@@ -1495,13 +1504,10 @@ impl<Prof: EngineProfile> ComponentProcessorContext<Prof> {&self.inner.data_dep_verdicts}- /// The collector of a preview run's actions. Only a build runs as a- /// preview: a preview plans no deletes of components.+ /// The collector of a preview run's actions; see+ /// [`ComponentProcessingAction::preview_collector`].pub(crate) fn preview_collector(&self) -> Option<&PreviewActionCollector<Prof>> {- match &self.inner.processing_action {- ComponentProcessingAction::Build(build_ctx) => build_ctx.preview_collector.as_ref(),- ComponentProcessingAction::Delete(_) => None,- }+ self.inner.processing_action.preview_collector()}/// The selector this run is under. A delete has none: it is reached onlydiff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rsindex 7d4177ac..112515e1 100644--- a/rust/core/src/engine/execution.rs+++ b/rust/core/src/engine/execution.rs@@ -944,8 +944,8 @@ impl<Prof: EngineProfile> Committer<Prof> {#[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+ /// found (in a preview: planned every child's delete), or found none. A+ /// run that sweeps nothing reports it too: 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.@@ -2264,8 +2264,10 @@ pub(crate) async fn submit<Prof: EngineProfile>(// handler factory, so the components declaring child target states can// preview theirs, and commits into its run's handle, where the run's// later reads find the component committed as an update would leave it,- // and nothing persists. The commit's Phase 5 deletes of the child- // components this run no longer declares are not previewed.+ // and nothing persists. The commit's Phase 5 GC runs as in an update: the+ // deletes of the child components this run no longer declares inherit+ // the preview's collector and store handle, so they plan their actions+ // into the preview too.// Whether the run applies its actions follows its store handle, as// whether it persists does: a run whose writes do not persist must not// apply its actions either, or LMDB would record states the targets no@@ -2277,7 +2279,7 @@ pub(crate) async fn submit<Prof: EngineProfile>("a run that persists nothing reached submit without a preview collector"));};- let planned: Result<Vec<_>> = async {+ let planned: Result<(Vec<_>, ChildDeletes)> = async {if let Some((child_provider, _)) = actions_by_sinks.values().find_map(|input| input.pending_children.first())@@ -2294,14 +2296,14 @@ pub(crate) async fn submit<Prof: EngineProfile>(// these target states waits on the staged token as it would there// (where the window also spans the sinks' apply).let children = build_factory_children(comp_ctx, &actions_by_sinks).await?;- Committer::new(comp_ctx, target_states_providers)?- .commit_writes(child_existence, fn_memos, user_states, tracking)+ let child_deletes = Committer::new(comp_ctx, target_states_providers)?+ .commit(child_existence, fn_memos, user_states, tracking).await?;- Ok(children)+ Ok((children, child_deletes))}.await;- let children = match planned {- Ok(children) => children,+ let (children, child_deletes) = match planned {+ Ok(planned) => planned,Err(e) => {cleanup_pending_token(comp_ctx, process_token).await;return Err(e);@@ -2323,7 +2325,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(return Ok(SubmitOutput {built_target_states_providers,touched_previous_states,- child_deletes: ChildDeletes::Done,+ child_deletes,});}diff --git a/rust/core/src/engine/live_component.rs b/rust/core/src/engine/live_component.rsindex 2218d5fe..51bc159b 100644--- a/rust/core/src/engine/live_component.rs+++ b/rust/core/src/engine/live_component.rs@@ -840,9 +840,9 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {/// returned handle. The tombstone always remains in the DB, so even/// a failed delete is retried by the next reconcile's GC sweep.///- /// 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).+ /// In a preview, the delete plans its actions into the preview's collector+ /// and applies none of them; the tombstone stays in the preview's store+ /// handle, which persists nothing.////// Under a selector, only a covered path is deleted: an ancestor of a/// selected path holds unselected descendants too (the same call as@@ -1463,11 +1463,6 @@ async fn run_op<Prof: EngineProfile>(inner_handle.ready().await}Op::Delete { on_error } => {- // A run that persists nothing (a preview) previews no deletes of- // components (see `LiveComponentController::delete`).- if app_store.write_scope() != crate::state_store::WriteScope::Persisted {- return Ok(());- }// Remove the existence entry again, now that this subpath's// earlier ops have finished. An update that was already running// when the delete was dispatched wrote it back (its build's eager@@ -1483,7 +1478,11 @@ async fn run_op<Prof: EngineProfile>(share.new_update(),processing_stats.clone(),host_ctx.clone(),- ComponentProcessingAction::new_delete(providers.clone(), on_error),+ ComponentProcessingAction::new_delete(+ providers.clone(),+ on_error,+ preview_collector.clone(),+ ),app_store.clone(),update_refusal.clone(),);diff --git a/rust/sdk/cocoindex/tests/it/live_component.rs b/rust/sdk/cocoindex/tests/it/live_component.rsindex 8a5948ea..375331af 100644--- a/rust/sdk/cocoindex/tests/it/live_component.rs+++ b/rust/sdk/cocoindex/tests/it/live_component.rs@@ -13,9 +13,9 @@ use std::time::Duration;use cocoindex::{App, Ctx, Error, LiveComponent, LiveComponentOperator, LiveMapFeed, LiveMapSubscriber,- LiveMapView, MountKind, Result, StableKey, TargetAction, TargetActionSink, TargetHandler,- TargetReconcileOutput, TargetStateProvider, UpdateOptions, async_trait, declare_target_state,- register_root_target_states_provider,+ LiveMapView, MountKind, PreviewAction, Result, StableKey, TargetAction, TargetActionSink,+ TargetHandler, TargetReconcileOutput, TargetStateProvider, UpdateOptions, async_trait,+ declare_target_state, register_root_target_states_provider,};use tokio::sync::Notify;@@ -358,9 +358,10 @@ impl LiveComponent for Rows {}}-/// A preview through a live component applies nothing and persists nothing:-/// the update after it finds no tracking of the rows the preview planned, so-/// it creates them rather than finding them in place.+/// A preview through a live component plans what an update would do, the+/// live delete included, applies nothing and persists nothing: the update+/// after it finds no tracking of the rows the preview planned, so it creates+/// them rather than finding them in place.#[tokio::test]async fn preview_through_live_component_persists_nothing() {let (app, _dir) = temp_app("live_preview_persists_nothing").await;@@ -389,7 +390,20 @@ async fn preview_through_live_component_persists_nothing() {}).await.unwrap();- assert_eq!(actions.len(), 2, "the preview plans a create per row");+ let mut verbs: Vec<&str> = actions+ .iter()+ .map(|action| match action {+ PreviewAction::Create(_) => "create",+ PreviewAction::Update(_) => "update",+ PreviewAction::Delete(_) => "delete",+ })+ .collect();+ verbs.sort();+ assert_eq!(+ verbs,+ ["create", "create", "delete"],+ "the preview plans a create per row, and the delete of `a`"+ );assert!(drain_sorted(&log).is_empty(),"the preview applied an action"