Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions core/continuum-flow/src/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -35,6 +36,7 @@ pub trait Stage: Send + 'static {
}

struct Inbox<T> {
producers: AtomicUsize,
items: Mutex<VecDeque<T>>,
signal: Notify,
depth: usize,
Expand All @@ -45,12 +47,12 @@ struct Inbox<T> {
/// its queued inputs are handled.
pub struct StageInput<T> {
inbox: Arc<Inbox<T>>,
alive: Arc<()>,
}

impl<T> Clone for StageInput<T> {
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) }
}
}

Expand Down Expand Up @@ -84,25 +86,25 @@ impl<T> StageInput<T> {
impl<T> Drop for StageInput<T> {
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();
}
}
}

/// Start `stage` on its own task; returns its input.
pub fn spawn_stage<S: Stage>(mut stage: S) -> StageInput<S::Input> {
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,
}
}
Expand Down
48 changes: 48 additions & 0 deletions core/continuum-flow/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u32>,
ended: Option<tokio::sync::oneshot::Sender<Vec<u32>>>,
}
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![] });
}
}
6 changes: 3 additions & 3 deletions tools/scripts/tests/ci-change-scope.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down Expand Up @@ -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 -> ...
Expand Down
Loading