Skip to content

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

perf(core): a submit that changes nothing writes nothing (#2785)

LJ πŸ₯₯🌴b6f2462b6b7b
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rs
index 8b4f5c16..28eb063e 100644
--- a/rust/core/src/engine/component.rs
+++ b/rust/core/src/engine/component.rs
@@ -1933,6 +1933,7 @@ mod tests {
reconcile_calls: child_reconcile_calls.clone(),
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject: false,
+ change_only: false,
}
}
}
@@ -1976,6 +1977,10 @@ mod tests {
reconcile_calls: Arc<AtomicUsize>,
sink: TargetActionSinkKeeper<TestProfile>,
reject: bool,
+ /// Plan an action only for a change, as a real connector does:
+ /// nothing for a desired target state the stored records already
+ /// hold, and a deletion for one no longer declared.
+ change_only: bool,
}
impl TargetHandler<TestProfile> for CountingHandler {
@@ -1983,13 +1988,27 @@ mod tests {
&self,
key: StableKey,
desired_target_state: Option<&()>,
- _prev_possible_records: &[TestData],
- _prev_may_be_missing: bool,
+ prev_possible_records: &[TestData],
+ prev_may_be_missing: bool,
) -> crate::prelude::Result<Option<TargetReconcileOutput<TestProfile>>> {
self.reconcile_calls.fetch_add(1, Ordering::SeqCst);
if self.reject && desired_target_state.is_some() {
cocoindex_utils::client_bail!("target state {key:?} rejected");
}
+ if self.change_only {
+ if desired_target_state.is_some()
+ && !prev_may_be_missing
+ && !prev_possible_records.is_empty()
+ {
+ return Ok(None);
+ }
+ return Ok(Some(TargetReconcileOutput {
+ action: (),
+ sink: self.sink.clone(),
+ tracking_record: desired_target_state.map(|_| TestData(Vec::new())),
+ child_invalidation: None,
+ }));
+ }
Ok(desired_target_state.map(|_| TargetReconcileOutput {
action: (),
sink: self.sink.clone(),
@@ -2061,6 +2080,9 @@ mod tests {
memo_states_reusable: bool,
/// What the memo state handler reports as `states_changed`.
memo_states_changed: bool,
+ /// Whether the processor has a memo key (`memo_fp`); a processor
+ /// without one re-runs every time and stores no component memo.
+ memoized: bool,
on_process: Option<ProcessHook>,
}
@@ -2078,10 +2100,17 @@ mod tests {
advance_clock_in_state_handler,
memo_states_reusable: false,
memo_states_changed: false,
+ memoized: true,
on_process: None,
}
}
+ /// No memo key: the component re-runs on every update.
+ fn without_memo(mut self) -> Self {
+ self.memoized = false;
+ self
+ }
+
fn with_reusable_memo_states(mut self) -> Self {
self.memo_states_reusable = true;
self
@@ -2124,7 +2153,7 @@ mod tests {
}
fn memo_key_fingerprint(&self) -> Option<Fingerprint> {
- Some(self.memo_fp)
+ self.memoized.then_some(self.memo_fp)
}
fn processor_info(&self) -> &ComponentProcessorInfo {
@@ -2920,6 +2949,7 @@ mod tests {
reconcile_calls: Arc::new(AtomicUsize::new(0)),
sink: container_sink,
reject: false,
+ change_only: false,
},
)?;
*child_provider.lock().unwrap() = Some(declare_target_state_with_child(
@@ -3171,6 +3201,7 @@ mod tests {
reconcile_calls: Arc::new(AtomicUsize::new(0)),
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject: false,
+ change_only: false,
},
)
.unwrap();
@@ -3347,6 +3378,108 @@ mod tests {
);
}
+ /// 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 commits
+ /// and the store keeps every byte. A changed declaration still writes,
+ /// and the run after it is again write-free.
+ #[tokio::test]
+ async fn an_unchanged_rerun_commits_no_write_txn() {
+ let (app, _dir) = test_app("unchanged_rerun").await;
+ let apply_calls = Arc::new(AtomicUsize::new(0));
+ let root = |keys: Vec<i64>| {
+ let apply_calls = apply_calls.clone();
+ TestProcessor::new(
+ "root",
+ Fingerprint::from(&"unchanged_rerun").unwrap(),
+ Arc::new(AtomicBool::new(false)),
+ false,
+ )
+ .without_memo()
+ .with_on_process(Arc::new(move |ctx| {
+ let keys = keys.clone();
+ let sink = TargetActionSinkKeeper::new(NoopSink {
+ apply_calls: apply_calls.clone(),
+ children: None,
+ });
+ Box::pin(async move {
+ let provider = register_root_target_state_provider(
+ &ctx,
+ "target".to_string(),
+ CountingHandler {
+ reconcile_calls: Arc::new(AtomicUsize::new(0)),
+ sink,
+ reject: false,
+ change_only: true,
+ },
+ )?;
+ for key in keys {
+ declare_target_state(
+ &ctx,
+ &FnCallContext::default(),
+ provider.clone(),
+ StableKey::Int(key),
+ (),
+ )?;
+ }
+ Ok(TestData(b"ret".to_vec()))
+ })
+ }))
+ };
+ let run = |keys: Vec<i64>, full_reprocess: bool| {
+ let options = AppUpdateOptions {
+ full_reprocess,
+ ..AppUpdateOptions::default()
+ };
+ let (handle, _) = app.update(root(keys), options, Arc::new(()), None).unwrap();
+ async move { handle.result().await.unwrap() }
+ };
+ let last_txn_id = || {
+ app.app_ctx()
+ .persisting_app_store()
+ .env()
+ .info()
+ .last_txn_id
+ };
+
+ run(vec![0, 1], false).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 1);
+ let (txn_before, contents_before) = (last_txn_id(), app_store_contents(&app).await);
+ run(vec![0, 1], false).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 1, "nothing to apply");
+ assert_eq!(
+ last_txn_id(),
+ txn_before,
+ "an unchanged re-run commits no write txn"
+ );
+ assert!(app_store_contents(&app).await == contents_before);
+
+ // A dropped declaration applies its deletion and commits.
+ run(vec![0], false).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), 2);
+ assert_ne!(last_txn_id(), txn_before);
+ let (txn_dropped, contents_dropped) = (last_txn_id(), app_store_contents(&app).await);
+ assert!(contents_dropped != contents_before);
+ run(vec![0], false).await;
+ assert_eq!(last_txn_id(), txn_dropped);
+ assert!(app_store_contents(&app).await == contents_dropped);
+
+ // Declaring it again applies its creation and commits.
+ let applied = apply_calls.load(Ordering::SeqCst);
+ run(vec![0, 1], false).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 1);
+ assert_ne!(last_txn_id(), txn_dropped);
+
+ // `full_reprocess` re-applies every target state, and the next
+ // ordinary run is write-free again.
+ run(vec![0, 1], true).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 2);
+ let txn_reprocessed = last_txn_id();
+ run(vec![0, 1], false).await;
+ assert_eq!(apply_calls.load(Ordering::SeqCst), applied + 2);
+ assert_eq!(last_txn_id(), txn_reprocessed);
+ }
+
/// A deprecated slot-fulfilling sink still works for a real update, but
/// fails a preview with an error naming the unsupported case.
#[tokio::test]
@@ -3444,6 +3577,7 @@ mod tests {
reconcile_calls: reconcile_calls.clone(),
sink: TargetActionSinkKeeper::new(NoopSink::default()),
reject,
+ change_only: false,
},
)
.unwrap();
diff --git a/rust/core/src/engine/context.rs b/rust/core/src/engine/context.rs
index c6693ba1..4e47289c 100644
--- a/rust/core/src/engine/context.rs
+++ b/rust/core/src/engine/context.rs
@@ -1717,11 +1717,11 @@ mod tests {
path: &StablePath,
cache: UserStateCache<TestData>,
) {
- use crate::state_store::CommitPlan;
+ use crate::state_store::{CommitPlan, TrackingInfoWrite};
let plan_data = cache.into_flush_plan().unwrap();
let plan = CommitPlan {
- new_tracking_info: None,
+ tracking_info: TrackingInfoWrite::Delete,
target_owners_to_upsert: Vec::new(),
target_owners_to_delete: Vec::new(),
fn_memo_clear_all_first: false,
diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rs
index 3f47c5a6..6f045b0c 100644
--- a/rust/core/src/engine/execution.rs
+++ b/rust/core/src/engine/execution.rs
@@ -25,7 +25,8 @@ use crate::state::target_state_path::{
};
use crate::state_store::{
AppStore, CommitPlan, ExistenceReconciler, OwnerStateForPreempt, PrecommitClaimTargetsPlan,
- PrecommitReadPlan, PrecommitWritePlan, WriteScope, WriteTxn, reconcile_child_existence,
+ PrecommitReadPlan, PrecommitWritePlan, TrackingInfoWrite, WriteScope, WriteTxn,
+ reconcile_child_existence,
};
use cocoindex_utils::deser::from_msgpack_slice;
use cocoindex_utils::fingerprint::Fingerprint;
@@ -563,6 +564,76 @@ enum ChildExistenceAction {
Keep,
}
+/// The commit-time form of a tracking record whose precommit, at
+/// `curr_version`, succeeded: drop the states the lifecycle superseded (older
+/// versions, and a current `Deleted`), prune the items left with none, clear
+/// the pending token, take the providers' current schema versions, and, once
+/// every state is at `curr_version`, converge the versions back to 1. Returns
+/// the target-state paths no surviving item uses any more, whose `__target`
+/// owner rows go too.
+///
+/// One function for [`Committer::build_commit_writes`] and for `pre_commit`,
+/// which runs it to see whether a build changes the stored record at all.
+fn finalize_tracking_info<Prof: EngineProfile>(
+ tracking_info: &mut db_schema::StablePathEntryTrackingInfo<'_>,
+ curr_version: u64,
+ target_states_providers: &rpds::HashTrieMapSync<TargetStatePath, TargetStateProvider<Prof>>,
+) -> HashSet<TargetStatePath> {
+ for item in tracking_info.target_state_items.values_mut() {
+ item.states.retain(|(version, state)| {
+ *version > curr_version || *version == curr_version && !state.is_deleted()
+ });
+ }
+ // Prune entries with empty states and collect their paths for
+ // inverted-tracking cleanup. Component-level
+ // `pending_process_token` is cleared here β€” pre_commit β†’
+ // sink_apply β†’ commit is succeeding, so any token written by
+ // pre_commit is no longer "pending".
+ let mut pruned_paths: HashSet<TargetStatePath> = HashSet::new();
+ tracking_info
+ .target_state_items
+ .retain(|path_with_pid, item| {
+ if item.states.is_empty() {
+ pruned_paths.insert(path_with_pid.target_state_path.clone());
+ false
+ } else {
+ true
+ }
+ });
+ tracking_info.pending_process_token = None;
+ // Don't delete inverted tracking if a surviving entry shares the
+ // same target_state_path (provider_id change β€” old entry pruned,
+ // new entry survives under different provider_id).
+ if !pruned_paths.is_empty() {
+ for path_with_pid in tracking_info.target_state_items.keys() {
+ pruned_paths.remove(&path_with_pid.target_state_path);
+ }
+ }
+ for (path_with_pid, item) in tracking_info.target_state_items.iter_mut() {
+ if let Some(parent_provider) =
+ target_states_providers.get(path_with_pid.target_state_path.provider_path())
+ && let Some(pg) = parent_provider.provider_generation()
+ {
+ item.provider_schema_version = pg.provider_schema_version;
+ }
+ }
+
+ let is_version_converged = tracking_info.target_state_items.iter().all(|(_, item)| {
+ item.states
+ .iter()
+ .all(|(version, _)| *version == curr_version)
+ });
+ if is_version_converged {
+ tracking_info.version = 1;
+ for item in tracking_info.target_state_items.values_mut() {
+ for (version, _) in item.states.iter_mut() {
+ *version = 1;
+ }
+ }
+ }
+ pruned_paths
+}
+
struct Committer<Prof: EngineProfile> {
component_ctx: ComponentProcessorContext<Prof>,
app_store: AppStore,
@@ -592,9 +663,9 @@ impl<Prof: EngineProfile> Committer<Prof> {
child_existence: ChildExistenceAction,
fn_memos: FnMemoCache<Prof>,
user_states: UserStateCache<Prof::FunctionData>,
- curr_version: Option<u64>,
+ tracking: PrecommittedTracking,
) -> Result<()> {
- self.commit_writes(child_existence, fn_memos, user_states, curr_version)
+ self.commit_writes(child_existence, fn_memos, user_states, tracking)
.await?;
self.launch_child_component_gc().await
}
@@ -611,7 +682,7 @@ impl<Prof: EngineProfile> Committer<Prof> {
child_existence: ChildExistenceAction,
fn_memos: FnMemoCache<Prof>,
user_states: UserStateCache<Prof::FunctionData>,
- curr_version: Option<u64>,
+ tracking: PrecommittedTracking,
) -> Result<()> {
// Consume FnMemoCache once (drains each entry's RwLock to Pending).
let fn_memo_plan = fn_memos.into_flush_plan()?;
@@ -624,8 +695,7 @@ impl<Prof: EngineProfile> Committer<Prof> {
// converge β€” produce final bytes the AppStore will write. Per-
// component exclusivity means no concurrent writer can change
// `__track` between this standalone read and `app_store.commit`.
- let (new_tracking_info, target_owners_to_delete) =
- self.build_commit_writes(curr_version).await?;
+ let (tracking_info, target_owners_to_delete) = self.build_commit_writes(tracking).await?;
// On whole-component deletion, also clear the `Live` user-state
// keyspace. The regular flush (clear_all_first / writes / deletes)
@@ -637,7 +707,7 @@ impl<Prof: EngineProfile> Committer<Prof> {
let user_state_clear_live = self.component_ctx.mode() == ComponentProcessingMode::Delete;
let plan = CommitPlan {
- new_tracking_info,
+ tracking_info,
target_owners_to_upsert: Vec::new(),
target_owners_to_delete,
fn_memo_clear_all_first: fn_memo_plan.clear_all_first,
@@ -693,15 +763,17 @@ impl<Prof: EngineProfile> Committer<Prof> {
})
}
- /// Engine-side reconcile that produces the `(new_tracking_info,
+ /// Engine-side reconcile that produces the `(tracking_info,
/// target_owners_to_delete)` portion of [`CommitPlan`]. Delete
- /// mode short-circuits to `(None, owned_target_paths)`, signalling
+ /// mode short-circuits to `(Delete, owned_target_paths)`, signalling
/// the session to delete the `__track` row and every `__target`
- /// owner row this component still holds.
+ /// owner row this component still holds. A build whose precommit found
+ /// nothing to change ([`PrecommittedTracking::Unchanged`]) keeps the row
+ /// as stored.
async fn build_commit_writes(
&self,
- curr_version: Option<u64>,
- ) -> Result<(Option<Vec<u8>>, Vec<TargetStatePath>)> {
+ tracking: PrecommittedTracking,
+ ) -> Result<(TrackingInfoWrite, Vec<TargetStatePath>)> {
if self.component_ctx.mode() == ComponentProcessingMode::Delete {
// Whole-component deletion also drops the inverted `__target`
// owner index for every path this component still owns. Without
@@ -725,10 +797,19 @@ impl<Prof: EngineProfile> Committer<Prof> {
}
None => Vec::new(),
};
- return Ok((None, owners_to_delete));
+ return Ok((TrackingInfoWrite::Delete, owners_to_delete));
}
- let curr_version = curr_version
- .ok_or_else(|| internal_error!("curr_version is required for Build mode"))?;
+ let curr_version = match tracking {
+ PrecommittedTracking::Written(version) => version,
+ PrecommittedTracking::Final {
+ bytes,
+ owners_to_delete,
+ } => return Ok((TrackingInfoWrite::Write(bytes), owners_to_delete)),
+ PrecommittedTracking::Unchanged => return Ok((TrackingInfoWrite::Keep, Vec::new())),
+ PrecommittedTracking::None => {
+ internal_bail!("a build commit needs the tracking record its precommit wrote")
+ }
+ };
let tracking_info_bytes = self
.app_store
.read_tracking_info(&self.component_path)
@@ -736,64 +817,14 @@ impl<Prof: EngineProfile> Committer<Prof> {
.ok_or_else(|| internal_error!("tracking info not found for commit"))?;
let mut tracking_info: db_schema::StablePathEntryTrackingInfo<'_> =
from_msgpack_slice(&tracking_info_bytes)?;
-
- for item in tracking_info.target_state_items.values_mut() {
- item.states.retain(|(version, state)| {
- *version > curr_version || *version == curr_version && !state.is_deleted()
- });
- }
- // Prune entries with empty states and collect their paths for
- // inverted-tracking cleanup. Component-level
- // `pending_process_token` is cleared here β€” pre_commit β†’
- // sink_apply β†’ commit is succeeding, so any token written by
- // pre_commit is no longer "pending".
- let mut pruned_paths: HashSet<TargetStatePath> = HashSet::new();
- tracking_info
- .target_state_items
- .retain(|path_with_pid, item| {
- if item.states.is_empty() {
- pruned_paths.insert(path_with_pid.target_state_path.clone());
- false
- } else {
- true
- }
- });
- tracking_info.pending_process_token = None;
- // Don't delete inverted tracking if a surviving entry shares the
- // same target_state_path (provider_id change β€” old entry pruned,
- // new entry survives under different provider_id).
- if !pruned_paths.is_empty() {
- for path_with_pid in tracking_info.target_state_items.keys() {
- pruned_paths.remove(&path_with_pid.target_state_path);
- }
- }
- for (path_with_pid, item) in tracking_info.target_state_items.iter_mut() {
- if let Some(parent_provider) = self
- .target_states_providers
- .get(path_with_pid.target_state_path.provider_path())
- && let Some(pg) = parent_provider.provider_generation()
- {
- item.provider_schema_version = pg.provider_schema_version;
- }
- }
-
- let is_version_converged = tracking_info.target_state_items.iter().all(|(_, item)| {
- item.states
- .iter()
- .all(|(version, _)| *version == curr_version)
- });
- if is_version_converged {
- tracking_info.version = 1;
- for item in tracking_info.target_state_items.values_mut() {
- for (version, _) in item.states.iter_mut() {
- *version = 1;
- }
- }
- }
-
+ let pruned_paths = finalize_tracking_info(
+ &mut tracking_info,
+ curr_version,
+ &self.target_states_providers,
+ );
let data_bytes = rmp_serde::to_vec_named(&tracking_info)?;
let owners_to_delete: Vec<TargetStatePath> = pruned_paths.into_iter().collect();
- Ok((Some(data_bytes), owners_to_delete))
+ Ok((TrackingInfoWrite::Write(data_bytes), owners_to_delete))
}
/// Phase 5 GC: snapshot-read tombstones and spawn child delete
@@ -987,8 +1018,35 @@ async fn build_factory_children<Prof: EngineProfile>(
Ok(children)
}
+/// The tracking record a precommit left for its commit.
+///
+/// The precommit writes the record, with its stage marker, only when the
+/// build queued sink actions (or claimed or preempted a target-state path,
+/// or set a provider generation): the marker is what recovers actions in
+/// flight should the process die before the commit. A build with none of
+/// these finalizes the record in the precommit instead and leaves the row
+/// to the commit alone, so it costs one durable write txn rather than two β€”
+/// and none when the record is unchanged.
+enum PrecommittedTracking {
+ /// No record: a component with nothing to track, or a deletion.
+ None,
+ /// The precommit wrote the record at this version; the commit finalizes
+ /// it (see [`finalize_tracking_info`]).
+ Written(u64),
+ /// The precommit wrote nothing; the commit writes these finalized bytes
+ /// and deletes the `__target` owner rows of the pruned paths.
+ Final {
+ bytes: Vec<u8>,
+ owners_to_delete: Vec<TargetStatePath>,
+ },
+ /// The finalized record equals the stored bytes: neither txn writes the
+ /// row. A warm run of an unchanged component, whose other writes are
+ /// empty too, so commits with no page to sync.
+ Unchanged,
+}
+
struct PreCommitOutput<Prof: EngineProfile> {
- curr_version: Option<u64>,
+ tracking: PrecommittedTracking,
previously_exists: bool,
actions_by_sinks: HashMap<TargetActionSinkKeeper<Prof>, SinkInput<Prof>>,
/// Name of the processor to be deleted; caller passes it to `collect_processor_name_name_for_del`.
@@ -1114,6 +1172,8 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
>,
declared_paths_all: Vec<TargetStatePath>,
mut tracking_info: Option<db_schema::StablePathEntryTrackingInfo<'tracking>>,
+ existing_tracking_info_bytes: Option<&[u8]>,
+ claims_new_paths: bool,
prior_owners: BTreeMap<TargetStatePath, Option<StablePath>>,
preempted_owner_states: BTreeMap<StablePath, OwnerStateForPreempt>,
) -> Result<PreCommitOutcome<Prof>> {
@@ -1584,13 +1644,45 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
Some(process_token)
};
- let data_bytes = rmp_serde::to_vec_named(&tracking_info)?;
+ // A build that queued no action, claims no new target-state path,
+ // preempts none and sets no provider generation changes nothing
+ // outside this record, and has no action for a stage marker to
+ // protect: finalize the record here, as its commit would, and leave
+ // the row to the commit (see `PrecommittedTracking`). Build mode only
+ // (`processor_name`): a deletion's commit removes the row.
+ let finalize_now = processor_name.is_some()
+ && actions_by_sinks.is_empty()
+ && !claims_new_paths
+ && deferred_provider_generations.is_empty()
+ && preempted_owners.values().all(|owner| !owner.modified);
+ let tracking = if finalize_now {
+ let pruned_paths =
+ finalize_tracking_info(&mut tracking_info, curr_version, target_states_providers);
+ let bytes = rmp_serde::to_vec_named(&tracking_info)?;
+ if existing_tracking_info_bytes == Some(bytes.as_slice()) {
+ (PrecommittedTracking::Unchanged, None)
+ } else {
+ (
+ PrecommittedTracking::Final {
+ bytes,
+ owners_to_delete: pruned_paths.into_iter().collect(),
+ },
+ None,
+ )
+ }
+ } else {
+ let data_bytes = rmp_serde::to_vec_named(&tracking_info)?;
+ (
+ PrecommittedTracking::Written(curr_version),
+ Some(data_bytes),
+ )
+ };
drop(tracking_info); // Release borrow before further mutation.
- (Some(curr_version), Some(data_bytes))
+ tracking
} else {
- (None, None)
+ (PrecommittedTracking::None, None)
};
- let (curr_version, new_tracking_info_bytes) = curr_version;
+ let (tracking, new_tracking_info_bytes) = curr_version;
// Encode each modified preempted owner once into the write plan. The
// backend writes them alongside the self tracking_info in the same
@@ -1608,7 +1700,7 @@ async fn pre_commit<'tracking, Prof: EngineProfile>(
// `OnceLock::set` "already set" guard.
Ok(PreCommitOutcome::Done {
output: PreCommitOutput {
- curr_version,
+ tracking,
previously_exists,
actions_by_sinks,
processor_name_for_del,
@@ -1824,6 +1916,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
.filter(|p| !existing_paths.contains(*p))
.cloned()
.collect();
+ let claims_new_paths = !paths_to_claim.is_empty();
let claim = session
.precommit_claim_targets(
@@ -1847,6 +1940,8 @@ pub(crate) async fn submit<Prof: EngineProfile>(
Arc::clone(&c.declared_target_states),
declared_paths_all,
tracking_info,
+ existing_tracking_info_bytes.as_deref(),
+ claims_new_paths,
claim.prior_owners,
claim.preempted_owner_states,
)
@@ -1892,7 +1987,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
if let Some(ref name) = pre_commit_out.processor_name_for_del {
collect_processor_name_name_for_del(name);
}
- let curr_version = pre_commit_out.curr_version;
+ let tracking = pre_commit_out.tracking;
let touched_previous_states = pre_commit_out.previously_exists;
#[allow(
clippy::mutable_key_type,
@@ -1944,7 +2039,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
// (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, curr_version)
+ .commit_writes(child_existence, fn_memos, user_states, tracking)
.await?;
Ok(children)
}
@@ -2010,7 +2105,7 @@ pub(crate) async fn submit<Prof: EngineProfile>(
// session handoff needed.
let committer = Committer::new(comp_ctx, target_states_providers)?;
if let Err(e) = committer
- .commit(child_existence, fn_memos, user_states, curr_version)
+ .commit(child_existence, fn_memos, user_states, tracking)
.await
{
// The commit txn either committed or rolled back before
diff --git a/rust/core/src/state_store/mod.rs b/rust/core/src/state_store/mod.rs
index 024e7dcd..d78f5d27 100644
--- a/rust/core/src/state_store/mod.rs
+++ b/rust/core/src/state_store/mod.rs
@@ -21,7 +21,7 @@ pub use storage::{Storage, StorageSettings};
pub use submit_session::{
CommitPlan, ExistenceReconciler, OwnerStateForPreempt, PrecommitClaimTargetsPlan,
PrecommitClaimTargetsResult, PrecommitReadPlan, PrecommitReadResult, PrecommitSession,
- PrecommitWritePlan, reconcile_child_existence,
+ PrecommitWritePlan, TrackingInfoWrite, reconcile_child_existence,
};
#[cfg(test)]
pub(crate) use txn::Db;
diff --git a/rust/core/src/state_store/submit_session.rs b/rust/core/src/state_store/submit_session.rs
index 728d972f..6aaa77f3 100644
--- a/rust/core/src/state_store/submit_session.rs
+++ b/rust/core/src/state_store/submit_session.rs
@@ -164,7 +164,7 @@ pub struct PrecommitWritePlan {
/// Self path.
pub self_path: StablePath,
/// New tracking-info bytes for this component. `None` skips the
- /// write (e.g. nothing to track yet).
+ /// write (nothing to track yet, or nothing the build changed).
pub new_tracking_info: Option<Vec<u8>>,
/// For each preempted other-owner: their new tracking-info bytes
/// (with the preempted item removed by the engine).
@@ -302,11 +302,22 @@ impl PrecommitSession {
// Phase 4 β€” Commit
// ---------------------------------------------------------------------------
+/// What [`AppStore::commit`] does to the component's tracking-info row.
+pub enum TrackingInfoWrite {
+ /// Write these final bytes (`Build` mode).
+ Write(Vec<u8>),
+ /// Delete the row (`Delete` mode).
+ Delete,
+ /// Leave the row as it is: the build queued no action and the bytes it
+ /// would write equal the stored ones, so its precommit wrote nothing
+ /// either (see `pre_commit` in the engine).
+ Keep,
+}
+
/// Inputs to [`AppStore::commit`].
pub struct CommitPlan {
- /// Final tracking-info bytes for self. `None` in `Delete` mode
- /// (AppStore deletes the row instead).
- pub new_tracking_info: Option<Vec<u8>>,
+ /// What happens to self's tracking-info row.
+ pub tracking_info: TrackingInfoWrite,
/// Bulk upserts on `__target`.
pub target_owners_to_upsert: Vec<(TargetStatePath, StablePath)>,
/// Bulk deletes from `__target` (pruned-item cleanup).
@@ -467,14 +478,18 @@ impl AppStore {
let plan = Arc::clone(&plan);
let existence_reconciler = Arc::clone(&existence_reconciler);
Box::pin(async move {
- if let Some(bytes) = plan.new_tracking_info.as_ref() {
- app_store
- .write_tracking_info_raw(wtxn, &component_path, bytes)
- .await?;
- } else {
- app_store
- .delete_tracking_info(wtxn, &component_path)
- .await?;
+ match &plan.tracking_info {
+ TrackingInfoWrite::Write(bytes) => {
+ app_store
+ .write_tracking_info_raw(wtxn, &component_path, bytes)
+ .await?;
+ }
+ TrackingInfoWrite::Delete => {
+ app_store
+ .delete_tracking_info(wtxn, &component_path)
+ .await?;
+ }
+ TrackingInfoWrite::Keep => {}
}
for (target_path, owner_path) in &plan.target_owners_to_upsert {
app_store
diff --git a/rust/core/tests/target_owner_cleanup.rs b/rust/core/tests/target_owner_cleanup.rs
index ef61e335..04fb1837 100644
--- a/rust/core/tests/target_owner_cleanup.rs
+++ b/rust/core/tests/target_owner_cleanup.rs
@@ -7,7 +7,9 @@ use std::sync::Arc;
use cocoindex_core::state::stable_path::{StableKey, StablePath};
use cocoindex_core::state::target_state_path::TargetStatePath;
-use cocoindex_core::state_store::{AppStore, CommitPlan, Storage, StorageSettings};
+use cocoindex_core::state_store::{
+ AppStore, CommitPlan, Storage, StorageSettings, TrackingInfoWrite,
+};
use cocoindex_utils::fingerprint::Fingerprint;
use tempfile::TempDir;
@@ -80,7 +82,7 @@ async fn commit_owner_deletes(
deletes: Vec<TargetStatePath>,
) {
let plan = CommitPlan {
- new_tracking_info: None,
+ tracking_info: TrackingInfoWrite::Delete,
target_owners_to_upsert: Vec::new(),
target_owners_to_delete: deletes,
fn_memo_clear_all_first: false,