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): apply a component's sinks parent-first (#2769)
LJ π₯₯π΄309724499490
diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rsindex a92554de..f89f1924 100644--- a/rust/core/src/engine/execution.rs+++ b/rust/core/src/engine/execution.rs@@ -856,6 +856,10 @@ struct SinkInput<Prof: EngineProfile> {/// sink for the declaring action. Read back after the sink call; a slot the/// sink left unfulfilled is an error.pending_children: Vec<(TargetStateProvider<Prof>, ChildTargetSlot<Prof>)>,+ /// The smallest [`TargetStateProvider::depth`] of the providers whose+ /// target states sent actions to this sink: sinks apply in this order+ /// (see [`sinks_in_apply_order`]).+ provider_depth: usize,}impl<Prof: EngineProfile> Default for SinkInput<Prof> {@@ -864,18 +868,22 @@ impl<Prof: EngineProfile> Default for SinkInput<Prof> {actions: Vec::new(),factory_children: Vec::new(),pending_children: Vec::new(),+ provider_depth: usize::MAX,}}}impl<Prof: EngineProfile> SinkInput<Prof> {- /// `child`: the child provider of the action's target state, with how its- /// sink provides child handlers.+ /// `provider`: the provider of the action's target state. `child`: the+ /// child provider of the action's target state, with how its sink+ /// provides child handlers.fn add_action(&mut self,+ provider: &TargetStateProvider<Prof>,action: Prof::TargetAction,child: Option<(TargetStateProvider<Prof>, ChildHandling)>,) -> Result<()> {+ self.provider_depth = self.provider_depth.min(provider.depth());let child_slot = match child {None => None,Some((child_provider, ChildHandling::Factory)) => {@@ -903,6 +911,23 @@ impl<Prof: EngineProfile> SinkInput<Prof> {}}+/// A component's sinks in the order they apply: those of shallower providers+/// first, so a container's sink (a table) applies before the sink of the+/// target states inside it (its rows), and those before the sinks of their+/// provider's attachments (an index over the rows, which may need the rows+/// to build). Sinks at one depth keep no particular order.+#[allow(+ clippy::mutable_key_type,+ reason = "`TargetActionSinkKeeper` hashes and compares by `Arc` identity"+)]+fn sinks_in_apply_order<Prof: EngineProfile>(+ actions_by_sinks: HashMap<TargetActionSinkKeeper<Prof>, SinkInput<Prof>>,+) -> Vec<(TargetActionSinkKeeper<Prof>, SinkInput<Prof>)> {+ let mut sinks: Vec<_> = actions_by_sinks.into_iter().collect();+ sinks.sort_by_key(|(_, input)| input.provider_depth);+ sinks+}+/// The child handlers of the [`ChildHandling::Factory`] sinks' child-bearing/// actions, each with the child provider it is for. A real update builds them/// right before applying the actions, a preview in place of applying them, so@@ -1302,7 +1327,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(// (`target_state_key_bytes`, `recon_output`, `child_provider`).// The guard drops at the end of this scope so subsequent awaits// in this iteration aren't carrying a `!Send` borrow.- let (target_state_key_bytes, recon_output, child_provider) = {+ let (target_state_key_bytes, recon_output, child_provider, provider) = {let guard = declared_target_states.lock().await;let decl = guard.get(target_state_path).ok_or_else(|| {internal_error!("declared entry vanished mid-pre_commit: {target_state_path}")@@ -1350,6 +1375,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(decl.item_key_bytes.to_vec(),recon_output,decl.child_provider.clone(),+ decl.provider.clone(),)};@@ -1408,7 +1434,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(let child = child_provider.map(|child_provider| (child_provider, recon_output.sink.child_handling()));let sink_input = actions_by_sinks.entry(recon_output.sink).or_default();- sink_input.add_action(recon_output.action, child)?;+ sink_input.add_action(&provider, recon_output.action, child)?;if let Some(item) = &mut prev_item {// Update existing item.@@ -1517,7 +1543,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(actions_by_sinks.entry(recon_output.sink).or_default()- .add_action(recon_output.action, None)?;+ .add_action(target_states_provider, recon_output.action, None)?;item.states.push((curr_version,match recon_output@@ -1951,7 +1977,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(// with nothing applied.pending_fulfillments.extend(build_factory_children(comp_ctx, &actions_by_sinks).await?);let host_runtime_ctx = comp_ctx.app_ctx().env().host_runtime_ctx();- for (sink, input) in actions_by_sinks {+ for (sink, input) in sinks_in_apply_order(actions_by_sinks) {sink.apply(host_runtime_ctx,Arc::clone(comp_ctx.host_ctx()),diff --git a/rust/core/src/engine/target_state.rs b/rust/core/src/engine/target_state.rsindex 732106c7..afa8cba2 100644--- a/rust/core/src/engine/target_state.rs+++ b/rust/core/src/engine/target_state.rs@@ -571,6 +571,18 @@ impl<Prof: EngineProfile> TargetStateProvider<Prof> {.join("/")}+ /// How many providers this one is below a root provider: 0 for a root,+ /// one more for each child or attachment provider below it.+ pub fn depth(&self) -> usize {+ let mut depth = 0;+ let mut current = self;+ while let Some(parent) = ¤t.inner.parent_provider {+ depth += 1;+ current = parent;+ }+ depth+ }+pub fn stable_key_chain(&self) -> Vec<StableKey> {let mut chain = vec![self.inner.stable_key.clone()];let mut current = self;diff --git a/rust/sdk/cocoindex/tests/target_state.rs b/rust/sdk/cocoindex/tests/target_state.rsindex 2ac15d73..0662cdba 100644--- a/rust/sdk/cocoindex/tests/target_state.rs+++ b/rust/sdk/cocoindex/tests/target_state.rs@@ -1143,6 +1143,48 @@ async fn attachment_lifecycle_create_and_cleanup() {assert_eq!(drain_sorted(&att_log), vec!["delete idx"]);}+/// Within one component's commit, the sink of an attachment (an index over+/// rows, which may need the rows to build) applies after the sink of the+/// target states it is attached to. Sink order is otherwise unspecified, so+/// several runs make an unordered apply fail almost surely.+#[tokio::test]+async fn attachment_sinks_apply_after_their_parents_sink() {+ let (app, _dir) = temp_app("attachment_order").await;+ for run in 0..8 {+ let log = new_log();+ let run_log = log.clone();+ app.update(move |ctx| {+ let log = run_log.clone();+ async move {+ let provider = register_root_target_states_provider(+ &ctx,+ "test/ordered_main",+ MainHandler {+ sink: recording_sink(log.clone()),+ att_log: log,+ },+ )?;+ declare_target_state(&ctx, provider.target_state("row", format!("v{run}")))?;+ let att: TargetStateProvider<String> = provider.attachment(&ctx, "index")?;+ declare_target_state(&ctx, att.target_state("idx", format!("spec{run}")))?;+ Ok(())+ }+ })+ .await+ .unwrap();+ let entries = std::mem::take(&mut *log.lock().unwrap());+ let verb = if run == 0 { "create" } else { "update" };+ assert_eq!(+ entries,+ vec![+ format!("{verb} row=v{run}"),+ format!("{verb} idx=spec{run}")+ ],+ "run {run}"+ );+ }+}+/// A main handler exposing two independent attachment types ("index", "tags").struct MultiAttachHandler {sink: TargetActionSink<RowAction>,