diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs index 4bd05a173b..ad02d45633 100644 --- a/core/continuum-flow/src/stage.rs +++ b/core/continuum-flow/src/stage.rs @@ -7,6 +7,7 @@ use crate::Qos; use std::collections::VecDeque; use std::future::Future; use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::sync::Notify; /// What a full stage does with a new input. Signals and reliable inputs are different types @@ -35,6 +36,7 @@ pub trait Stage: Send + 'static { } struct Inbox { + producers: AtomicUsize, items: Mutex>, signal: Notify, depth: usize, @@ -45,12 +47,12 @@ struct Inbox { /// its queued inputs are handled. pub struct StageInput { inbox: Arc>, - alive: Arc<()>, } impl Clone for StageInput { fn clone(&self) -> Self { - Self { inbox: Arc::clone(&self.inbox), alive: Arc::clone(&self.alive) } + self.inbox.producers.fetch_add(1, Ordering::Relaxed); + Self { inbox: Arc::clone(&self.inbox) } } } @@ -84,7 +86,7 @@ impl StageInput { impl Drop for StageInput { fn drop(&mut self) { // The last producer gone: wake the worker so it can drain and end. - if Arc::strong_count(&self.alive) == 1 { + if self.inbox.producers.fetch_sub(1, Ordering::AcqRel) == 1 { self.inbox.signal.notify_one(); } } @@ -92,17 +94,17 @@ impl Drop for StageInput { /// Start `stage` on its own task; returns its input. pub fn spawn_stage(mut stage: S) -> StageInput { - let inbox = Arc::new(Inbox { items: Mutex::new(VecDeque::new()), signal: Notify::new(), depth: S::DEPTH.max(1), overflow: S::OVERFLOW }); - let alive = Arc::new(()); - let input = StageInput { inbox: Arc::clone(&inbox), alive: Arc::clone(&alive) }; - let watch = Arc::downgrade(&alive); - drop(alive); + let inbox = Arc::new(Inbox { producers: AtomicUsize::new(1), items: Mutex::new(VecDeque::new()), signal: Notify::new(), depth: S::DEPTH.max(1), overflow: S::OVERFLOW }); + let input = StageInput { inbox: Arc::clone(&inbox) }; tokio::spawn(async move { loop { - let next = inbox.items.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); // see push + let (next, closed) = { + let mut items = inbox.items.lock().unwrap_or_else(|e| e.into_inner()); // see push + (items.pop_front(), inbox.producers.load(Ordering::Acquire) == 0) + }; match next { Some(item) => stage.handle(item).await, - None if watch.strong_count() == 0 => return, + None if closed => return, None => inbox.signal.notified().await, } } diff --git a/core/continuum-flow/src/tests.rs b/core/continuum-flow/src/tests.rs index 908bf91862..f3cb039b24 100644 --- a/core/continuum-flow/src/tests.rs +++ b/core/continuum-flow/src/tests.rs @@ -231,3 +231,51 @@ async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newe } assert_eq!(*seen.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 3], "the newest wake is handled"); // test: plain data } + +// Last producers may close concurrently while the worker sleeps or drains accepted input. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn simultaneous_last_producers_close_and_drain_the_stage() { + use std::sync::{Arc, Barrier}; + struct Drain { + seen: Vec, + ended: Option>>, + } + impl Stage for Drain { + type Input = u32; + const QOS: Qos = Qos::Work; + const DEPTH: usize = 2; + async fn handle(&mut self, input: u32) { self.seen.push(input); } + } + impl Drop for Drain { + fn drop(&mut self) { + if let Some(ended) = self.ended.take() { + let _ = ended.send(std::mem::take(&mut self.seen)); + } + } + } + for queued in [false, true] { + let (ended, done) = tokio::sync::oneshot::channel(); + let first = spawn_stage(Drain { seen: Vec::new(), ended: Some(ended) }); + let second = first.clone(); + tokio::task::yield_now().await; + let barrier = Arc::new(Barrier::new(2)); + std::thread::scope(|scope| { + let barrier = &barrier; + scope.spawn(move || { + barrier.wait(); + if queued { assert_eq!(first.push(1), Ok(0)); } + drop(first); + }); + scope.spawn(move || { + barrier.wait(); + if queued { assert_eq!(second.push(2), Ok(0)); } + drop(second); + }); + }); + let mut seen = tokio::time::timeout(Duration::from_secs(2), done) + .await.expect("test: the closed stage must terminate") + .expect("test: stage drop reports drained input"); + seen.sort_unstable(); + assert_eq!(seen, if queued { vec![1, 2] } else { vec![] }); + } +} diff --git a/tools/scripts/tests/ci-change-scope.test.cjs b/tools/scripts/tests/ci-change-scope.test.cjs index f4d07d2dbc..25961c03cb 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -10,10 +10,10 @@ const select = (...paths) => { }; // The tested crates that do not build on the kernel: the floor (base, host, git) and pure leaves -// with no workspace dependency at all (continuum-service). A kernel or lifecycle change cannot +// with no workspace dependency at all (continuum-service and continuum-flow). A kernel or lifecycle change cannot // reach them. Kept explicit, so a crate moving in the graph fails here instead of silently // changing what CI runs. -const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service']; +const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-flow']; test('installer repairs run installer checks without unrelated Rust builds', () => { for (const file of ['install.ps1', 'tools/scripts/lib/install-common.ps1', 'tools/scripts/lib/win-modules.ps1', 'tools/scripts/lib/win-engine.ps1', 'tools/scripts/lib/windows-engine-receipt.ps1', 'tools/scripts/lib/windows-service.ps1', 'tools/scripts/lib/windows-media-reconciliation.ps1', 'tools/scripts/lib/windows-elevation.ps1', 'tools/scripts/tests/windows-process.test.ps1', 'tools/scripts/tests/windows-airc-download.test.ps1', 'tools/scripts/tests/windows-xz.test.ps1', 'tools/scripts/sync-windows-bootstrap.ps1']) @@ -116,7 +116,7 @@ test('a crate-local change runs that crate and every crate that depends on it', const aboveFloor = TESTED_CRATES.filter(n => !BELOW_KERNEL.includes(n)); assert.deepEqual(scope(['core/continuum-kernel/src/lib.rs']), { crates: aboveFloor, cli: false }); // A floor change runs the floor crate and every crate built on it. - assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => n !== 'continuum-base' && n !== 'continuum-service'), cli: true }); + assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-flow'].includes(n)), cli: true }); // continuum-git is used by hands (a citizen's git) and core (the deploy tree): both run, and every crate above hands. assert.deepEqual(scope(['core/continuum-git/src/index_lock.rs']), crates('continuum-git', 'continuum-hands', 'continuum-cognition', 'continuum-academy', 'continuum-mind', 'continuum-dreaming', 'continuum-grid', 'continuum-serving', 'continuum-core')); // Untested crates reach the tested ones through the graph: llama -> engine -> ...