Skip to content

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

perf(rust-sdk): live LocalFS and LiveMap feeds process a burst concurrently (#2780)

LJ πŸ₯₯🌴d699eb1ccf83
diff --git a/rust/sdk/cocoindex/src/connectors/partition_tail.rs b/rust/sdk/cocoindex/src/connectors/partition_tail.rs
index e15109c4..d704c056 100644
--- a/rust/sdk/cocoindex/src/connectors/partition_tail.rs
+++ b/rust/sdk/cocoindex/src/connectors/partition_tail.rs
@@ -346,4 +346,93 @@ mod tests {
assert_eq!(recorder.ready.load(Ordering::SeqCst), 1);
assert!(source.commits.lock().unwrap().is_empty());
}
+
+ /// A subscriber whose handle for `fail_on` fails (a handler propagated
+ /// the child's error).
+ struct FailingOn {
+ fail_on: i64,
+ delivered: Mutex<Vec<i64>>,
+ }
+
+ #[crate::async_trait]
+ impl LiveStreamSubscriber<(&'static str, i64)> for FailingOn {
+ async fn send(&self, message: (&'static str, i64)) -> Result<ReadyHandle> {
+ self.delivered.lock().unwrap().push(message.1);
+ let fail = message.1 == self.fail_on;
+ Ok(ReadyHandle::from_future(async move {
+ if fail {
+ Err(crate::error::Error::engine("poison message"))
+ } else {
+ Ok(())
+ }
+ }))
+ }
+
+ async fn mark_ready(&self) {}
+ }
+
+ // A message whose processing fails ends the watch with its error and is
+ // never committed, so the next watch delivers it again; what was committed
+ // before it stays committed.
+ #[tokio::test]
+ async fn a_failed_message_is_not_committed_and_ends_the_watch() {
+ let Fakes { tails, .. } = fakes(vec![("a", vec!["x", "y", "z"])]);
+ let source = tails[0].source.clone();
+ let subscriber = FailingOn {
+ fail_on: 1,
+ delivered: Mutex::new(Vec::new()),
+ };
+ let err =
+ tokio::time::timeout(Duration::from_secs(5), watch_partitions(tails, &subscriber))
+ .await
+ .expect("the watch did not end on the failure")
+ .expect_err("a failed message must end the watch");
+ assert!(err.to_string().contains("poison message"), "{err}");
+ let commits: Vec<i64> = source
+ .commits
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|(n, _)| *n)
+ .collect();
+ assert_eq!(commits, vec![1], "committed past the failed message");
+ assert_eq!(*subscriber.delivered.lock().unwrap(), vec![0, 1]);
+ }
+
+ /// A partition whose fetch fails.
+ struct BrokenPartition;
+
+ #[crate::async_trait]
+ impl PartitionSource<(&'static str, i64)> for BrokenPartition {
+ async fn fetch(&self, _offset: i64) -> Result<Vec<(i64, (&'static str, i64))>> {
+ Err(crate::error::Error::engine("broker unreachable"))
+ }
+ async fn commit(&self, _next: i64) -> Result<()> {
+ Ok(())
+ }
+ }
+
+ // A fetch error ends the watch: the shared loop does not retry, so a
+ // source that should survive a transient broker error must retry inside
+ // its own `fetch` (Iggy's `polling_retry_interval` does; Kafka's fetch
+ // does not).
+ #[tokio::test]
+ async fn a_fetch_error_ends_the_watch() {
+ let recorder = Recorder {
+ delivered: Mutex::new(Vec::new()),
+ processed: Arc::default(),
+ ready: AtomicUsize::new(0),
+ };
+ let tails = vec![PartitionTail {
+ source: BrokenPartition,
+ start: 0,
+ high_watermark: 3,
+ }];
+ let err = tokio::time::timeout(Duration::from_secs(5), watch_partitions(tails, &recorder))
+ .await
+ .unwrap()
+ .expect_err("a fetch error must end the watch");
+ assert!(err.to_string().contains("broker unreachable"), "{err}");
+ assert_eq!(recorder.ready.load(Ordering::SeqCst), 0);
+ }
}
diff --git a/rust/sdk/cocoindex/src/resources/fs.rs b/rust/sdk/cocoindex/src/resources/fs.rs
index e6974dcb..70448e4f 100644
--- a/rust/sdk/cocoindex/src/resources/fs.rs
+++ b/rust/sdk/cocoindex/src/resources/fs.rs
@@ -260,22 +260,48 @@ mod live {
}
}
}
+ // Each key appears once in the batch, so its deletes and updates
+ // are queued together and awaited together: the engine runs the
+ // children concurrently (bounded by its admission limit) instead
+ // of one after another, which is what keeps a burst of thousands
+ // of files from taking thousands of round trips.
+ let mut handles = Vec::with_capacity(deletes.len() + updates.len());
for key in deletes {
if updates.contains_key(&key) {
continue;
}
- subscriber.delete(key.clone()).await?;
- self.known_keys().remove(&key);
+ let handle = subscriber.start_delete(key.clone()).await?;
+ handles.push((key, false, handle));
}
// Every event re-runs its file's component, as in the Python SDK:
// an equal size and mtime is not proof of equal content (a rewrite
// in the mtime's own tick keeps it), so whether the work can be
// skipped is the file memo state's decision, not the feed's.
for (key, entry) in updates {
- subscriber.update(key.clone(), entry).await?;
- self.known_keys().insert(key);
+ let handle = subscriber.start_update(key.clone(), entry).await?;
+ handles.push((key, true, handle));
}
- Ok(())
+ let results =
+ futures::future::join_all(handles.into_iter().map(
+ |(key, present, handle)| async move { (key, present, handle.ready().await) },
+ ))
+ .await;
+ let mut first_error = None;
+ let mut known = self.known_keys();
+ for (key, present, result) in results {
+ match result {
+ Ok(()) if present => {
+ known.insert(key);
+ }
+ Ok(()) => {
+ known.remove(&key);
+ }
+ Err(e) => {
+ first_error.get_or_insert(e);
+ }
+ }
+ }
+ first_error.map_or(Ok(()), Err)
}
}
diff --git a/rust/sdk/cocoindex/src/resources/live_map.rs b/rust/sdk/cocoindex/src/resources/live_map.rs
index 3d1ec2b6..e9ecfbee 100644
--- a/rust/sdk/cocoindex/src/resources/live_map.rs
+++ b/rust/sdk/cocoindex/src/resources/live_map.rs
@@ -30,6 +30,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
+use futures::StreamExt;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
@@ -268,15 +269,32 @@ impl<K: LiveMapKey, V: LiveMapValue> LiveMapFeed<K, V> for LiveMap<K, V> {
subscriber.update_all().await?;
}
let snapshot_seq = self.inner.lock().scan_seq;
- while let Some(SeqChange { seq, change }) = rx.recv().await {
- if seq <= snapshot_seq {
- continue;
- }
- match change {
- Change::Upsert(key, value) => subscriber.update(key, value).await?,
- Change::Delete(key) => subscriber.delete(key).await?,
+ // Each change is queued without waiting for the one before it: the
+ // engine runs different keys' children concurrently and coalesces a
+ // key's queued changes into its latest, so a burst is not consumed one
+ // entry at a time. A key's changes still apply in the order they were
+ // made. A failure a handler propagates ends the watch, as when each
+ // change was awaited in turn.
+ let mut in_flight = futures::stream::FuturesUnordered::new();
+ loop {
+ tokio::select! {
+ change = rx.recv() => {
+ let Some(SeqChange { seq, change }) = change else { break };
+ if seq <= snapshot_seq {
+ continue;
+ }
+ let handle = match change {
+ Change::Upsert(key, value) => subscriber.start_update(key, value).await?,
+ Change::Delete(key) => subscriber.start_delete(key).await?,
+ };
+ in_flight.push(handle.ready());
+ }
+ Some(result) = in_flight.next(), if !in_flight.is_empty() => result?,
}
}
+ while let Some(result) = in_flight.next().await {
+ result?;
+ }
Ok(())
}
}
diff --git a/rust/sdk/cocoindex/tests/fs_live_battle.rs b/rust/sdk/cocoindex/tests/fs_live_battle.rs
new file mode 100644
index 00000000..e8e49981
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/fs_live_battle.rs
@@ -0,0 +1,564 @@
+//! Adversarial live LocalFS tests (`fs_live` feature): event storms, rapid
+//! create-delete-create of one path, editor-style rename-over saves,
+//! directories moved and removed, symlinks, permission changes, a file
+//! rewritten while its component reads it, an event the watcher cannot see
+//! (caught by the periodic rescan), and the watched root itself removed.
+//!
+//! Each file's component writes `<key>` (with `/` as `__`) into an output
+//! directory through a `DirTarget`, so a test checks the end state on disk:
+//! what the pipeline wrote, updated and removed.
+//!
+//! cargo test -p cocoindex --features fs_live --test fs_live_battle
+#![cfg(feature = "fs_live")]
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cocoindex::resources::file::PatternFilePathMatcher;
+use cocoindex::resources::fs::{self, FileEntry, LiveDirWalker};
+use cocoindex::{App, UpdateHandle, UpdateOptions};
+
+/// How many times each key's component ran.
+type Runs = Arc<Mutex<BTreeMap<String, usize>>>;
+
+fn out_name(key: &str) -> String {
+ key.replace('/', "__")
+}
+
+/// The output directory's files, by name, with their content.
+fn outputs(out: &Path) -> BTreeMap<String, String> {
+ let Ok(entries) = std::fs::read_dir(out) else {
+ return BTreeMap::new();
+ };
+ entries
+ .filter_map(|e| {
+ let e = e.ok()?;
+ let content = std::fs::read_to_string(e.path()).ok()?;
+ Some((e.file_name().to_string_lossy().into_owned(), content))
+ })
+ .collect()
+}
+
+async fn wait_for(what: &str, timeout: Duration, mut pred: impl FnMut() -> bool) {
+ let deadline = Instant::now() + timeout;
+ while !pred() {
+ assert!(Instant::now() < deadline, "timed out waiting for {what}");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+async fn wait_output(out: &Path, key: &str, expected: Option<&str>) {
+ let name = out_name(key);
+ wait_for(
+ &format!("output {name} to be {expected:?}"),
+ Duration::from_secs(20),
+ || outputs(out).get(&name).map(String::as_str) == expected,
+ )
+ .await;
+}
+
+struct Fixture {
+ _dir: tempfile::TempDir,
+ root: PathBuf,
+ src: PathBuf,
+ out: PathBuf,
+ app: App,
+ runs: Runs,
+ handle: Option<UpdateHandle<()>>,
+}
+
+impl Fixture {
+ async fn new(name: &str) -> Self {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().canonicalize().unwrap();
+ let src = root.join("src");
+ let out = root.join("out");
+ std::fs::create_dir_all(&src).unwrap();
+ let app = App::builder(name)
+ .db_path(root.join(".cocoindex_db"))
+ .build()
+ .await
+ .unwrap();
+ Self {
+ _dir: dir,
+ root,
+ src,
+ out,
+ app,
+ runs: Arc::default(),
+ handle: None,
+ }
+ }
+
+ /// Start the live update. `configure` turns the recursive walker into the
+ /// live feed; `delay` is how long each component waits between reading its
+ /// file and declaring the output.
+ fn start(
+ &mut self,
+ configure: impl Fn(fs::DirWalker) -> LiveDirWalker + Send + Sync + 'static,
+ delay: Duration,
+ ) {
+ let (src, out, runs) = (self.src.clone(), self.out.clone(), self.runs.clone());
+ let handle = self
+ .app
+ .start_update_with_options(
+ UpdateOptions {
+ live: true,
+ ..UpdateOptions::default()
+ },
+ move |ctx| async move {
+ let target = fs::mount_dir_target(&ctx, out)?;
+ let feed = configure(fs::walk_dir(src).recursive(true));
+ ctx.mount_each_live(&"files", feed, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ let runs = runs.clone();
+ async move {
+ *runs.lock().unwrap().entry(file.key()).or_default() += 1;
+ let content = file.content()?;
+ if !delay.is_zero() {
+ tokio::time::sleep(delay).await;
+ }
+ target.declare_file(&ctx, &out_name(&file.key()), &content)
+ }
+ })
+ .await
+ },
+ )
+ .unwrap();
+ self.handle = Some(handle);
+ }
+
+ fn start_default(&mut self) {
+ self.start(|w| w.live().rescan_interval(None), Duration::ZERO);
+ }
+
+ fn runs_of(&self, key: &str) -> usize {
+ self.runs.lock().unwrap().get(key).copied().unwrap_or(0)
+ }
+
+ fn total_runs(&self) -> usize {
+ self.runs.lock().unwrap().values().sum()
+ }
+
+ async fn stop(mut self) {
+ let _ = tokio::time::timeout(Duration::from_secs(20), self.app.drop_state()).await;
+ if let Some(handle) = self.handle.take() {
+ let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;
+ }
+ }
+}
+
+/// Thousands of writes in one burst: 2000 new files, a hot file rewritten 200
+/// times, and 200 files the matcher excludes. Every included file ends with
+/// its content on the output side, the hot file with its last write, and the
+/// excluded ones nowhere. Coalescing keeps the hot file's runs far below its
+/// writes.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn burst_of_thousands_of_writes_converges() {
+ let mut f = Fixture::new("FsBattleStorm").await;
+ std::fs::write(f.src.join("hot.txt"), b"hot-init").unwrap();
+ f.start(
+ |w| {
+ w.path_matcher(PatternFilePathMatcher::new(["**/*.txt"], ["**/*.skip.txt"]).unwrap())
+ .live()
+ .rescan_interval(None)
+ },
+ Duration::ZERO,
+ );
+ wait_output(&f.out, "hot.txt", Some("hot-init")).await;
+
+ let started = Instant::now();
+ for i in 0..2000 {
+ std::fs::write(f.src.join(format!("n{i:04}.txt")), format!("c{i}")).unwrap();
+ if i % 10 == 0 {
+ std::fs::write(f.src.join("hot.txt"), format!("hot-{i}")).unwrap();
+ }
+ if i % 10 == 5 {
+ std::fs::write(f.src.join(format!("x{i:04}.skip.txt")), b"no").unwrap();
+ }
+ }
+ std::fs::write(f.src.join("hot.txt"), b"hot-final").unwrap();
+ let written = started.elapsed();
+
+ wait_for(
+ "every burst file processed",
+ Duration::from_secs(120),
+ || {
+ let out = outputs(&f.out);
+ out.len() == 2001 && out.get("hot.txt").map(String::as_str) == Some("hot-final")
+ },
+ )
+ .await;
+ let converged = started.elapsed();
+ eprintln!(
+ "burst: 2000 files + 201 hot writes written in {written:?}, converged in {converged:?}"
+ );
+
+ let out = outputs(&f.out);
+ for i in 0..2000 {
+ assert_eq!(out[&format!("n{i:04}.txt")], format!("c{i}"));
+ }
+ assert!(
+ !out.keys().any(|k| k.contains(".skip")),
+ "excluded file processed"
+ );
+ assert!(
+ f.runs_of("hot.txt") < 100,
+ "201 writes of one file should coalesce; it ran {} times",
+ f.runs_of("hot.txt")
+ );
+ for i in 0..2000 {
+ let key = format!("n{i:04}.txt");
+ assert!(f.runs_of(&key) <= 3, "{key} ran {} times", f.runs_of(&key));
+ }
+ f.stop().await;
+}
+
+/// One path created and deleted a hundred times in a row: the output follows
+/// the last operation, whichever it is.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rapid_create_delete_create_of_one_path() {
+ let mut f = Fixture::new("FsBattleFlip").await;
+ f.start_default();
+ wait_for("watch armed", Duration::from_secs(10), || {
+ f.handle.is_some()
+ })
+ .await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let path = f.src.join("flip.txt");
+ for i in 0..100 {
+ std::fs::write(&path, format!("v{i}")).unwrap();
+ std::fs::remove_file(&path).unwrap();
+ }
+ std::fs::write(&path, b"final").unwrap();
+ wait_output(&f.out, "flip.txt", Some("final")).await;
+
+ // Spread the flips over several debounce windows, ending in a delete.
+ for i in 0..20 {
+ std::fs::remove_file(&path).unwrap();
+ tokio::time::sleep(Duration::from_millis(30)).await;
+ std::fs::write(&path, format!("w{i}")).unwrap();
+ tokio::time::sleep(Duration::from_millis(30)).await;
+ }
+ std::fs::remove_file(&path).unwrap();
+ wait_output(&f.out, "flip.txt", None).await;
+ // And settles there.
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ assert_eq!(outputs(&f.out).get("flip.txt"), None);
+ f.stop().await;
+}
+
+/// Editor-style saves: write a temp file next to the target, then rename it
+/// over the target. The target's output follows every save, and no temp file
+/// survives on the output side, whether or not its own component ran.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rename_over_saves_leave_only_the_saved_file() {
+ let mut f = Fixture::new("FsBattleRenameOver").await;
+ std::fs::write(f.src.join("doc.txt"), b"v0").unwrap();
+ f.start_default();
+ wait_output(&f.out, "doc.txt", Some("v0")).await;
+
+ for i in 1..=20 {
+ let tmp = f.src.join(format!(".doc.txt.{i}.tmp"));
+ std::fs::write(&tmp, format!("v{i}")).unwrap();
+ // Some saves land in the same debounce window as the temp file, some
+ // after the temp file was already processed on its own.
+ if i % 2 == 0 {
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ std::fs::rename(&tmp, f.src.join("doc.txt")).unwrap();
+ }
+ wait_output(&f.out, "doc.txt", Some("v20")).await;
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ let out = outputs(&f.out);
+ assert_eq!(
+ out.keys().collect::<Vec<_>>(),
+ vec!["doc.txt"],
+ "a temp file's output survived its rename: {out:?}"
+ );
+ f.stop().await;
+}
+
+/// A directory moved in is walked; moved out, every output under it goes;
+/// a directory removed with its files likewise; a file moved between
+/// directories inside the root changes key.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn directories_moved_in_out_and_removed() {
+ let mut f = Fixture::new("FsBattleDirs").await;
+ std::fs::create_dir_all(f.src.join("keep")).unwrap();
+ std::fs::write(f.src.join("keep/k.txt"), b"k").unwrap();
+ f.start_default();
+ wait_output(&f.out, "keep/k.txt", Some("k")).await;
+
+ let staging = f.root.join("staging");
+ std::fs::create_dir_all(staging.join("deep/deeper")).unwrap();
+ std::fs::write(staging.join("a.txt"), b"A").unwrap();
+ std::fs::write(staging.join("deep/b.txt"), b"B").unwrap();
+ std::fs::write(staging.join("deep/deeper/c.txt"), b"C").unwrap();
+ std::fs::rename(&staging, f.src.join("moved")).unwrap();
+ wait_output(&f.out, "moved/deep/deeper/c.txt", Some("C")).await;
+ wait_output(&f.out, "moved/a.txt", Some("A")).await;
+ wait_output(&f.out, "moved/deep/b.txt", Some("B")).await;
+
+ // A file renamed across directories inside the root: old key gone, new
+ // key present.
+ std::fs::rename(f.src.join("moved/a.txt"), f.src.join("keep/a2.txt")).unwrap();
+ wait_output(&f.out, "keep/a2.txt", Some("A")).await;
+ wait_output(&f.out, "moved/a.txt", None).await;
+
+ // Moved out: every output under it is removed.
+ std::fs::rename(f.src.join("moved"), f.root.join("gone")).unwrap();
+ wait_output(&f.out, "moved/deep/b.txt", None).await;
+ wait_output(&f.out, "moved/deep/deeper/c.txt", None).await;
+
+ // Moved back in and then removed with its files.
+ std::fs::rename(f.root.join("gone"), f.src.join("back")).unwrap();
+ wait_output(&f.out, "back/deep/b.txt", Some("B")).await;
+ std::fs::remove_dir_all(f.src.join("back")).unwrap();
+ wait_output(&f.out, "back/deep/b.txt", None).await;
+ wait_output(&f.out, "back/deep/deeper/c.txt", None).await;
+
+ // An empty directory created and removed is nothing.
+ std::fs::create_dir(f.src.join("empty")).unwrap();
+ std::fs::remove_dir(f.src.join("empty")).unwrap();
+ tokio::time::sleep(Duration::from_millis(800)).await;
+ let out = outputs(&f.out);
+ assert_eq!(
+ out.keys().cloned().collect::<Vec<_>>(),
+ vec!["keep__a2.txt".to_string(), "keep__k.txt".to_string()],
+ "{out:?}"
+ );
+ f.stop().await;
+}
+
+/// Symlinks: a link to a file is a file with the target's content, a link to
+/// a directory is walked, a dangling link is skipped without stopping the
+/// watch, and removing a link removes its output.
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn symlinks_are_followed_and_removed() {
+ use std::os::unix::fs::symlink;
+ let mut f = Fixture::new("FsBattleSymlinks").await;
+ let outside = f.root.join("outside");
+ std::fs::create_dir_all(outside.join("d")).unwrap();
+ std::fs::write(outside.join("t.txt"), b"target").unwrap();
+ std::fs::write(outside.join("d/in_dir.txt"), b"in-dir").unwrap();
+ f.start_default();
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ symlink(outside.join("t.txt"), f.src.join("link.txt")).unwrap();
+ wait_output(&f.out, "link.txt", Some("target")).await;
+ symlink(outside.join("d"), f.src.join("linkdir")).unwrap();
+ wait_output(&f.out, "linkdir/in_dir.txt", Some("in-dir")).await;
+ symlink(f.root.join("nowhere"), f.src.join("dangling.txt")).unwrap();
+ // The watch is still alive after the dangling link.
+ std::fs::write(f.src.join("after.txt"), b"after").unwrap();
+ wait_output(&f.out, "after.txt", Some("after")).await;
+ assert_eq!(outputs(&f.out).get("dangling.txt"), None);
+
+ std::fs::remove_file(f.src.join("link.txt")).unwrap();
+ wait_output(&f.out, "link.txt", None).await;
+ std::fs::remove_file(f.src.join("linkdir")).unwrap();
+ wait_output(&f.out, "linkdir/in_dir.txt", None).await;
+ f.stop().await;
+}
+
+/// A file that becomes unreadable fails its component, which keeps its last
+/// output; once readable again, the permission change itself is an event and
+/// the file is processed again.
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn unreadable_file_keeps_output_and_recovers() {
+ use std::os::unix::fs::PermissionsExt;
+ if nix_is_root() {
+ eprintln!("skipped: permission bits do not stop root");
+ return;
+ }
+ let mut f = Fixture::new("FsBattlePerms").await;
+ let path = f.src.join("p.txt");
+ std::fs::write(&path, b"readable").unwrap();
+ f.start_default();
+ wait_output(&f.out, "p.txt", Some("readable")).await;
+
+ std::fs::write(&path, b"secret").unwrap();
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();
+ let runs_before = f.runs_of("p.txt");
+ wait_for(
+ "the unreadable file's component to run",
+ Duration::from_secs(10),
+ || f.runs_of("p.txt") > runs_before,
+ )
+ .await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(
+ outputs(&f.out).get("p.txt").map(String::as_str),
+ Some("readable"),
+ "a failed read must keep the last output"
+ );
+
+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
+ wait_output(&f.out, "p.txt", Some("secret")).await;
+ // Another file keeps flowing throughout.
+ std::fs::write(f.src.join("q.txt"), b"q").unwrap();
+ wait_output(&f.out, "q.txt", Some("q")).await;
+ f.stop().await;
+}
+
+#[cfg(unix)]
+fn nix_is_root() -> bool {
+ use std::os::unix::fs::MetadataExt;
+ // A file we create is owned by our uid.
+ let probe = tempfile::NamedTempFile::new().unwrap();
+ probe.as_file().metadata().unwrap().uid() == 0
+}
+
+/// A file rewritten while its component is between reading it and declaring
+/// its output: the component's stale result is replaced by a later run that
+/// reads the new content.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn file_rewritten_while_being_processed_ends_with_new_content() {
+ let mut f = Fixture::new("FsBattleRewriteDuringRead").await;
+ f.start(
+ |w| w.live().rescan_interval(None),
+ Duration::from_millis(400),
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let path = f.src.join("busy.txt");
+ std::fs::write(&path, b"first").unwrap();
+ wait_for("first run to start", Duration::from_secs(10), || {
+ f.runs_of("busy.txt") >= 1
+ })
+ .await;
+ // The first run has read "first" and is sleeping before it declares.
+ std::fs::write(&path, b"second").unwrap();
+ wait_output(&f.out, "busy.txt", Some("second")).await;
+ tokio::time::sleep(Duration::from_millis(1200)).await;
+ assert_eq!(
+ outputs(&f.out).get("busy.txt").map(String::as_str),
+ Some("second")
+ );
+ f.stop().await;
+}
+
+/// A write the watcher cannot see β€” through a hard link outside the watched
+/// tree, which inotify reports only for the directory of the path written β€”
+/// is caught by the periodic rescan, and only by it.
+#[cfg(target_os = "linux")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn rescan_catches_a_change_the_watcher_missed() {
+ for rescan in [None, Some(Duration::from_millis(800))] {
+ let mut f = Fixture::new(&format!("FsBattleRescan{}", rescan.is_some())).await;
+ std::fs::write(f.src.join("linked.txt"), b"v1").unwrap();
+ let alias = f.root.join("alias.txt");
+ std::fs::hard_link(f.src.join("linked.txt"), &alias).unwrap();
+ f.start(move |w| w.live().rescan_interval(rescan), Duration::ZERO);
+ wait_output(&f.out, "linked.txt", Some("v1")).await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+
+ // Rewrite in place through the alias (same inode, no new file).
+ {
+ use std::io::{Seek, Write};
+ let mut file = std::fs::OpenOptions::new()
+ .write(true)
+ .open(&alias)
+ .unwrap();
+ file.seek(std::io::SeekFrom::Start(0)).unwrap();
+ file.write_all(b"v2").unwrap();
+ }
+ match rescan {
+ None => {
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert_eq!(
+ outputs(&f.out).get("linked.txt").map(String::as_str),
+ Some("v1"),
+ "the watcher saw the aliased write, so this test proves nothing"
+ );
+ }
+ Some(_) => wait_output(&f.out, "linked.txt", Some("v2")).await,
+ }
+ f.stop().await;
+ }
+}
+
+/// The watched root removed and created again: the outputs of its files go
+/// when it goes, and its new files are processed once it is back (picked up
+/// by the rescan, since the old watch died with the directory).
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn watched_root_removed_and_recreated() {
+ let mut f = Fixture::new("FsBattleRootGone").await;
+ std::fs::write(f.src.join("a.txt"), b"a").unwrap();
+ f.start(
+ |w| w.live().rescan_interval(Some(Duration::from_millis(800))),
+ Duration::ZERO,
+ );
+ wait_output(&f.out, "a.txt", Some("a")).await;
+
+ std::fs::remove_dir_all(&f.src).unwrap();
+ wait_output(&f.out, "a.txt", None).await;
+ // Stay gone across a couple of rescans, which find no root to watch.
+ tokio::time::sleep(Duration::from_millis(2000)).await;
+
+ std::fs::create_dir_all(&f.src).unwrap();
+ std::fs::write(f.src.join("b.txt"), b"b").unwrap();
+ wait_output(&f.out, "b.txt", Some("b")).await;
+ // And the watch is live again for ordinary events.
+ std::fs::write(f.src.join("c.txt"), b"c").unwrap();
+ wait_output(&f.out, "c.txt", Some("c")).await;
+ f.stop().await;
+}
+
+/// The feed's own reads never feed back: after the catch-up and the
+/// armed-watch rescan, a quiet tree stays quiet even while every file is
+/// read repeatedly by someone else.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn reads_never_trigger_work() {
+ let mut f = Fixture::new("FsBattleQuiet").await;
+ for i in 0..50 {
+ std::fs::write(f.src.join(format!("q{i}.txt")), format!("{i}")).unwrap();
+ }
+ f.start_default();
+ wait_for("catch-up", Duration::from_secs(20), || {
+ outputs(&f.out).len() == 50
+ })
+ .await;
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ let settled = f.total_runs();
+ for _ in 0..5 {
+ for i in 0..50 {
+ let _ = std::fs::read(f.src.join(format!("q{i}.txt"))).unwrap();
+ }
+ let _ = std::fs::read_dir(&f.src).unwrap().count();
+ }
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ assert_eq!(f.total_runs(), settled, "reads triggered work");
+ f.stop().await;
+}
+
+/// The files of one burst are processed concurrently: 30 new files whose
+/// components take 300ms each land well before the nine seconds one at a
+/// time would take.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn one_burst_is_processed_concurrently() {
+ let mut f = Fixture::new("FsBattleConcurrent").await;
+ f.start(
+ |w| w.live().rescan_interval(None),
+ Duration::from_millis(300),
+ );
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let started = Instant::now();
+ for i in 0..30 {
+ std::fs::write(f.src.join(format!("c{i:02}.txt")), format!("{i}")).unwrap();
+ }
+ wait_for("the burst", Duration::from_secs(30), || {
+ outputs(&f.out).len() == 30
+ })
+ .await;
+ let took = started.elapsed();
+ assert!(
+ took < Duration::from_secs(4),
+ "30 files at 300ms each took {took:?}: processed one at a time"
+ );
+ f.stop().await;
+}
diff --git a/rust/sdk/cocoindex/tests/fs_live_restart.rs b/rust/sdk/cocoindex/tests/fs_live_restart.rs
new file mode 100644
index 00000000..64b254b1
--- /dev/null
+++ b/rust/sdk/cocoindex/tests/fs_live_restart.rs
@@ -0,0 +1,268 @@
+//! A live app killed mid-burst and started again (`fs_live` feature).
+//!
+//! The first run is a child process β€” this test binary re-run on its own
+//! `restart_child_process` entry β€” so it can be killed with SIGKILL while
+//! events are in flight, as a crash or `kill -9` would. The parent then
+//! changes the tree offline and starts the same app again on the same state
+//! db. Checks:
+//! * no lost work: the output tree ends equal to the source tree (files
+//! created in the burst the child never processed, edited, deleted and
+//! added while nothing ran are all reconciled);
+//! * no duplicated work: a file untouched since the first run reached it does
+//! not run its memoized body again;
+//! * committed live state reads back: a live component's boot counter, kept
+//! with `write_committed_state`, is read with `read_committed_state` on the
+//! next run.
+//!
+//! cargo test -p cocoindex --features fs_live --test fs_live_restart
+#![cfg(all(feature = "fs_live", unix))]
+
+use std::collections::BTreeMap;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
+
+use cocoindex::resources::fs::{self, FileEntry};
+use cocoindex::{
+ App, Ctx, LiveComponent, LiveComponentOperator, Result, UpdateOptions, async_trait,
+};
+
+const CHILD_ENV: &str = "COCO_FS_LIVE_RESTART_CHILD";
+const APP: &str = "FsLiveRestart";
+
+fn append(journal: &Path, line: &str) {
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(journal)
+ .unwrap();
+ // One write per line, so concurrent components never interleave.
+ file.write_all(format!("{line}\n").as_bytes()).unwrap();
+}
+
+fn journal_lines(journal: &Path) -> Vec<String> {
+ std::fs::read_to_string(journal)
+ .unwrap_or_default()
+ .lines()
+ .map(str::to_string)
+ .collect()
+}
+
+fn tree(dir: &Path) -> BTreeMap<String, String> {
+ let Ok(entries) = std::fs::read_dir(dir) else {
+ return BTreeMap::new();
+ };
+ entries
+ .filter_map(|e| {
+ let e = e.ok()?;
+ Some((
+ e.file_name().to_string_lossy().into_owned(),
+ std::fs::read_to_string(e.path()).ok()?,
+ ))
+ })
+ .collect()
+}
+
+/// Counts the runs of the app: reads its counter from committed live state,
+/// journals the new value and commits it.
+struct BootCounter {
+ journal: PathBuf,
+}
+
+#[async_trait]
+impl LiveComponent for BootCounter {
+ async fn process(&self, _ctx: Ctx) -> Result<()> {
+ Ok(())
+ }
+
+ async fn process_live(&self, operator: LiveComponentOperator) -> Result<()> {
+ let boots: u64 = operator.read_committed_state("boots").await?.unwrap_or(0);
+ operator
+ .write_committed_state("boots", &(boots + 1))
+ .await?;
+ append(&self.journal, &format!("boot={}", boots + 1));
+ operator.update_full().await?;
+ operator.mark_ready().await;
+ std::future::pending::<()>().await;
+ Ok(())
+ }
+}
+
+/// The app: a boot counter, then one component per source file that runs a
+/// memoized body (journaled) and writes the file's content to `out`.
+async fn start_live(root: &Path) -> (App, cocoindex::UpdateHandle<()>) {
+ let app = App::builder(APP)
+ .db_path(root.join("db"))
+ .build()
+ .await
+ .unwrap();
+ let (src, out, journal) = (root.join("src"), root.join("out"), root.join("journal"));
+ let handle = app
+ .start_update_with_options(
+ UpdateOptions {
+ live: true,
+ ..UpdateOptions::default()
+ },
+ move |ctx| async move {
+ ctx.mount_live(
+ &"boots",
+ BootCounter {
+ journal: journal.clone(),
+ },
+ )
+ .await?;
+ let target = fs::mount_dir_target(&ctx, out)?;
+ let feed = fs::walk_dir(src)
+ .live()
+ .rescan_interval(Some(Duration::from_secs(3600)));
+ ctx.mount_each_live(&"files", feed, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ let journal = journal.clone();
+ async move {
+ // Keyed by the file's path, size and mtime.
+ let content: String = ctx
+ .memo(&file, |_ctx| {
+ let file = file.clone();
+ let journal = journal.clone();
+ async move {
+ append(&journal, &format!("run={}", file.key()));
+ file.content_str()
+ }
+ })
+ .await?;
+ target.declare_file(&ctx, &file.key(), content.as_bytes())
+ }
+ })
+ .await
+ },
+ )
+ .unwrap();
+ (app, handle)
+}
+
+/// The first run, in a child process: runs live until killed.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+#[ignore = "entry point of the child process of `killed_live_app_restarts_without_lost_or_duplicated_work`"]
+async fn restart_child_process() {
+ let Ok(root) = std::env::var(CHILD_ENV) else {
+ return;
+ };
+ let (_app, _handle) = start_live(Path::new(&root)).await;
+ std::future::pending::<()>().await;
+}
+
+async fn wait_for(what: &str, timeout: Duration, mut pred: impl FnMut() -> bool) {
+ let deadline = Instant::now() + timeout;
+ while !pred() {
+ assert!(Instant::now() < deadline, "timed out waiting for {what}");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn killed_live_app_restarts_without_lost_or_duplicated_work() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().canonicalize().unwrap();
+ let (src, out, journal) = (root.join("src"), root.join("out"), root.join("journal"));
+ std::fs::create_dir_all(&src).unwrap();
+ for i in 0..20 {
+ std::fs::write(src.join(format!("base{i:02}.txt")), format!("base{i}")).unwrap();
+ }
+
+ // --- First run, killed while a burst is in flight. ---
+ let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+ .args([
+ "--exact",
+ "restart_child_process",
+ "--ignored",
+ "--nocapture",
+ ])
+ .env(CHILD_ENV, &root)
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .unwrap();
+ wait_for("the first run's catch-up", Duration::from_secs(60), || {
+ tree(&out).len() == 20
+ })
+ .await;
+ // Let the armed-watch rescan settle before the burst.
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ for i in 0..300 {
+ std::fs::write(src.join(format!("burst{i:03}.txt")), format!("burst{i}")).unwrap();
+ }
+ for i in 0..5 {
+ std::fs::write(
+ src.join(format!("base{i:02}.txt")),
+ format!("edited-live{i}"),
+ )
+ .unwrap();
+ }
+ tokio::time::sleep(Duration::from_millis(120)).await;
+ child.kill().unwrap();
+ child.wait().unwrap();
+ let processed_by_child = tree(&out).len();
+ eprintln!("the killed run had written {processed_by_child} outputs");
+
+ // --- Offline changes. ---
+ for i in 5..8 {
+ std::fs::remove_file(src.join(format!("base{i:02}.txt"))).unwrap();
+ }
+ for i in 8..10 {
+ std::fs::write(
+ src.join(format!("base{i:02}.txt")),
+ format!("edited-offline{i}"),
+ )
+ .unwrap();
+ }
+ for i in 0..3 {
+ std::fs::write(src.join(format!("offline{i}.txt")), format!("offline{i}")).unwrap();
+ }
+ let runs_before_restart = journal_lines(&journal).len();
+
+ // --- Second run, in process. ---
+ let (app, handle) = start_live(&root).await;
+ let expected = tree(&src);
+ wait_for("the restart to converge", Duration::from_secs(60), || {
+ tree(&out) == expected
+ })
+ .await;
+ // And it stays live after the restart.
+ std::fs::write(src.join("after_restart.txt"), b"live").unwrap();
+ wait_for(
+ "a live change after the restart",
+ Duration::from_secs(20),
+ || tree(&out).get("after_restart.txt").map(String::as_str) == Some("live"),
+ )
+ .await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ let lines = journal_lines(&journal);
+ let boots: Vec<&String> = lines.iter().filter(|l| l.starts_with("boot=")).collect();
+ assert_eq!(
+ boots,
+ ["boot=1", "boot=2"],
+ "committed state did not read back"
+ );
+ let reruns: Vec<&String> = lines[runs_before_restart..]
+ .iter()
+ .filter(|l| l.starts_with("run=base"))
+ .collect();
+ // base00..base04 were edited during the first run, base08/09 offline;
+ // base10..base19 were untouched since the first run processed them.
+ for line in &reruns {
+ let key = line.trim_start_matches("run=");
+ let index: usize = key
+ .trim_start_matches("base")
+ .trim_end_matches(".txt")
+ .parse()
+ .unwrap_or_else(|_| panic!("unexpected journal line {line:?}"));
+ assert!(
+ index < 5 || (8..10).contains(&index),
+ "untouched {key} ran its memoized body again after the restart: {reruns:?}"
+ );
+ }
+
+ let _ = tokio::time::timeout(Duration::from_secs(20), app.drop_state()).await;
+ let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;
+}
diff --git a/rust/sdk/cocoindex/tests/live_map.rs b/rust/sdk/cocoindex/tests/live_map.rs
index d9f8f003..1fe98201 100644
--- a/rust/sdk/cocoindex/tests/live_map.rs
+++ b/rust/sdk/cocoindex/tests/live_map.rs
@@ -282,4 +282,132 @@ mod live {
let _ = app.drop_state().await;
let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;
}
+
+ /// Consumes the map with a slow per-entry component that records each
+ /// value it processed (in order, per key) and the latest value per key.
+ struct SlowConsumer {
+ lm: LiveMap<String, String>,
+ latest: Arc<Mutex<std::collections::BTreeMap<String, String>>>,
+ runs: Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl LiveComponent for SlowConsumer {
+ async fn process(&self, ctx: Ctx) -> Result<()> {
+ let (latest, runs) = (self.latest.clone(), self.runs.clone());
+ ctx.mount_each_live(&"each", self.lm.clone(), move |_ctx, value: String| {
+ let (latest, runs) = (latest.clone(), runs.clone());
+ async move {
+ runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let (key, _) = value.split_once('=').unwrap();
+ latest
+ .lock()
+ .unwrap()
+ .insert(key.to_string(), value.clone());
+ Ok(())
+ }
+ })
+ .await
+ }
+ }
+
+ /// A burst of changes from the producer: 200 new entries at once are
+ /// consumed concurrently (the consumer takes 50ms an entry, so one at a
+ /// time would need ten seconds), and 50 rewrites of one entry end at the
+ /// last one with fewer runs than writes.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn live_map_burst_is_consumed_concurrently_and_coalesced() {
+ let dir = tempfile::tempdir().unwrap();
+ let app = App::open("live_map_burst", dir.path().join("lmdb"))
+ .await
+ .unwrap();
+ let source = Arc::new(Mutex::new(vec![("seed".to_string(), "seed=0".to_string())]));
+ let trigger = Arc::new(Notify::new());
+ let latest = Arc::new(Mutex::new(std::collections::BTreeMap::new()));
+ let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+
+ let handle = {
+ let (source, trigger, latest, runs) = (
+ source.clone(),
+ trigger.clone(),
+ latest.clone(),
+ runs.clone(),
+ );
+ app.start_update_with_options(
+ UpdateOptions {
+ live: true,
+ ..UpdateOptions::default()
+ },
+ move |ctx| async move {
+ let lm: LiveMap<String, String> = LiveMap::create(&ctx).await?;
+ ctx.mount_live(
+ &"producer",
+ Producer {
+ lm: lm.clone(),
+ source,
+ trigger,
+ },
+ )
+ .await?;
+ ctx.mount_live(&"consumer", SlowConsumer { lm, latest, runs })
+ .await
+ },
+ )
+ .unwrap()
+ };
+ type Pred = Box<dyn Fn(&std::collections::BTreeMap<String, String>) -> bool>;
+ let wait = |pred: Pred, secs: u64| {
+ let latest = latest.clone();
+ async move {
+ let deadline = std::time::Instant::now() + Duration::from_secs(secs);
+ while !pred(&latest.lock().unwrap()) {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "timed out; consumed {:?}",
+ latest.lock().unwrap().len()
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ }
+ };
+ wait(Box::new(|m| m.contains_key("seed")), 10).await;
+
+ let started = std::time::Instant::now();
+ source
+ .lock()
+ .unwrap()
+ .extend((0..200).map(|i| (format!("k{i:03}"), format!("k{i:03}=v"))));
+ trigger.notify_one();
+ wait(Box::new(|m| m.len() == 201), 30).await;
+ let took = started.elapsed();
+ eprintln!("live map: 200 entries consumed in {took:?}");
+ assert!(
+ took < Duration::from_secs(5),
+ "200 entries at 50ms each took {took:?}: consumed one at a time"
+ );
+
+ // Rewrite one entry 50 times, one producer pass each.
+ let runs_before = runs.load(std::sync::atomic::Ordering::SeqCst);
+ for i in 0..50 {
+ source.lock().unwrap()[0] = ("seed".to_string(), format!("seed={i}"));
+ trigger.notify_one();
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+ wait(
+ Box::new(|m| m.get("seed").map(String::as_str) == Some("seed=49")),
+ 30,
+ )
+ .await;
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ assert_eq!(
+ latest.lock().unwrap().get("seed").map(String::as_str),
+ Some("seed=49")
+ );
+ let seed_runs = runs.load(std::sync::atomic::Ordering::SeqCst) - runs_before;
+ eprintln!("live map: 50 rewrites of one entry ran its component {seed_runs} times");
+
+ let _ = app.drop_state().await;
+ let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;
+ }
}