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
test(rust-sdk): wait on events, not time, in OCI live and admission tests (#2761)
Jiangzhoue00c47ffb539
diff --git a/rust/sdk/cocoindex/tests/admission.rs b/rust/sdk/cocoindex/tests/admission.rsindex 1f07165f..c092ae49 100644--- a/rust/sdk/cocoindex/tests/admission.rs+++ b/rust/sdk/cocoindex/tests/admission.rs@@ -6,7 +6,7 @@mod admission_common;-use admission_common::count_admitted;+use admission_common::assert_admits;use cocoindex::Environment;#[tokio::test]@@ -20,7 +20,7 @@ async fn default_limit_is_1024_components() {.app("admission_default").await.unwrap();- assert_eq!(count_admitted(&app, 1030).await, 1024);+ assert_admits(&app, 1024, 1030).await;}#[tokio::test]@@ -35,5 +35,5 @@ async fn builder_limit_bounds_components() {.app("admission_builder").await.unwrap();- assert_eq!(count_admitted(&app, 10).await, 3);+ assert_admits(&app, 3, 10).await;}diff --git a/rust/sdk/cocoindex/tests/admission_common/mod.rs b/rust/sdk/cocoindex/tests/admission_common/mod.rsindex 57281bad..67b4a8df 100644--- a/rust/sdk/cocoindex/tests/admission_common/mod.rs+++ b/rust/sdk/cocoindex/tests/admission_common/mod.rs@@ -1,60 +1,103 @@//! Shared by `admission.rs` and `admission_env.rs`.use std::sync::Arc;-use std::sync::atomic::{AtomicUsize, Ordering};-use std::time::{Duration, Instant};+use std::time::Duration;use cocoindex::App;-use tokio::sync::Semaphore;+use tokio::sync::{Semaphore, watch};-/// Mount `children` background components that block until released and-/// return how many of them were running once the count stopped growing:-/// the app's limit, when `children` exceeds it.-pub async fn count_admitted(app: &App, children: usize) -> usize {- let started = Arc::new(AtomicUsize::new(0));+/// How far the children of [`assert_admits`] have got.+#[derive(Clone, Copy, Debug, Default)]+struct Progress {+ /// Children the parent has taken from its source. `mount_each` takes the+ /// next one only once the previous one is admitted.+ taken: usize,+ /// Children whose body has started.+ started: usize,+ /// Children whose body has passed the gate.+ finished: usize,+ /// The most children in their body at any one time+ /// (`started - finished`).+ peak_running: usize,+}++/// A bound on the wait for `limit` children to run at once: it only turns a+/// limit that is too small from a hang into a failure, so it is generous.+const LIMIT_WAIT: Duration = Duration::from_secs(120);++/// Mount `children` background components, more than `limit`, that block+/// until released, and assert that exactly `limit` of them run at once.+///+/// The children are released once `limit` of them run and the parent has+/// taken one more, whose mount then waits for a token. Both are events, so a+/// stalled machine delays them but cannot make the test see a lower limit.+/// While no child is released, a correct pool admits none past the limit:+/// one more shows as a child taken or started too many at that point, and+/// later as a peak above `limit`.+pub async fn assert_admits(app: &App, limit: usize, children: usize) {+ assert!(children > limit, "the children must outnumber the limit");+ let (progress, mut observed) = watch::channel(Progress::default());let gate = Arc::new(Semaphore::new(0));- let admitted = Arc::new(AtomicUsize::new(0));let observer = tokio::spawn({- let (started, gate, admitted) = (started.clone(), gate.clone(), admitted.clone());+ let gate = gate.clone();async move {- let mut last = usize::MAX;- let mut stable_since = Instant::now();- loop {- tokio::time::sleep(Duration::from_millis(20)).await;- let now = started.load(Ordering::SeqCst);- if now != last {- last = now;- stable_since = Instant::now();- } else if now > 0 && stable_since.elapsed() > Duration::from_millis(500) {- break;- }- }- admitted.store(started.load(Ordering::SeqCst), Ordering::SeqCst);+ let at_limit = tokio::time::timeout(LIMIT_WAIT, async {+ observed+ .wait_for(|p| p.started >= limit && p.taken > limit)+ .await+ .map(|p| *p)+ })+ .await;+ let at_limit = match at_limit {+ Ok(at_limit) => Ok(at_limit.unwrap()),+ Err(_) => Err(*observed.borrow()),+ };gate.add_permits(children);+ at_limit}});- let (started_outer, gate_outer) = (started.clone(), gate.clone());+ let (take, run) = (progress.clone(), progress.clone());app.update(move |ctx| async move {let handle = ctx- .mount_each(0..children, |i| *i as i64, {+ .mount_each(+ 0..children,+ move |i| {+ take.send_modify(|p| p.taken += 1);+ *i as i64+ },move |_child, _i| {- let (started, gate) = (started_outer.clone(), gate_outer.clone());+ let (progress, gate) = (run.clone(), gate.clone());async move {- started.fetch_add(1, Ordering::SeqCst);+ progress.send_modify(|p| {+ p.started += 1;+ p.peak_running = p.peak_running.max(p.started - p.finished);+ });let _permit = gate.acquire().await.unwrap();+ progress.send_modify(|p| p.finished += 1);Ok(())}- }- })+ },+ ).await?;handle.ready().await?;Ok(())}).await.unwrap();- observer.await.unwrap();- assert_eq!(started.load(Ordering::SeqCst), children);- admitted.load(Ordering::SeqCst)++ let at_limit = match observer.await.unwrap() {+ Ok(at_limit) => at_limit,+ Err(stuck) => panic!("{limit} children never ran at once: {stuck:?}"),+ };+ assert_eq!(+ (at_limit.started, at_limit.taken),+ (limit, limit + 1),+ "with {limit} children running and none released, the next one waits \+ for a token: {at_limit:?}"+ );+ let end = *progress.borrow();+ assert_eq!(end.started, children, "{end:?}");+ assert_eq!(end.peak_running, limit, "{end:?}");}diff --git a/rust/sdk/cocoindex/tests/admission_env.rs b/rust/sdk/cocoindex/tests/admission_env.rsindex fd4dbe1f..094d475e 100644--- a/rust/sdk/cocoindex/tests/admission_env.rs+++ b/rust/sdk/cocoindex/tests/admission_env.rs@@ -6,7 +6,7 @@mod admission_common;-use admission_common::count_admitted;+use admission_common::assert_admits;use cocoindex::Environment;#[tokio::test]@@ -31,7 +31,7 @@ async fn environment_variable_sets_the_limit() {unsafe { std::env::set_var("COCOINDEX_MAX_INFLIGHT_COMPONENTS", "5") };let app = env.app("admission_env").await.unwrap();- assert_eq!(count_admitted(&app, 12).await, 5);+ assert_admits(&app, 5, 12).await;// The builder's value wins over the variable.let dir = tempfile::tempdir().unwrap();@@ -44,5 +44,5 @@ async fn environment_variable_sets_the_limit() {.app("admission_env_builder").await.unwrap();- assert_eq!(count_admitted(&app, 12).await, 2);+ assert_admits(&app, 2, 12).await;}diff --git a/rust/sdk/cocoindex/tests/oci_live.rs b/rust/sdk/cocoindex/tests/oci_live.rsindex 0bff632f..ba0c4b49 100644--- a/rust/sdk/cocoindex/tests/oci_live.rs+++ b/rust/sdk/cocoindex/tests/oci_live.rs@@ -31,21 +31,23 @@ use cocoindex::{use rsa::RsaPrivateKey;use rsa::pkcs8::{EncodePrivateKey, LineEnding};use serde_json::json;+use tokio::sync::watch;use wiremock::matchers::{header, method, path};use wiremock::{Mock, MockServer, Request, ResponseTemplate};/// A finite in-memory `LiveStream<Vec<u8>>` of event payloads. It records, per-/// event, whether the view acknowledged it (awaited the handle `send`-/// returned), then waits until cancelled, as a topic would.+/// event, whether the view acknowledged it (the handle `send` returned became+/// ready), then waits until cancelled, as a topic would. A test subscribes to+/// `acked` to wait for the acknowledgements it expects.#[derive(Clone)]struct EventStream {events: Vec<Vec<u8>>,- acked: Arc<Mutex<Vec<bool>>>,+ acked: watch::Sender<Vec<bool>>,}impl EventStream {fn new(events: Vec<Vec<u8>>) -> Self {- let acked = Arc::new(Mutex::new(vec![false; events.len()]));+ let (acked, _) = watch::channel(vec![false; events.len()]);Self { events, acked }}}@@ -56,7 +58,7 @@ impl LiveStream<Vec<u8>> for EventStream {for (i, event) in self.events.iter().enumerate() {let handle = subscriber.send(event.clone()).await?;handle.ready().await?;- self.acked.lock().unwrap()[i] = true;+ self.acked.send_modify(|acked| acked[i] = true);}subscriber.mark_ready().await;std::future::pending::<()>().await;@@ -175,7 +177,7 @@ async fn oci_live_view_scan_then_events() -> Result<()> {];let events = EventStream::new(events);- let acked = events.acked.clone();+ let mut acked = events.acked.subscribe();let processed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));let app = App::builder("OciLive").db_path(tmp.path().join("db"))@@ -220,21 +222,26 @@ async fn oci_live_view_scan_then_events() -> Result<()> {).unwrap();- // Wait until the scan item and the live create are both processed.- let deadline = Instant::now() + Duration::from_secs(20);- loop {- {- let got = processed.lock().unwrap();- if got.iter().any(|k| k == "a.txt") && got.iter().any(|k| k == "new.txt") {- break;- }- }- if Instant::now() > deadline {- let got = processed.lock().unwrap().clone();- panic!("live view did not process scan + create event in time; got={got:?}");- }- tokio::time::sleep(Duration::from_millis(100)).await;- }+ // Wait until the stream has every event acknowledged, before stopping the+ // run. The scan has synced before the watch starts, and an event is+ // acknowledged once the update or delete it caused has synced, so this+ // also covers both objects. Seeing `new.txt` processed is not enough: its+ // sync and the later events can still be in flight, and stopping the run+ // cancels them, which leaves them unacknowledged.+ let all_acked = matches!(+ tokio::time::timeout(+ Duration::from_secs(20),+ acked.wait_for(|acked| acked.iter().all(|&a| a)),+ )+ .await,+ Ok(Ok(_))+ );+ assert!(+ all_acked,+ "every event, handled or dropped, is acknowledged to the stream; acked={:?}, processed={:?}",+ *acked.borrow(),+ processed.lock().unwrap(),+ );let _ = app.drop_state().await;let _ = tokio::time::timeout(Duration::from_secs(10), handle.result()).await;@@ -248,11 +255,6 @@ async fn oci_live_view_scan_then_events() -> Result<()> {"only the scanned object and the in-window create event should be processed \(old/cross-bucket/malformed dropped, delete is a no-op)");- assert_eq!(- acked.lock().unwrap().clone(),- vec![true; 5],- "every event, handled or dropped, is acknowledged to the stream"- );Ok(())}