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 catch-up update leaves a running live update alone, and drop reverts run-time root providers (#2802)
LJ π₯₯π΄562986aec0bd
diff --git a/docs/src/content/docs/advanced_topics/custom_target_connector.mdx b/docs/src/content/docs/advanced_topics/custom_target_connector.mdxindex 76987709..3ca8052a 100644--- a/docs/src/content/docs/advanced_topics/custom_target_connector.mdx+++ b/docs/src/content/docs/advanced_topics/custom_target_connector.mdx@@ -679,7 +679,7 @@ for (k, v) in rows {}```-The provider is registered for the current run, from inside a component, so register it on every run. Once a run stops registering it, the engine cannot reach its handler, and the target states declared through it are left in place; `App::drop_state` leaves them in place too.+The provider is registered for the current run, from inside a component, so register it on every run. Once a run stops registering it, the engine cannot reach its handler, and the target states declared through it are left in place. `App::drop_state` reverts them through the handler the app's latest run registered; an app opened in a new process has to run once before its drop can reach the handler.</Fragment></LangTabs>diff --git a/docs/src/content/docs/advanced_topics/live_component.mdx b/docs/src/content/docs/advanced_topics/live_component.mdxindex a0eb7ad8..56e3798e 100644--- a/docs/src/content/docs/advanced_topics/live_component.mdx+++ b/docs/src/content/docs/advanced_topics/live_component.mdx@@ -161,6 +161,10 @@ Failures in the mounted child (or in the delete itself) are routed through the pSignals to the parent that the live component has caught up. The parent's <Lang only="python">`await handle.ready()`</Lang><Lang only="rust">`ctx.mount_live(...)` call</Lang> returns when `mark_ready()` is called. If `process_live()` returns without calling `mark_ready()`, it is called automatically.+### A catch-up update beside a running live update++A catch-up update of an app whose live update is still running leaves the live component running. The catch-up mounts its own instance of the component beside it, so two `process_live()` calls for one component can run at the same time: the live one, and the catch-up one, which ends at `mark_ready()`. Their full passes take turns, and an `update()` or `delete()` from the live one that arrives during the catch-up's full pass runs after that pass commits. If `process_live()` takes an exclusive resource (a lock, a port, a consumer group membership) before `mark_ready()`, the catch-up instance must be able to wait for it or do without it.+<Lang only="python">### `report_exception()`diff --git a/python/tests/core/test_live_component.py b/python/tests/core/test_live_component.pyindex cb2c1f1e..f76be621 100644--- a/python/tests/core/test_live_component.py+++ b/python/tests/core/test_live_component.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import threadingimport tracebackfrom collections.abc import AsyncIterator, Awaitable, Callablefrom typing import Any@@ -1827,6 +1828,158 @@ async def test_live_component_global_cancel_terminates_update() -> None:_core.reset_global_cancellation()+async def test_catch_up_update_beside_running_live_update() -> None:+ """A catch-up `app.update()` while the same app's live update runs does+ its work and leaves the live incarnation running: its `process_live` is+ not cancelled, and its operator still applies updates afterwards."""+ GlobalDictTarget.store.clear()+ _source_data.clear()+ _source_data["a"] = 1++ # `process_live` runs on the environment's loop, not the test's: signal+ # across them with thread-safe events, polled.+ started = threading.Event()+ cancelled = threading.Event()+ go = threading.Event()+ applied = threading.Event()++ async def _wait(event: threading.Event) -> None:+ for _ in range(1000):+ if event.is_set():+ return+ await asyncio.sleep(0.01)+ raise AssertionError("timed out")++ class _Live:+ async def process(self) -> None:+ _declare_source_entries()++ async def process_live(self, operator: coco.LiveComponentOperator) -> None:+ await operator.update_full()+ # In catch-up mode `mark_ready` ends `process_live` here.+ await operator.mark_ready()+ started.set()+ try:+ await _wait(go)+ handle = await operator.update(+ coco.component_subpath("late"), _declare_item, "late", 7+ )+ await handle.ready()+ applied.set()+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancelled.set()+ raise++ async def _main() -> None:+ await coco.mount(coco.component_subpath("live"), _Live)++ app = coco.App(+ coco.AppConfig(name="test_catch_up_beside_live", environment=coco_env),+ _main,+ )+ live_task = asyncio.create_task(app.update(live=True).result())+ try:+ await _wait(started)+ _source_data["b"] = 2+ await asyncio.wait_for(app.update().result(), timeout=10.0)+ assert "b" in GlobalDictTarget.store.data+ assert not cancelled.is_set(), "the catch-up update cancelled the live one"++ go.set()+ await _wait(applied)+ assert "late" in GlobalDictTarget.store.data+ finally:+ try:+ await app.drop()+ finally:+ live_task.cancel()+ try:+ await live_task+ except BaseException:+ pass+++async def test_live_update_during_catch_up_is_not_reconciled_away() -> None:+ """A live `operator.update()` that lands while a catch-up update beside+ it works from a source listing taken before the update must survive the+ catch-up's commit: it queues behind the catch-up's `update_full` and is+ applied after it, instead of being applied first and then reconciled+ away."""+ GlobalDictTarget.store.clear()+ _source_data.clear()+ _source_data["a"] = 1++ calls = {"n": 0}+ started = threading.Event()+ catch_up_listed = threading.Event()+ release_catch_up = threading.Event()+ applied = threading.Event()++ async def _wait(event: threading.Event) -> None:+ for _ in range(1000):+ if event.is_set():+ return+ await asyncio.sleep(0.01)+ raise AssertionError("timed out")++ class _Live:+ async def process(self) -> None:+ calls["n"] += 1+ snapshot = dict(_source_data)+ if calls["n"] == 2: # the catch-up update's process()+ catch_up_listed.set()+ await _wait(release_catch_up)+ for key, value in snapshot.items():+ await coco.mount(coco.component_subpath(key), _declare_item, key, value)++ async def process_live(self, operator: coco.LiveComponentOperator) -> None:+ await operator.update_full()+ await operator.mark_ready()+ if calls["n"] != 1:+ return+ started.set()+ await _wait(catch_up_listed)+ _source_data["x"] = 9+ handle = await operator.update(+ coco.component_subpath("x"), _declare_item, "x", 9+ )+ await handle.ready()+ applied.set()+ await asyncio.Event().wait()++ async def _main() -> None:+ await coco.mount(coco.component_subpath("live"), _Live)++ app = coco.App(+ coco.AppConfig(name="test_live_update_during_catch_up", environment=coco_env),+ _main,+ )+ live_task = asyncio.create_task(app.update(live=True).result())+ try:+ await _wait(started)+ catch_up = asyncio.create_task(app.update().result())+ await _wait(catch_up_listed)+ # Give the live update a moment to reach the engine.+ await asyncio.sleep(0.3)+ release_catch_up.set()+ await asyncio.wait_for(catch_up, timeout=10.0)+ await _wait(applied)+ assert "x" in GlobalDictTarget.store.data+ finally:+ release_catch_up.set()+ try:+ await app.drop()+ finally:+ live_task.cancel()+ try:+ await live_task+ except BaseException:+ pass++# ============================================================================# LiveStream primitives# ============================================================================diff --git a/rust/core/src/engine/app.rs b/rust/core/src/engine/app.rsindex 6b7d6b39..08f9e101 100644--- a/rust/core/src/engine/app.rs+++ b/rust/core/src/engine/app.rs@@ -220,7 +220,7 @@ impl<Prof: EngineProfile> App<Prof> {let processing_stats = ProcessingStats::default();let version_rx = processing_stats.subscribe();- let providers = self+ let mut providers = self.app_ctx().env().target_states_providers()@@ -228,6 +228,14 @@ impl<Prof: EngineProfile> App<Prof> {.unwrap().providers.clone();+ // Root providers this app's runs registered at run time are not in+ // the environment's registry; add them so their target states are+ // reverted too.+ for (path, provider) in self.app_ctx().run_root_providers() {+ if !providers.contains_key(&path) {+ providers.insert_mut(path, provider);+ }+ }// Install a single on_error handler that always propagates: app.drop// is an explicit operation, so root-delete failures (and anydiff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rsindex 28eb063e..f200989a 100644--- a/rust/core/src/engine/component.rs+++ b/rust/core/src/engine/component.rs@@ -3378,6 +3378,74 @@ mod tests {);}+ /// `drop_app` reverts the target states of a root provider that a run+ /// registered at run time (in its build state, not in the environment's+ /// registry): the handler sees a deletion for each of them, and its sink+ /// applies it.+ #[tokio::test]+ async fn drop_app_reverts_a_root_provider_registered_at_run_time() {+ let (app, _dir) = test_app("drop_run_time_provider").await;+ let apply_calls = Arc::new(AtomicUsize::new(0));+ let reconcile_calls = Arc::new(AtomicUsize::new(0));+ let root = {+ let (apply_calls, reconcile_calls) = (apply_calls.clone(), reconcile_calls.clone());+ TestProcessor::new(+ "root",+ Fingerprint::from(&"drop_run_time_provider").unwrap(),+ Arc::new(AtomicBool::new(false)),+ false,+ )+ .without_memo()+ .with_on_process(Arc::new(move |ctx| {+ let sink = TargetActionSinkKeeper::new(NoopSink {+ apply_calls: apply_calls.clone(),+ children: None,+ });+ let reconcile_calls = reconcile_calls.clone();+ Box::pin(async move {+ let provider = register_root_target_state_provider(+ &ctx,+ "target".to_string(),+ CountingHandler {+ reconcile_calls,+ sink,+ reject: false,+ change_only: true,+ },+ )?;+ for key in [0, 1] {+ declare_target_state(+ &ctx,+ &FnCallContext::default(),+ provider.clone(),+ StableKey::Int(key),+ (),+ )?;+ }+ Ok(TestData(b"ret".to_vec()))+ })+ }))+ };+ let (handle, _) = app+ .update(root, AppUpdateOptions::default(), Arc::new(()), None)+ .unwrap();+ handle.result().await.unwrap();+ assert_eq!(apply_calls.load(Ordering::SeqCst), 1);+ assert_eq!(reconcile_calls.load(Ordering::SeqCst), 2);++ app.drop_app(Arc::new(())).unwrap().result().await.unwrap();+ assert_eq!(+ reconcile_calls.load(Ordering::SeqCst),+ 4,+ "drop reconciles both target states of the run-time provider away"+ );+ assert_eq!(+ apply_calls.load(Ordering::SeqCst),+ 2,+ "drop applies the deletions through the provider's sink"+ );+ }+/// A re-run of an unmemoized component that declares the same target/// states, which its handler finds unchanged, writes nothing: neither its/// precommit nor its commit has a page to write, so no write txn commitsdiff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rsindex 4e47289c..2cd7aeed 100644--- a/rust/core/src/engine/context.rs+++ b/rust/core/src/engine/context.rs@@ -62,6 +62,13 @@ struct AppContextInner<Prof: EngineProfile> {live_components: parking_lot::Mutex<Vec<std::sync::Weak<crate::engine::live_component::LiveComponentState<Prof>>>,>,++ /// Root target-state providers (with their attachment providers) that+ /// this app's runs registered at run time, by path; the latest+ /// registration of a path wins. Such a provider lives in its run's build+ /// state only, not in the environment's registry, so `App::drop_app`+ /// adds these to revert the target states they own.+ run_root_providers: parking_lot::Mutex<HashMap<TargetStatePath, TargetStateProvider<Prof>>>,}#[derive(Clone)]@@ -88,10 +95,30 @@ impl<Prof: EngineProfile> AppContext<Prof> {crate::engine::runtime::global_cancellation_token().child_token(),),live_components: parking_lot::Mutex::new(Vec::new()),+ run_root_providers: parking_lot::Mutex::new(HashMap::new()),}),}}+ /// Remember root providers a run registered; see `run_root_providers`.+ pub(crate) fn remember_run_root_providers(+ &self,+ providers: impl IntoIterator<Item = (TargetStatePath, TargetStateProvider<Prof>)>,+ ) {+ self.inner.run_root_providers.lock().extend(providers);+ }++ /// The root providers this app's runs registered; see+ /// `run_root_providers`.+ pub(crate) fn run_root_providers(&self) -> Vec<(TargetStatePath, TargetStateProvider<Prof>)> {+ self.inner+ .run_root_providers+ .lock()+ .iter()+ .map(|(path, provider)| (path.clone(), provider.clone()))+ .collect()+ }+/// Register a live component for shutdown drain coverage.////// Compacts dead `Weak`s out of the registry before appending the new one,diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rsindex 6f045b0c..1b1cea87 100644--- a/rust/core/src/engine/execution.rs+++ b/rust/core/src/engine/execution.rs@@ -491,12 +491,23 @@ pub fn register_root_target_state_provider<Prof: EngineProfile>(name: String,handler: Prof::TargetHdl,) -> Result<TargetStateProvider<Prof>> {- comp_ctx.update_building_state(|building_state| {- building_state- .target_states- .provider_registry- .register_root(name, handler)- })+ let (provider, added) = comp_ctx.update_building_state(|building_state| {+ let registry = &mut building_state.target_states.provider_registry;+ let before = registry.providers.clone();+ let provider = registry.register_root(name, handler)?;+ // The root provider and the attachment providers it registered.+ let added: Vec<_> = registry+ .providers+ .iter()+ .filter(|(path, _)| !before.contains_key(*path))+ .map(|(path, provider)| (path.clone(), provider.clone()))+ .collect();+ Ok((provider, added))+ })?;+ // A provider registered by a run lives in that run's build state only;+ // the app remembers it so `App::drop_app` can revert its target states.+ comp_ctx.app_ctx().remember_run_root_providers(added);+ Ok(provider)}pub fn declare_target_state_with_child<Prof: EngineProfile>(diff --git a/rust/core/src/engine/live_component.rs b/rust/core/src/engine/live_component.rsindex 0accedef..f869ff82 100644--- a/rust/core/src/engine/live_component.rs+++ b/rust/core/src/engine/live_component.rs@@ -94,7 +94,16 @@ impl<Prof: EngineProfile> MountLivePending<Prof> {live,} = self;- // 2. If existing live state, cancel and drain it (with 30s timeout).+ // 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.//// Without a timeout, a prior incarnation wedged in non-yielding// synchronous Python compute would hold the parent's@@ -106,7 +115,12 @@ 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).- if let Some(existing_state) = child.live_state() {+ let existing_state = child.live_state();+ let beside_running_live = !live+ && existing_state+ .as_ref()+ .is_some_and(|state| state.is_running_live());+ if let Some(existing_state) = existing_state.as_ref().filter(|_| !beside_running_live) {let drain_fut = existing_state.cancel_and_drain();if tokio::time::timeout(std::time::Duration::from_secs(LIVE_COMPONENT_DRAIN_TIMEOUT_SECS),@@ -160,9 +174,16 @@ 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 {+ existing_state.clone()+ } else {+ None+ };let state = Arc::new(LiveComponentState::<Prof>::new(readiness_guard,cancellation_token,+ live,+ beside,));// 6. Install ordering (matters for drop_app race coverage):@@ -177,8 +198,11 @@ 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).- child.set_live_state(state.clone());+ // releases the strong ref). An incarnation running beside a live one+ // (step 2) is anchored by its controller alone.+ if !beside_running_live {+ child.set_live_state(state.clone());+ }parent_ctx.app_ctx().register_live_component(Arc::downgrade(&state));@@ -329,12 +353,26 @@ pub struct LiveComponentState<Prof: EngineProfile> {/// JoinHandle of the tokio task running `process_live`. Set by `start()`.live_task: Mutex<Option<tokio::task::JoinHandle<()>>>,++ /// Whether this incarnation was mounted by a live update.+ live: bool,++ /// For a catch-up incarnation mounted beside a running live one: that+ /// live incarnation. The catch-up's `update_full` also takes the live+ /// one's `update_full_lock` and `update_full_active` gate and waits for+ /// its drains, so a live `update()` cannot land between the catch-up's+ /// source listing and its commit (which would reconcile it away). A+ /// live `update()` that arrives meanwhile queues and runs after the+ /// catch-up's commit.+ beside: Option<Arc<LiveComponentState<Prof>>>,}impl<Prof: EngineProfile> LiveComponentState<Prof> {pub fn new(readiness_guard: ComponentBgChildReadinessChildGuard,cancellation_token: tokio_util::sync::CancellationToken,+ live: bool,+ beside: Option<Arc<LiveComponentState<Prof>>>,) -> Self {Self {update_full_lock: tokio::sync::Mutex::new(()),@@ -347,9 +385,26 @@ impl<Prof: EngineProfile> LiveComponentState<Prof> {ready_notify: tokio::sync::Notify::new(),cancellation_token,live_task: Mutex::new(None),+ live,+ beside,}}+ /// Whether this is a live update's incarnation whose `process_live`+ /// may still be following its source: it is not cancelled, and its task+ /// has not finished. (Before `start()` sets the task, a mounted live+ /// incarnation is about to run, so it counts as running.)+ fn is_running_live(&self) -> bool {+ self.live+ && !self.cancellation_token.is_cancelled()+ && !self+ .live_task+ .lock()+ .unwrap()+ .as_ref()+ .is_some_and(|task| task.is_finished())+ }+pub fn cancellation_token(&self) -> &tokio_util::sync::CancellationToken {&self.cancellation_token}@@ -603,6 +658,12 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {on_error: Option<OnError>,) -> Result<()> {let _full_guard = self.state.update_full_lock.lock().await;+ // A catch-up incarnation beside a running live one also holds the+ // live one's lock (always after its own: one lock order).+ let _beside_full_guard = match &self.state.beside {+ Some(live) => Some(live.update_full_lock.lock().await),+ None => None,+ };// Step-1 cancellation gate (mirrors design.md Section "update_full// body, step 1"). Avoids paying drain cost on a cancelled controller.@@ -614,12 +675,16 @@ impl<Prof: EngineProfile> LiveComponentController<Prof> {// observing it know to gate themselves before promoting queued ops.// Use an RAII guard so we always clear it on every exit path.let _active_guard = UpdateFullActiveGuard::new(&self.state);+ let _beside_active_guard = self.state.beside.as_deref().map(UpdateFullActiveGuard::new);// Wait until no subpath has `processing == true`. We allow queued// ops to remain β they'll be re-collapsed to `Superseded` once// process() completes, since `update_full` re-derives all subpaths// authoritatively.self.state.wait_until_quiescent().await;+ if let Some(live) = &self.state.beside {+ live.wait_until_quiescent().await;+ }// Now run process() via run_in_background. Errors from process() are// routed via `on_error` (parent's exception handler chain), matching