From 9a974629f6b893630ff3b639604d72849be80b82 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 09:07:43 -0500 Subject: [PATCH 1/7] continuum-flow: QoS classes, a coalescing serial queue per owner, one event-driven dispatcher per capacity (draft, untested) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SERVING-ENGINE §1c. Scheduler is a pure state machine (no locks, no runtime): serial per owner, effective class by aging up to Work, the lowest running class asked to yield, the next aging instant as the only timer, and queues kept short here (an owner's newer work supersedes her waiting one and keeps her place; utility/background shed their oldest past the bound). Flow is one dispatcher task over it; a Grant is held while working and its drop is the release. Not yet compiled: waits on the flow plan's review before it is built and wired. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.toml | 1 + core/continuum-flow/Cargo.toml | 8 ++ core/continuum-flow/src/flow.rs | 168 ++++++++++++++++++++++++ core/continuum-flow/src/lib.rs | 29 ++++ core/continuum-flow/src/qos.rs | 24 ++++ core/continuum-flow/src/scheduler.rs | 189 +++++++++++++++++++++++++++ core/continuum-flow/src/tests.rs | 180 +++++++++++++++++++++++++ 7 files changed, 599 insertions(+) create mode 100644 core/continuum-flow/Cargo.toml create mode 100644 core/continuum-flow/src/flow.rs create mode 100644 core/continuum-flow/src/lib.rs create mode 100644 core/continuum-flow/src/qos.rs create mode 100644 core/continuum-flow/src/scheduler.rs create mode 100644 core/continuum-flow/src/tests.rs diff --git a/Cargo.toml b/Cargo.toml index efecf7e65f..cecaec185a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ members = [ "core/continuum-cli-lifecycle", "core/continuum-tool-protocol", "core/continuum-base", + "core/continuum-flow", "core/continuum-git", "core/continuum-host", "core/continuum-context", diff --git a/core/continuum-flow/Cargo.toml b/core/continuum-flow/Cargo.toml new file mode 100644 index 0000000000..0907023d21 --- /dev/null +++ b/core/continuum-flow/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "continuum-flow" +version = "0.1.0" +edition = "2021" +description = "Work flows through queues, never locks: quality-of-service classes, a serial queue per owner, and one event-driven dispatcher per capacity that owns its ready heap, ages waiting work so nothing starves, and asks lower classes to yield. SERVING-ENGINE §1c." + +[dependencies] +tokio = { workspace = true } diff --git a/core/continuum-flow/src/flow.rs b/core/continuum-flow/src/flow.rs new file mode 100644 index 0000000000..9b8521d936 --- /dev/null +++ b/core/continuum-flow/src/flow.rs @@ -0,0 +1,168 @@ +//! The dispatcher: one task owns the scheduler and wakes only on events (a submission, a release, +//! a resize) or the next aging instant. Callers hold no lock while they wait or while they work: +//! `submit` returns a grant when the scheduler starts it; dropping the grant (or an unstarted +//! submission) is the release event. + +use crate::scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; +use crate::Qos; +use std::collections::HashMap; +use std::hash::Hash; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::time::Instant; + +enum Event { + Submit { ticket: Ticket, owner: K, qos: Qos, start: oneshot::Sender, Dropped>> }, + Release(Ticket), + Resize(usize), +} + +/// A handle to one capacity's dispatcher. Cheap to clone; every clone feeds the same queue. +pub struct Flow { + events: mpsc::UnboundedSender>, + tickets: Arc, +} + +impl Clone for Flow { + fn clone(&self) -> Self { + Self { events: self.events.clone(), tickets: Arc::clone(&self.tickets) } + } +} + +/// Why a submission did not start. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refused { + /// It left the queue without running (see [`Dropped`]). + Dropped(Dropped), + /// The dispatcher has stopped. + Stopped, +} + +/// Permission to use one unit of capacity, held while working. Dropping it frees the unit. +pub struct Grant { + ticket: Ticket, + events: Box, + yield_asked: watch::Receiver, +} + +impl Grant { + /// Resolves when a higher class is waiting and nothing is free: yield at the next safe + /// point (for a sequence, a decode-step boundary) by dropping this grant. + pub async fn yield_requested(&mut self) { + while !*self.yield_asked.borrow_and_update() { + if self.yield_asked.changed().await.is_err() { + return std::future::pending().await; + } + } + } + + pub fn yield_is_requested(&self) -> bool { + *self.yield_asked.borrow() + } +} + +impl Drop for Grant { + fn drop(&mut self) { + (self.events)(self.ticket); + } +} + +/// Releases an unstarted submission if its caller stops waiting. +struct Pending { + ticket: Ticket, + events: mpsc::UnboundedSender>, + armed: bool, +} + +impl Drop for Pending { + fn drop(&mut self) { + if self.armed { + let _ = self.events.send(Event::Release(self.ticket)); // a stopped dispatcher has nothing to release + } + } +} + +impl Flow { + /// Start the dispatcher for a capacity of `capacity` units. + pub fn spawn(capacity: usize, aging: Aging) -> Self { + let (events, inbox) = mpsc::unbounded_channel(); + tokio::spawn(dispatch(Scheduler::new(capacity, aging), inbox)); + Self { events, tickets: Arc::new(AtomicU64::new(0)) } + } + + /// Queue work for `owner` at `qos`; resolves when it may start, or at once with why it left + /// the queue without running (`Refused::Dropped`: superseded by the owner's newer work, or + /// shed from a full utility/background queue), or `Refused::Stopped` if the dispatcher has. + pub async fn submit(&self, owner: K, qos: Qos) -> Result { + let ticket = Ticket(self.tickets.fetch_add(1, Ordering::Relaxed)); + let (start, started) = oneshot::channel(); + self.events.send(Event::Submit { ticket, owner, qos, start }).map_err(|_| Refused::Stopped)?; + let mut pending = Pending { ticket, events: self.events.clone(), armed: true }; + let outcome = started.await.map_err(|_| Refused::Stopped)?; + pending.armed = false; + let yield_asked = outcome.map_err(Refused::Dropped)?; + let events = self.events.clone(); + Ok(Grant { + ticket, + events: Box::new(move |t| { + let _ = events.send(Event::Release(t)); // a stopped dispatcher has nothing to release + }), + yield_asked, + }) + } + + /// The capacity changed (an engine relaunched with another slot count). + pub fn resize(&self, capacity: usize) { + let _ = self.events.send(Event::Resize(capacity)); // a stopped dispatcher has no capacity + } +} + +async fn dispatch(mut scheduler: Scheduler, mut inbox: mpsc::UnboundedReceiver>) { + let mut starting: HashMap>> = HashMap::new(); + let mut yielding: HashMap> = HashMap::new(); + loop { + let now = Instant::now(); + for decision in scheduler.decide(now.into_std()) { + match decision { + Decision::Run(ticket) => { + let (asked, yield_asked) = watch::channel(false); + match starting.remove(&ticket).map(|start| start.send(Ok(yield_asked))) { + Some(Ok(())) => { + yielding.insert(ticket, asked); + } + // the submitter stopped waiting before its start: free the unit again + _ => scheduler.release(ticket), + } + } + Decision::Yield(ticket) => { + if let Some(asked) = yielding.get(&ticket) { + let _ = asked.send(true); // a grant already dropped has yielded + } + } + } + } + let wake = scheduler.next_wakeup(now.into_std()).map(Instant::from_std); + let event = tokio::select! { + event = inbox.recv() => event, + () = async { match wake { Some(at) => tokio::time::sleep_until(at).await, None => std::future::pending().await } } => continue, + }; + match event { + None => return, + Some(Event::Submit { ticket, owner, qos, start }) => { + starting.insert(ticket, start); + for (gone, why) in scheduler.submit(ticket, owner, qos, now.into_std()) { + if let Some(start) = starting.remove(&gone) { + let _ = start.send(Err(why)); // a submitter that stopped waiting needs no reason + } + } + } + Some(Event::Release(ticket)) => { + starting.remove(&ticket); + yielding.remove(&ticket); + scheduler.release(ticket); + } + Some(Event::Resize(capacity)) => scheduler.resize(capacity), + } + } +} diff --git a/core/continuum-flow/src/lib.rs b/core/continuum-flow/src/lib.rs new file mode 100644 index 0000000000..001b56b1f1 --- /dev/null +++ b/core/continuum-flow/src/lib.rs @@ -0,0 +1,29 @@ +//! Work flows through queues, never locks (SERVING-ENGINE §1c; Joel, 2026-10-28: "Its got to +//! flow or have MANY queues"; "Semaphore really only exists for queue inserts and signals"). +//! +//! - Every unit of work has a quality-of-service class ([`Qos`]): interactive, work, utility, +//! background. A higher class never waits behind a lower one. +//! - Each owner (a mind) is a serial queue: one unit of its work runs at a time. +//! - One dispatcher per capacity (an engine's slots) owns the ready set and starts work only when +//! a unit frees. It wakes on events and on the next aging instant, never by polling. +//! - Waiting work ages one class at a time up to `Work`, so a dream still runs, irregularly and +//! in the gaps, and never passes a directed reply. +//! - When a higher class waits and nothing is free, the lowest running class is asked to yield at +//! its next safe point (`Grant::yield_requested`); for a sequence, a page-out at a decode-step +//! boundary. +//! - Queues stay short, owned here and not by callers: an owner keeps one waiting unit (her +//! newer work supersedes the older and keeps its place); utility and background queues are +//! bounded and shed their oldest. A long queue gives every request everyone's latency. +//! - Nobody holds a lock while waiting or working: a grant is a capability whose drop is the +//! release event. + +mod flow; +mod qos; +mod scheduler; + +pub use flow::{Flow, Grant, Refused}; +pub use qos::Qos; +pub use scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; + +#[cfg(test)] +mod tests; diff --git a/core/continuum-flow/src/qos.rs b/core/continuum-flow/src/qos.rs new file mode 100644 index 0000000000..ea0865e65b --- /dev/null +++ b/core/continuum-flow/src/qos.rs @@ -0,0 +1,24 @@ +//! Quality-of-service classes, highest first (GCD's model: a few classes, any number of queues). + +/// What a unit of work is, which decides when it runs. A higher class never waits behind a +/// lower one; a lower one still runs, in the gaps, and ages upward so it is never starved. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Qos { + /// Work nobody waits on now: dreams, training, consolidation. + Background = 0, + /// Work that fills what the classes above leave: ambient thought, perception, exams. + Utility = 1, + /// An owner's own work in progress: a resident's act on her card. + Work = 2, + /// Someone is waiting on the answer: a directed reply. + Interactive = 3, +} + +impl Qos { + /// Every class, highest first. + pub const ALL: [Qos; 4] = [Qos::Interactive, Qos::Work, Qos::Utility, Qos::Background]; + + pub(crate) fn rank(self) -> u32 { + self as u32 + } +} diff --git a/core/continuum-flow/src/scheduler.rs b/core/continuum-flow/src/scheduler.rs new file mode 100644 index 0000000000..6193c9fd03 --- /dev/null +++ b/core/continuum-flow/src/scheduler.rs @@ -0,0 +1,189 @@ +//! The scheduler's decisions as a pure state machine: no locks, no runtime, time passed in. The +//! dispatcher (`flow.rs`) turns events into these calls; a validator replays them in microseconds. + +use crate::Qos; +use std::collections::{HashMap, HashSet}; +use std::hash::Hash; +use std::time::{Duration, Instant}; + +/// One unit of work's identity, unique per scheduler. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct Ticket(pub u64); + +/// What the dispatcher must do after an event. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + /// Start this waiting ticket: capacity is free and it is the best eligible. + Run(Ticket), + /// Ask this running ticket to yield at its next safe point: a higher class is waiting and + /// nothing is free. Asked once per ticket. + Yield(Ticket), +} + +/// How long work of each class waits before it is treated as one class higher (never above +/// `Work`, so aged work never preempts and never passes a directed reply). Measured per +/// deployment; indexed by `Qos as usize`. +#[derive(Debug, Clone, Copy)] +pub struct Aging(pub [Duration; 4]); + +struct Waiting { + owner: K, + qos: Qos, + since: Instant, +} + +struct Running { + owner: K, + qos: Qos, + yield_asked: bool, +} + +/// Why a waiting ticket left without running. The flow, not each caller, keeps queues short: +/// a long queue gives every request everyone's latency and answers stale questions. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dropped { + /// The same owner submitted newer work: a mind's fresher thought replaces her waiting one. + Superseded, + /// A utility or background queue passed its bound: the oldest waiting is shed. + Shed, +} + +pub struct Scheduler { + capacity: usize, + aging: Aging, + waiting: HashMap>, + running: HashMap>, + busy_owners: HashSet, +} + +impl Scheduler { + pub fn new(capacity: usize, aging: Aging) -> Self { + Self { capacity, aging, waiting: HashMap::new(), running: HashMap::new(), busy_owners: HashSet::new() } + } + + /// Queue `ticket`, returning the tickets that leave the queue because of it. An owner keeps + /// at most one waiting ticket (the newer supersedes the older, keeping the higher class); + /// utility and background keep at most `capacity` waiting each, shedding the oldest. + /// Interactive and work are bounded by the owners themselves and never shed. + pub fn submit(&mut self, ticket: Ticket, owner: K, qos: Qos, now: Instant) -> Vec<(Ticket, Dropped)> { + let mut dropped = Vec::new(); + // The newer work keeps the owner's place in line and the higher of the two classes. + let (mut qos, mut since) = (qos, now); + let older: Vec = self.waiting.iter().filter(|(_, w)| w.owner == owner).map(|(t, _)| *t).collect(); + for t in older { + if let Some(w) = self.waiting.remove(&t) { + qos = qos.max(w.qos); + since = since.min(w.since); + dropped.push((t, Dropped::Superseded)); + } + } + self.waiting.insert(ticket, Waiting { owner, qos, since }); + if qos <= Qos::Utility { + let bound = self.capacity.max(1); + let mut same: Vec<(Instant, Ticket)> = + self.waiting.iter().filter(|(_, w)| w.qos == qos).map(|(t, w)| (w.since, *t)).collect(); + if same.len() > bound { + same.sort(); + let excess = same.len() - bound; + for (_, t) in same.into_iter().take(excess) { + self.waiting.remove(&t); + dropped.push((t, Dropped::Shed)); + } + } + } + dropped + } + + /// A running ticket finished, or a waiting one was cancelled. Unknown tickets are ignored: + /// a release can race the decision that would have started it. + pub fn release(&mut self, ticket: Ticket) { + self.waiting.remove(&ticket); + if let Some(done) = self.running.remove(&ticket) { + self.busy_owners.remove(&done.owner); + } + } + + /// Capacity follows the resource (an engine's slots after a relaunch). Shrinking never + /// interrupts running work; it only stops new starts until enough finish. + pub fn resize(&mut self, capacity: usize) { + self.capacity = capacity; + } + + /// The class a waiting ticket competes as now: its own, raised one class per aging step, + /// never above `Work`. + fn effective(&self, w: &Waiting, now: Instant) -> u32 { + let step = self.aging.0[w.qos as usize]; + let raised = if step.is_zero() { 0 } else { (now.saturating_duration_since(w.since).as_nanos() / step.as_nanos()) as u32 }; + let ceiling = Qos::Work.rank().max(w.qos.rank()); + (w.qos.rank() + raised).min(ceiling) + } + + /// The best waiting ticket whose owner has nothing running (each owner is a serial queue): + /// highest effective class, then oldest, then lowest ticket. + fn best_eligible(&self, now: Instant) -> Option { + self.waiting + .iter() + .filter(|(_, w)| !self.busy_owners.contains(&w.owner)) + .max_by(|(ta, a), (tb, b)| { + self.effective(a, now) + .cmp(&self.effective(b, now)) + .then(b.since.cmp(&a.since)) + .then(tb.cmp(ta)) + }) + .map(|(t, _)| *t) + } + + /// Everything to do now: start the best eligible work while capacity is free, then, if a + /// higher class still waits, ask the lowest running class to yield. + pub fn decide(&mut self, now: Instant) -> Vec { + let mut out = Vec::new(); + while self.running.len() < self.capacity { + let Some(ticket) = self.best_eligible(now) else { break }; + let Some(w) = self.waiting.remove(&ticket) else { break }; + self.busy_owners.insert(w.owner.clone()); + self.running.insert(ticket, Running { owner: w.owner, qos: w.qos, yield_asked: false }); + out.push(Decision::Run(ticket)); + } + if let Some(best) = self.best_eligible(now) { + let wanted = self.waiting.get(&best).map(|w| w.qos); + let victim = self + .running + .iter() + .filter(|(_, r)| !r.yield_asked && wanted.is_some_and(|q| q > r.qos)) + .min_by_key(|(t, r)| (r.qos, std::cmp::Reverse(**t))) + .map(|(t, _)| *t); + if let Some(t) = victim { + if let Some(r) = self.running.get_mut(&t) { + r.yield_asked = true; + } + out.push(Decision::Yield(t)); + } + } + out + } + + /// When the next waiting ticket rises a class: the dispatcher's only timer, so it sleeps + /// until an event or this instant and never polls. + pub fn next_wakeup(&self, now: Instant) -> Option { + self.waiting + .values() + .filter(|w| self.effective(w, now) < Qos::Work.rank().max(w.qos.rank())) + .filter_map(|w| { + let step = self.aging.0[w.qos as usize]; + if step.is_zero() { + return None; + } + let steps = (now.saturating_duration_since(w.since).as_nanos() / step.as_nanos()) as u32 + 1; + Some(w.since + step * steps) + }) + .min() + } + + pub fn running(&self) -> usize { + self.running.len() + } + + pub fn waiting(&self) -> usize { + self.waiting.len() + } +} diff --git a/core/continuum-flow/src/tests.rs b/core/continuum-flow/src/tests.rs new file mode 100644 index 0000000000..26169dc69e --- /dev/null +++ b/core/continuum-flow/src/tests.rs @@ -0,0 +1,180 @@ +#![cfg(test)] +//! The rules the flow keeps, as a validator that runs in milliseconds (SERVING-ENGINE §1c). +use super::*; +use std::time::{Duration, Instant}; + +fn aging() -> Aging { + // Background rises a class every 10 s, utility every 5 s; work and interactive do not age. + Aging([Duration::from_secs(10), Duration::from_secs(5), Duration::ZERO, Duration::ZERO]) +} + +fn at(base: Instant, secs: u64) -> Instant { + base + Duration::from_secs(secs) +} + +// what this catches: a directed reply waiting behind four residents' acts. It is not queued +// behind them: the lowest running work is asked to yield at once, and the reply starts on release. +#[test] +fn a_directed_reply_asks_the_lowest_work_to_yield_and_starts_on_release() { + let t0 = Instant::now(); + let mut s = Scheduler::new(4, aging()); + for (i, mind) in ["aiko", "aris", "atlas", "benchy"].into_iter().enumerate() { + s.submit(Ticket(i as u64), mind, Qos::Work, t0); + } + assert_eq!(s.decide(t0).len(), 4); + s.submit(Ticket(9), "joel-asked-aiko", Qos::Interactive, at(t0, 1)); + let asked = s.decide(at(t0, 1)); + assert_eq!(asked, vec![Decision::Yield(Ticket(3))], "the newest-started work yields first"); + assert!(s.decide(at(t0, 1)).is_empty(), "asked once, not every event"); + s.release(Ticket(3)); + assert_eq!(s.decide(at(t0, 1)), vec![Decision::Run(Ticket(9))]); +} + +// what this catches: background work taking a free slot ahead of a resident's act. +#[test] +fn work_never_waits_behind_a_dream() { + let t0 = Instant::now(); + let mut s = Scheduler::new(1, aging()); + s.submit(Ticket(1), "dream", Qos::Background, t0); + s.submit(Ticket(2), "aiko", Qos::Work, at(t0, 1)); + assert_eq!(s.decide(at(t0, 1)), vec![Decision::Run(Ticket(2))]); +} + +// what this catches: a dream starved forever on a busy node. It ages to `Work`, then wins on +// age the next time a slot frees: it runs irregularly, and it never preempts work to do so. +#[test] +fn a_dream_still_runs_on_a_busy_node_without_preempting_work() { + let t0 = Instant::now(); + let mut s = Scheduler::new(1, aging()); + s.submit(Ticket(1), "dream", Qos::Background, t0); + s.submit(Ticket(2), "aiko", Qos::Work, t0); + assert_eq!(s.decide(t0), vec![Decision::Run(Ticket(2))]); + s.submit(Ticket(3), "aris", Qos::Work, at(t0, 25)); + assert!(s.decide(at(t0, 25)).is_empty(), "an aged dream never asks work to yield"); + s.release(Ticket(2)); + assert_eq!(s.decide(at(t0, 25)), vec![Decision::Run(Ticket(1))], "aged to work, and older than aris"); + s.release(Ticket(1)); + assert_eq!(s.decide(at(t0, 26)), vec![Decision::Run(Ticket(3))]); +} + +// what this catches: an aged ticket passing a directed reply or preempting anyone. +#[test] +fn aging_stops_at_work() { + let t0 = Instant::now(); + let mut s = Scheduler::new(1, aging()); + s.submit(Ticket(1), "dream", Qos::Background, t0); + s.submit(Ticket(2), "aiko", Qos::Interactive, at(t0, 1000)); + assert_eq!(s.decide(at(t0, 1000)), vec![Decision::Run(Ticket(2))]); +} + +// what this catches: one mind running two acts at once (each owner is a serial queue), and a +// free slot left idle while another owner's work waits. +#[test] +fn an_owner_runs_one_unit_at_a_time_and_others_fill_the_rest() { + let t0 = Instant::now(); + let mut s = Scheduler::new(3, aging()); + s.submit(Ticket(1), "aiko", Qos::Work, t0); + s.submit(Ticket(3), "aris", Qos::Utility, t0); + assert_eq!(s.decide(t0).len(), 2); + s.submit(Ticket(2), "aiko", Qos::Interactive, t0); + assert!(s.decide(t0).is_empty(), "aiko's next unit waits for her first, though a slot is free"); + s.release(Ticket(1)); + assert_eq!(s.decide(t0), vec![Decision::Run(Ticket(2))]); +} + +// what this catches: a mind's queue growing. Her newer work replaces her waiting work, keeps +// her place in line and the higher class, and the replaced ticket is told why it left. +#[test] +fn a_newer_submission_supersedes_the_owners_waiting_one_and_keeps_her_place() { + let t0 = Instant::now(); + let mut s = Scheduler::new(1, aging()); + s.submit(Ticket(1), "aris", Qos::Work, t0); + assert_eq!(s.decide(t0), vec![Decision::Run(Ticket(1))]); + s.submit(Ticket(2), "aiko", Qos::Interactive, at(t0, 1)); + s.submit(Ticket(3), "atlas", Qos::Work, at(t0, 2)); + assert_eq!(s.submit(Ticket(4), "aiko", Qos::Work, at(t0, 5)), vec![(Ticket(2), Dropped::Superseded)]); + assert_eq!(s.waiting(), 2, "aiko still has one waiting unit, not two"); + s.release(Ticket(1)); + assert_eq!(s.decide(at(t0, 5)), vec![Decision::Run(Ticket(4))], "interactive class and her t+1 place kept"); +} + +// what this catches: a background backlog building up behind busy work. Past its bound the +// oldest background work is shed, and work is never shed. +#[test] +fn a_full_background_queue_sheds_its_oldest_and_never_sheds_work() { + let t0 = Instant::now(); + let mut s = Scheduler::new(1, aging()); + s.submit(Ticket(1), "aris", Qos::Work, t0); + s.decide(t0); + assert!(s.submit(Ticket(2), "dream-a", Qos::Background, t0).is_empty()); + assert_eq!(s.submit(Ticket(3), "dream-b", Qos::Background, at(t0, 1)), vec![(Ticket(2), Dropped::Shed)]); + for (i, mind) in ["aiko", "atlas", "benchy"].into_iter().enumerate() { + assert!(s.submit(Ticket(10 + i as u64), mind, Qos::Work, at(t0, 1)).is_empty(), "work is bounded by its owners, never shed"); + } + assert_eq!(s.waiting(), 4); +} + +// what this catches: a superseded submitter waiting forever. Through the real dispatcher it +// resolves at once with the reason. +#[tokio::test(start_paused = true)] +async fn a_superseded_submission_resolves_at_once_with_its_reason() { + let flow: Flow<&'static str> = Flow::spawn(1, aging()); + let _busy = flow.submit("aris", Qos::Work).await; + let first = tokio::spawn({ + let flow = flow.clone(); + async move { flow.submit("aiko", Qos::Work).await.err() } + }); + tokio::task::yield_now().await; + let _second = tokio::spawn({ + let flow = flow.clone(); + async move { flow.submit("aiko", Qos::Work).await.is_ok() } + }); + let why = tokio::time::timeout(Duration::from_secs(1), first).await; + assert!(matches!(why, Ok(Ok(Some(Refused::Dropped(Dropped::Superseded))))), "{why:?}"); +} + +// what this catches: a dispatcher that polls. It sleeps until the next aging step, or forever +// when nothing can still age. +#[test] +fn the_dispatcher_wakes_only_at_the_next_aging_step() { + let t0 = Instant::now(); + let mut s = Scheduler::new(0, aging()); + assert_eq!(s.next_wakeup(t0), None); + s.submit(Ticket(1), "dream", Qos::Background, t0); + assert_eq!(s.next_wakeup(at(t0, 3)), Some(at(t0, 10))); + assert_eq!(s.next_wakeup(at(t0, 21)), None, "at work it no longer ages"); + s.submit(Ticket(2), "aiko", Qos::Work, t0); + assert_eq!(s.next_wakeup(at(t0, 21)), None, "work does not age"); +} + +// what this catches: a submitter that stops waiting keeping its unit, and a dropped grant +// not freeing capacity; through the real dispatcher task, not the state machine alone. +#[tokio::test(start_paused = true)] +async fn dropping_a_grant_or_a_waiting_submission_frees_the_unit() { + let flow: Flow<&'static str> = Flow::spawn(1, aging()); + let held = flow.submit("aiko", Qos::Work).await; + assert!(held.is_ok()); + let waiting = tokio::spawn({ + let flow = flow.clone(); + async move { flow.submit("aris", Qos::Work).await.is_ok() } + }); + tokio::task::yield_now().await; + waiting.abort(); + drop(held); + let next = tokio::time::timeout(Duration::from_secs(1), flow.submit("atlas", Qos::Work)).await; + assert!(matches!(next, Ok(Ok(_))), "neither the aborted wait nor the dropped grant kept the unit"); +} + +// what this catches: a running low class never told to yield through the dispatcher. +#[tokio::test(start_paused = true)] +async fn a_running_dream_hears_the_yield_when_a_reply_arrives() { + let flow: Flow<&'static str> = Flow::spawn(1, aging()); + let mut dream = flow.submit("dream", Qos::Background).await.expect("dispatcher running"); // expect: the test owns the live dispatcher + let reply = tokio::spawn({ + let flow = flow.clone(); + async move { flow.submit("aiko", Qos::Interactive).await.is_ok() } + }); + tokio::time::timeout(Duration::from_secs(1), dream.yield_requested()).await.expect("asked to yield"); // expect: the assertion itself + drop(dream); + assert!(reply.await.expect("reply task")); // expect: the assertion itself +} From 3f967297e5708607b31b57b43c7039f6d0e513b3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 09:48:01 -0500 Subject: [PATCH 2/7] continuum-flow: Stage (CBAR QueueThread), the capacity dispatcher, and a simulator calibrated to the M5; 16 cases green - Stage: a bounded keep-newest input, one worker task woken only by a push, a class. - Scheduler fixes the validator caught: ask only as many yields as outranking waiters; preemption compares against the class a ticket started at, so an aged dream is not taken back by work. - sim: decode 30.5*n^0.865 tok/s across n streams (101 at four), prefill 304/sqrt(n) per job, page-out 0.1 s (M5, 2026-10-28). Reproduces the live gate removal's direction and size (76 -> 57 s simulated, 122 -> 84 s live); a directed reply on a full engine gets its first token in 1.7 s; a dream runs 16 times an hour and slows six residents by 4%. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- Cargo.lock | 7 ++ core/continuum-flow/Cargo.toml | 3 + core/continuum-flow/src/flow.rs | 2 +- core/continuum-flow/src/lib.rs | 5 + core/continuum-flow/src/scheduler.rs | 25 +++- core/continuum-flow/src/sim.rs | 176 +++++++++++++++++++++++++++ core/continuum-flow/src/sim_tests.rs | 95 +++++++++++++++ core/continuum-flow/src/stage.rs | 87 +++++++++++++ 8 files changed, 393 insertions(+), 7 deletions(-) create mode 100644 core/continuum-flow/src/sim.rs create mode 100644 core/continuum-flow/src/sim_tests.rs create mode 100644 core/continuum-flow/src/stage.rs diff --git a/Cargo.lock b/Cargo.lock index b24dd9039e..7b4fdffe8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3198,6 +3198,13 @@ dependencies = [ "uuid", ] +[[package]] +name = "continuum-flow" +version = "0.1.0" +dependencies = [ + "tokio", +] + [[package]] name = "continuum-genome" version = "0.1.0" diff --git a/core/continuum-flow/Cargo.toml b/core/continuum-flow/Cargo.toml index 0907023d21..12af393af5 100644 --- a/core/continuum-flow/Cargo.toml +++ b/core/continuum-flow/Cargo.toml @@ -6,3 +6,6 @@ description = "Work flows through queues, never locks: quality-of-service classe [dependencies] tokio = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["test-util", "macros", "rt-multi-thread"] } diff --git a/core/continuum-flow/src/flow.rs b/core/continuum-flow/src/flow.rs index 9b8521d936..6ddb4dfffb 100644 --- a/core/continuum-flow/src/flow.rs +++ b/core/continuum-flow/src/flow.rs @@ -119,7 +119,7 @@ impl Flow { } async fn dispatch(mut scheduler: Scheduler, mut inbox: mpsc::UnboundedReceiver>) { - let mut starting: HashMap>> = HashMap::new(); + let mut starting: HashMap, Dropped>>> = HashMap::new(); let mut yielding: HashMap> = HashMap::new(); loop { let now = Instant::now(); diff --git a/core/continuum-flow/src/lib.rs b/core/continuum-flow/src/lib.rs index 001b56b1f1..abc96d1fc2 100644 --- a/core/continuum-flow/src/lib.rs +++ b/core/continuum-flow/src/lib.rs @@ -20,10 +20,15 @@ mod flow; mod qos; mod scheduler; +mod stage; +pub mod sim; pub use flow::{Flow, Grant, Refused}; pub use qos::Qos; pub use scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; +pub use stage::{spawn_stage, Stage, StageInput}; #[cfg(test)] mod tests; +#[cfg(test)] +mod sim_tests; diff --git a/core/continuum-flow/src/scheduler.rs b/core/continuum-flow/src/scheduler.rs index 6193c9fd03..8fce92754d 100644 --- a/core/continuum-flow/src/scheduler.rs +++ b/core/continuum-flow/src/scheduler.rs @@ -34,7 +34,9 @@ struct Waiting { struct Running { owner: K, - qos: Qos, + /// The class it started at: its own, or the class aging raised it to. Preemption compares + /// against this, so a dream that aged into its turn is not taken back by work. + started_as: u32, yield_asked: bool, } @@ -140,17 +142,28 @@ impl Scheduler { while self.running.len() < self.capacity { let Some(ticket) = self.best_eligible(now) else { break }; let Some(w) = self.waiting.remove(&ticket) else { break }; + let started_as = self.effective(&w, now); self.busy_owners.insert(w.owner.clone()); - self.running.insert(ticket, Running { owner: w.owner, qos: w.qos, yield_asked: false }); + self.running.insert(ticket, Running { owner: w.owner, started_as, yield_asked: false }); out.push(Decision::Run(ticket)); } - if let Some(best) = self.best_eligible(now) { - let wanted = self.waiting.get(&best).map(|w| w.qos); + // Ask yields only for waiting work that outranks what runs, one per such ticket, oldest + // asks first: the lowest class that started lowest yields first. + let eligible: Vec = self + .waiting + .values() + .filter(|w| !self.busy_owners.contains(&w.owner)) + .map(|w| w.qos.rank()) + .collect(); + let asked = self.running.values().filter(|r| r.yield_asked).count(); + let lowest_running = self.running.values().filter(|r| !r.yield_asked).map(|r| r.started_as).min(); + let outranking = lowest_running.map_or(0, |low| eligible.iter().filter(|&&q| q > low).count()); + if outranking > asked { let victim = self .running .iter() - .filter(|(_, r)| !r.yield_asked && wanted.is_some_and(|q| q > r.qos)) - .min_by_key(|(t, r)| (r.qos, std::cmp::Reverse(**t))) + .filter(|(_, r)| !r.yield_asked) + .min_by_key(|(t, r)| (r.started_as, std::cmp::Reverse(**t))) .map(|(t, _)| *t); if let Some(t) = victim { if let Some(r) = self.running.get_mut(&t) { diff --git a/core/continuum-flow/src/sim.rs b/core/continuum-flow/src/sim.rs new file mode 100644 index 0000000000..be8e815a28 --- /dev/null +++ b/core/continuum-flow/src/sim.rs @@ -0,0 +1,176 @@ +//! A discrete-time simulator: the pure scheduler driving a fake engine calibrated from the M5's +//! measurements (Qwen3.6-35B-A3B at ~64k context, 2026-10-28): +//! - decode: all streams together make `30.5 * n^0.865` tok/s (30.5 alone, 101 at four streams); +//! - prefill: each prefilling job gets `304 / sqrt(n)` tok/s with `n` jobs on the engine (152 at +//! four, measured 146-163); +//! - a yield costs a page-out (`0.1 s`, fork #70). +//! Minds act (prefill, decode, then tools off the engine), directed calls arrive, dreams and +//! training run in the gaps. Every case in FLOW-IMPLEMENTATION-PLAN §6 runs here in milliseconds +//! and reports what a live read reports. + +use crate::{Aging, Decision, Qos, Scheduler, Ticket}; +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +/// The fake engine's measured shape. +#[derive(Clone, Copy, Debug)] +pub struct Engine { + pub slots: usize, + pub decode_alone: f64, + pub decode_exponent: f64, + pub prefill_alone: f64, + pub page_out_s: f64, +} + +impl Engine { + pub fn m5() -> Self { + Self { slots: 4, decode_alone: 30.5, decode_exponent: 0.865, prefill_alone: 304.0, page_out_s: 0.1 } + } +} + +/// One unit of work: what it costs and how it repeats. +#[derive(Clone, Debug)] +pub struct Job { + pub owner: &'static str, + pub qos: Qos, + pub prefill: f64, + pub decode: f64, + /// Off-engine time before the owner's next unit (tools, settle); `None` = runs once. + pub then_off_engine_s: Option, + /// First submission time. + pub at_s: f64, +} + +/// What a run reports: the numbers a live read reads. +#[derive(Debug, Default)] +pub struct Report { + /// Per owner: units finished, total wait before start, worst wait, sum of unit times. + pub owners: HashMap<&'static str, OwnerStats>, + pub tokens_decoded: f64, + pub seconds: f64, +} + +#[derive(Debug, Default, Clone)] +pub struct OwnerStats { + pub done: u32, + pub waits: Vec, + pub unit_s: Vec, + /// Submission to first decoded token, per unit. + pub first_token_s: Vec, +} + +impl OwnerStats { + pub fn median_unit_s(&self) -> f64 { median(&self.unit_s) } + pub fn worst_wait_s(&self) -> f64 { self.waits.iter().cloned().fold(0.0, f64::max) } + pub fn median_first_token_s(&self) -> f64 { median(&self.first_token_s) } +} + +fn median(v: &[f64]) -> f64 { + if v.is_empty() { return f64::NAN; } + let mut s = v.to_vec(); + s.sort_by(|a, b| a.total_cmp(b)); + s[s.len() / 2] +} + +struct Live { + job: Job, + submitted_s: f64, + started_s: Option, + first_token_s: Option, + prefill_left: f64, + decode_left: f64, + yielding_until: Option, +} + +/// Run `jobs` for `seconds` of virtual time in steps of `dt`. `prefill_cap` models a prefill throttle +/// (the gate deleted in 4579b4711) so the simulator can be checked against the live before/after. +pub fn run(engine: Engine, aging: Aging, jobs: &[Job], seconds: f64, dt: f64, prefill_cap: Option) -> Report { + let t0 = Instant::now(); + let at = |s: f64| t0 + Duration::from_secs_f64(s); + let mut sched: Scheduler<&'static str> = Scheduler::new(engine.slots, aging); + let mut live: HashMap = HashMap::new(); + let mut running: Vec = Vec::new(); + let mut next_ticket = 0u64; + let mut timers: Vec<(f64, Job)> = jobs.iter().map(|j| (j.at_s, j.clone())).collect(); + let mut report = Report { seconds, ..Default::default() }; + let mut now = 0.0; + while now < seconds { + // Submissions due now. + let (due, later): (Vec<_>, Vec<_>) = timers.into_iter().partition(|(t, _)| *t <= now); + timers = later; + for (_, job) in due { + let ticket = Ticket(next_ticket); + next_ticket += 1; + for (gone, _) in sched.submit(ticket, job.owner, job.qos, at(now)) { + live.remove(&gone); + } + live.insert(ticket, Live { prefill_left: job.prefill, decode_left: job.decode, job, submitted_s: now, started_s: None, first_token_s: None, yielding_until: None }); + } + for decision in sched.decide(at(now)) { + match decision { + Decision::Run(t) => { + if let Some(l) = live.get_mut(&t) { + l.started_s.get_or_insert(now); + running.push(t); + } + } + Decision::Yield(t) => { + if let Some(l) = live.get_mut(&t) { + l.yielding_until = Some(now + engine.page_out_s); + } + } + } + } + // The engine advances every running job by one step. + let active: Vec = running.iter().copied().filter(|t| live.get(t).is_some_and(|l| l.yielding_until.is_none())).collect(); + let n = active.len().max(1) as f64; + let prefilling: Vec = active.iter().copied().filter(|t| live[t].prefill_left > 0.0).collect(); + let allowed_prefill = prefill_cap.map_or(prefilling.len(), |c| c.min(prefilling.len())); + let decoding = active.iter().filter(|t| live[t].prefill_left <= 0.0).count().max(1) as f64; + let per_stream_decode = engine.decode_alone * decoding.powf(engine.decode_exponent) / decoding; + let mut finished = Vec::new(); + for t in active.iter() { + let l = live.get_mut(t).expect("active tickets are live"); // expect: `active` was filtered from `live` + if l.prefill_left > 0.0 { + if prefilling.iter().position(|p| p == t).is_some_and(|k| k < allowed_prefill) { + l.prefill_left -= engine.prefill_alone / n.sqrt() * dt; + } + } else { + l.first_token_s.get_or_insert(now); + l.decode_left -= per_stream_decode * dt; + report.tokens_decoded += per_stream_decode * dt; + if l.decode_left <= 0.0 { finished.push(*t); } + } + } + // Yields complete: the job leaves its slot and waits again with its work left. + let yielded: Vec = running.iter().copied().filter(|t| live.get(t).and_then(|l| l.yielding_until).is_some_and(|u| u <= now)).collect(); + for t in yielded { + running.retain(|r| *r != t); + sched.release(t); + if let Some(mut l) = live.remove(&t) { + l.yielding_until = None; + let ticket = Ticket(next_ticket); + next_ticket += 1; + let _ = sched.submit(ticket, l.job.owner, l.job.qos, at(l.submitted_s)); + live.insert(ticket, l); + } + } + for t in finished { + running.retain(|r| *r != t); + sched.release(t); + if let Some(l) = live.remove(&t) { + let s = report.owners.entry(l.job.owner).or_default(); + s.done += 1; + let started = l.started_s.unwrap_or(now); // started is set before any decode + s.waits.push(started - l.submitted_s); + s.unit_s.push(now - l.submitted_s); + if let Some(ft) = l.first_token_s { s.first_token_s.push(ft - l.submitted_s); } + if let Some(off) = l.job.then_off_engine_s { + timers.push((now + off, Job { at_s: now + off, ..l.job.clone() })); + } + } + } + now += dt; + } + report +} diff --git a/core/continuum-flow/src/sim_tests.rs b/core/continuum-flow/src/sim_tests.rs new file mode 100644 index 0000000000..ff2e02f2f1 --- /dev/null +++ b/core/continuum-flow/src/sim_tests.rs @@ -0,0 +1,95 @@ +#![cfg(test)] +//! The simulator's cases (FLOW-IMPLEMENTATION-PLAN §6). Each prints what a live read reports and +//! asserts the plan's rule. Resident act shape from the M5's last 400 requests (2026-10-28): +//! ~4,000 tokens prefilled and ~870 decoded per model call, then ~15 s of tools off the engine. +use crate::sim::{run, Engine, Job, Report}; +use crate::{Aging, Qos}; +use std::time::Duration; + +const RESIDENTS: [&str; 6] = ["aiko", "aris", "atlas", "benchy", "kimi", "nova"]; + +fn aging() -> Aging { + Aging([Duration::from_secs(60), Duration::from_secs(30), Duration::ZERO, Duration::ZERO]) +} + +fn residents(n: usize) -> Vec { + RESIDENTS[..n] + .iter() + .enumerate() + .map(|(i, owner)| Job { owner, qos: Qos::Work, prefill: 4000.0, decode: 870.0, then_off_engine_s: Some(15.0), at_s: i as f64 * 0.5 }) + .collect() +} + +fn summary(label: &str, r: &Report) -> f64 { + let mut units: Vec = r.owners.iter().filter(|(o, _)| RESIDENTS.contains(*o)).flat_map(|(_, s)| s.unit_s.clone()).collect(); + units.sort_by(|a, b| a.total_cmp(b)); + let median = units.get(units.len() / 2).copied().unwrap_or(f64::NAN); // empty = NaN, printed as such + let acts: u32 = r.owners.iter().filter(|(o, _)| RESIDENTS.contains(*o)).map(|(_, s)| s.done).sum(); + println!( + "{label}: resident model call median {median:.0} s, {:.0} acts/h, {:.0} tok/s decoded overall", + acts as f64 * 3600.0 / r.seconds, + r.tokens_decoded / r.seconds + ); + median +} + +// what this catches: a simulator that does not match the node. The live M5 went from a 3-slot, +// prefill-throttled admission (median model-call wait+run ~122 s) to 4579b4711 (~84 s). The +// simulator must reproduce that direction and roughly that size before it may forecast anything. +#[test] +fn the_simulator_reproduces_todays_live_before_and_after() { + let three_slots = Engine { slots: 3, ..Engine::m5() }; + let before = summary("before: 3 usable slots, prefill throttled to 1-2", &run(three_slots, aging(), &residents(4), 3600.0, 0.05, Some(1))); + let after = summary("after 4579b4711: 3 usable slots, no throttle", &run(three_slots, aging(), &residents(4), 3600.0, 0.05, None)); + let all = summary("all 4 slots serve minds", &run(Engine::m5(), aging(), &residents(4), 3600.0, 0.05, None)); + assert!(after < before, "removing the throttle must help"); + assert!(all <= after, "a fourth usable slot must not hurt"); +} + +// what this catches: minds waiting when there is a slot for each. +#[test] +fn four_minds_on_four_slots_never_wait() { + let r = run(Engine::m5(), aging(), &residents(4), 1800.0, 0.05, None); + summary("4 minds, 4 slots", &r); + for (owner, s) in &r.owners { + assert!(s.worst_wait_s() < 0.2, "{owner} waited {:.1} s with a free slot", s.worst_wait_s()); + } +} + +// what this catches: a mind starving when minds outnumber slots. +#[test] +fn six_minds_on_four_slots_all_progress_with_bounded_waits() { + let r = run(Engine::m5(), aging(), &residents(6), 3600.0, 0.05, None); + summary("6 minds, 4 slots", &r); + for owner in RESIDENTS { + let s = &r.owners[owner]; + assert!(s.done >= 10, "{owner} finished only {} acts in an hour", s.done); + println!(" {owner}: {} acts, worst wait {:.0} s", s.done, s.worst_wait_s()); + } +} + +// what this catches: a directed reply queued behind a full engine. It preempts at once: its first +// token comes within its own prefill time plus one page-out, not after someone's whole act. +#[test] +fn a_directed_reply_on_a_full_engine_starts_within_its_own_prefill() { + let mut jobs = residents(4); + jobs.push(Job { owner: "joel-asks-aiko", qos: Qos::Interactive, prefill: 300.0, decode: 120.0, then_off_engine_s: None, at_s: 300.0 }); + let r = run(Engine::m5(), aging(), &jobs, 600.0, 0.05, None); + let reply = &r.owners["joel-asks-aiko"]; + println!("directed reply: first token after {:.2} s, done after {:.1} s", reply.median_first_token_s(), reply.median_unit_s()); + assert!(reply.median_first_token_s() < 3.0, "first token after {:.2} s", reply.median_first_token_s()); +} + +// what this catches: background work never running, or running at work's expense. +#[test] +fn a_dream_completes_under_steady_work_without_slowing_it() { + let mut jobs = residents(6); + jobs.push(Job { owner: "dream", qos: Qos::Background, prefill: 2000.0, decode: 400.0, then_off_engine_s: Some(60.0), at_s: 10.0 }); + let with = run(Engine::m5(), aging(), &jobs, 3600.0, 0.05, None); + let without = run(Engine::m5(), aging(), &residents(6), 3600.0, 0.05, None); + let dream = &with.owners["dream"]; + println!("dream: {} runs, worst wait {:.0} s", dream.done, dream.worst_wait_s()); + assert!(dream.done >= 3, "the dream ran {} times in an hour", dream.done); + let slower = summary("6 minds + dream", &with) / summary("6 minds", &without); + assert!(slower < 1.15, "the dream slowed work by {:.0}%", (slower - 1.0) * 100.0); +} diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs new file mode 100644 index 0000000000..5694985f1f --- /dev/null +++ b/core/continuum-flow/src/stage.rs @@ -0,0 +1,87 @@ +//! A stage: CBAR's `QueueThread` (`cb-mobile-sdk/cpp/utility/Threads.h`) in Rust. A bounded +//! input that keeps the newest (`push` drops the oldest past `DEPTH` and signals), one worker +//! task that wakes only on a push, and a class. A stage is its handler and nothing else: the +//! queue, its bound, waking and shutdown live here, never in the subsystem. + +use crate::Qos; +use std::collections::VecDeque; +use std::future::Future; +use std::sync::{Arc, Mutex}; +use tokio::sync::Notify; + +pub trait Stage: Send + 'static { + /// What wakes it: a signal, a digest handle, a frame. + type Input: Send + 'static; + /// Its class, for any capacity it submits to. + const QOS: Qos; + /// How many inputs it holds; past this the oldest is dropped. 1 = only the newest matters. + const DEPTH: usize = 1; + fn handle(&mut self, input: Self::Input) -> impl Future + Send; +} + +struct Inbox { + items: Mutex>, + signal: Notify, + depth: usize, +} + +/// The handle producers push into. Cheap to clone. Dropping every clone ends the stage once +/// 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) } + } +} + +impl StageInput { + /// Insert, dropping the oldest past the stage's depth, and signal. Returns how many it dropped. + /// The lock is held for the insert alone, never across work (CBAR's `addItem`). + pub fn push(&self, item: T) -> usize { + let dropped = { + let mut items = self.inbox.items.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned queue still holds plain data: keep serving it + let mut dropped = 0; + while items.len() >= self.inbox.depth { + items.pop_front(); + dropped += 1; + } + items.push_back(item); + dropped + }; + self.inbox.signal.notify_one(); + dropped + } +} + +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 { + self.inbox.signal.notify_one(); + } + } +} + +/// 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) }); + let alive = Arc::new(()); + let input = StageInput { inbox: Arc::clone(&inbox), alive: Arc::clone(&alive) }; + let watch = Arc::downgrade(&alive); + drop(alive); + tokio::spawn(async move { + loop { + let next = inbox.items.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); // see push + match next { + Some(item) => stage.handle(item).await, + None if watch.strong_count() == 0 => return, + None => inbox.signal.notified().await, + } + } + }); + input +} From b90d7064f7166e285726502aef439c781b11756f Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 09:48:52 -0500 Subject: [PATCH 3/7] sim: the M5 at a working-context depth (stock llama-bench fit); forecast: 82k -> 79 s/call, 32k -> 43 s, 16k -> 33 s Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-flow/src/sim.rs | 7 +++++++ core/continuum-flow/src/sim_tests.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/core/continuum-flow/src/sim.rs b/core/continuum-flow/src/sim.rs index be8e815a28..dc6258c36f 100644 --- a/core/continuum-flow/src/sim.rs +++ b/core/continuum-flow/src/sim.rs @@ -23,6 +23,13 @@ pub struct Engine { } impl Engine { + /// The M5 at a working context of `tokens`: stock `llama-bench` (741b0175b, q4_0 KV, FA) gave + /// decode 58.7 / 47.8 / 29.5 tok/s and prefill 968 / 650 / 304 tok/s at depth 0 / 16k / 64k. + /// Fitted: decode 59/(1+d/64k), within 2%; prefill 968/(1+d/30k), within 4%. + pub fn m5_at_depth(tokens: f64) -> Self { + Self { decode_alone: 59.0 / (1.0 + tokens / 65_536.0), prefill_alone: 968.0 / (1.0 + tokens / 30_000.0), ..Self::m5() } + } + pub fn m5() -> Self { Self { slots: 4, decode_alone: 30.5, decode_exponent: 0.865, prefill_alone: 304.0, page_out_s: 0.1 } } diff --git a/core/continuum-flow/src/sim_tests.rs b/core/continuum-flow/src/sim_tests.rs index ff2e02f2f1..d3cf5b54a1 100644 --- a/core/continuum-flow/src/sim_tests.rs +++ b/core/continuum-flow/src/sim_tests.rs @@ -93,3 +93,23 @@ fn a_dream_completes_under_steady_work_without_slowing_it() { let slower = summary("6 minds + dream", &with) / summary("6 minds", &without); assert!(slower < 1.15, "the dream slowed work by {:.0}%", (slower - 1.0) * 100.0); } + +// what this catches: guessing where speed comes from. The same four residents at today's median +// working context (82k) and at smaller ones, where an epoch turnover re-prefills half the context +// once every ~20 acts (today: ~65k tokens). Prints the forecast; asserts only that less context is +// faster, so the numbers stay the measurement. +#[test] +fn how_much_faster_a_smaller_working_context_makes_an_act() { + for (label, depth) in [("82k (today's median)", 82_000.0), ("32k", 32_000.0), ("16k", 16_000.0)] { + let turnover_prefill_per_act = depth * 0.5 / 20.0; + let jobs: Vec = RESIDENTS[..4] + .iter() + .enumerate() + .map(|(i, owner)| Job { owner, qos: Qos::Work, prefill: 4000.0 + turnover_prefill_per_act, decode: 870.0, then_off_engine_s: Some(15.0), at_s: i as f64 * 0.5 }) + .collect(); + summary(&format!("working context {label}"), &run(Engine::m5_at_depth(depth), aging(), &jobs, 3600.0, 0.05, None)); + } + let big = run(Engine::m5_at_depth(82_000.0), aging(), &residents(4), 1800.0, 0.05, None); + let small = run(Engine::m5_at_depth(16_000.0), aging(), &residents(4), 1800.0, 0.05, None); + assert!(summary("check 16k", &small) < summary("check 82k", &big)); +} From 4c560eff922162f5083655904904e9f6cfdf2ead Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Wed, 28 Oct 2026 11:42:42 -0500 Subject: [PATCH 4/7] continuum-flow: a stage's overflow is explicit, Reliable by default (backpressure, never drops) or KeepNewest for signals only Codex on the FLOW plan (6d18b4564): committed inputs and tool results must never ride a dropping queue. Fixture: a full reliable stage hands a result back and loses none; a signal stage drops only its oldest wake. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-flow/src/lib.rs | 2 +- core/continuum-flow/src/stage.rs | 46 ++++++++++++++++++++------- core/continuum-flow/src/tests.rs | 53 ++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 12 deletions(-) diff --git a/core/continuum-flow/src/lib.rs b/core/continuum-flow/src/lib.rs index abc96d1fc2..f255f52339 100644 --- a/core/continuum-flow/src/lib.rs +++ b/core/continuum-flow/src/lib.rs @@ -26,7 +26,7 @@ pub mod sim; pub use flow::{Flow, Grant, Refused}; pub use qos::Qos; pub use scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; -pub use stage::{spawn_stage, Stage, StageInput}; +pub use stage::{spawn_stage, Overflow, Stage, StageInput}; #[cfg(test)] mod tests; diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs index 5694985f1f..4bd05a173b 100644 --- a/core/continuum-flow/src/stage.rs +++ b/core/continuum-flow/src/stage.rs @@ -1,5 +1,5 @@ //! A stage: CBAR's `QueueThread` (`cb-mobile-sdk/cpp/utility/Threads.h`) in Rust. A bounded -//! input that keeps the newest (`push` drops the oldest past `DEPTH` and signals), one worker +//! input (reliable by default; a signal stage keeps the newest), one worker //! task that wakes only on a push, and a class. A stage is its handler and nothing else: the //! queue, its bound, waking and shutdown live here, never in the subsystem. @@ -9,13 +9,28 @@ use std::future::Future; use std::sync::{Arc, Mutex}; use tokio::sync::Notify; +/// What a full stage does with a new input. Signals and reliable inputs are different types +/// (Codex on FLOW plan 6d18b4564): a dropped tool result is lost work; a dropped wake signal is +/// not, because it only references content already committed elsewhere. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Overflow { + /// Never drop. A full stage hands the item back to the producer (backpressure), who must + /// handle it. The default. + Reliable, + /// Drop the oldest and keep the newest (CBAR's `QueueThread`). Only for signals whose input + /// references content committed elsewhere: a wake, a frame, a "fresh activity" digest handle. + KeepNewest, +} + pub trait Stage: Send + 'static { - /// What wakes it: a signal, a digest handle, a frame. + /// What wakes it: a signal, a digest handle, a frame, a result. type Input: Send + 'static; /// Its class, for any capacity it submits to. const QOS: Qos; - /// How many inputs it holds; past this the oldest is dropped. 1 = only the newest matters. + /// How many inputs it holds before `OVERFLOW` applies. const DEPTH: usize = 1; + /// What a full stage does: never drops unless a signal stage opts in. + const OVERFLOW: Overflow = Overflow::Reliable; fn handle(&mut self, input: Self::Input) -> impl Future + Send; } @@ -23,6 +38,7 @@ struct Inbox { items: Mutex>, signal: Notify, depth: usize, + overflow: Overflow, } /// The handle producers push into. Cheap to clone. Dropping every clone ends the stage once @@ -39,21 +55,29 @@ impl Clone for StageInput { } impl StageInput { - /// Insert, dropping the oldest past the stage's depth, and signal. Returns how many it dropped. - /// The lock is held for the insert alone, never across work (CBAR's `addItem`). - pub fn push(&self, item: T) -> usize { + /// Insert and signal. A `KeepNewest` stage drops its oldest past its depth and returns how + /// many it dropped; a `Reliable` stage at its depth hands the item back (`Err`) and drops + /// nothing. The lock is held for the insert alone, never across work (CBAR's `addItem`). + pub fn push(&self, item: T) -> Result { let dropped = { let mut items = self.inbox.items.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned queue still holds plain data: keep serving it let mut dropped = 0; - while items.len() >= self.inbox.depth { - items.pop_front(); - dropped += 1; + if items.len() >= self.inbox.depth { + match self.inbox.overflow { + Overflow::Reliable => return Err(item), + Overflow::KeepNewest => { + while items.len() >= self.inbox.depth { + items.pop_front(); + dropped += 1; + } + } + } } items.push_back(item); dropped }; self.inbox.signal.notify_one(); - dropped + Ok(dropped) } } @@ -68,7 +92,7 @@ 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) }); + 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); diff --git a/core/continuum-flow/src/tests.rs b/core/continuum-flow/src/tests.rs index 26169dc69e..908bf91862 100644 --- a/core/continuum-flow/src/tests.rs +++ b/core/continuum-flow/src/tests.rs @@ -178,3 +178,56 @@ async fn a_running_dream_hears_the_yield_when_a_reply_arrives() { drop(dream); assert!(reply.await.expect("reply task")); // expect: the assertion itself } + +// what this catches (Codex on the FLOW plan): a tool result riding a queue that drops. A reliable +// stage hands a result back when full and never loses one; only a signal stage drops, and only +// its oldest wakes. +#[tokio::test(start_paused = true)] +async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newest() { + use std::sync::{Arc, Mutex}; + struct Results(Arc>>, Arc); + impl Stage for Results { + type Input = u32; + const QOS: Qos = Qos::Work; + const DEPTH: usize = 2; + async fn handle(&mut self, input: u32) { + self.1.notified().await; // hold the worker so the queue fills + self.0.lock().unwrap_or_else(|e| e.into_inner()).push(input); // test: plain data + } + } + struct Wakes(Arc>>, Arc); + impl Stage for Wakes { + type Input = u32; + const QOS: Qos = Qos::Utility; + const DEPTH: usize = 1; + const OVERFLOW: Overflow = Overflow::KeepNewest; + async fn handle(&mut self, input: u32) { + self.1.notified().await; + self.0.lock().unwrap_or_else(|e| e.into_inner()).push(input); // test: plain data + } + } + let (got, gate) = (Arc::new(Mutex::new(Vec::new())), Arc::new(tokio::sync::Notify::new())); + let results = spawn_stage(Results(Arc::clone(&got), Arc::clone(&gate))); + assert_eq!(results.push(1), Ok(0)); + tokio::task::yield_now().await; // the worker takes 1 and waits on the gate + assert_eq!(results.push(2), Ok(0)); + assert_eq!(results.push(3), Ok(0)); + assert_eq!(results.push(4), Err(4), "full: the producer gets its result back, nothing is dropped"); + for _ in 0..3 { + gate.notify_one(); + tokio::task::yield_now().await; + } + assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2, 3]); // test: plain data + + let (seen, hold) = (Arc::new(Mutex::new(Vec::new())), Arc::new(tokio::sync::Notify::new())); + let wakes = spawn_stage(Wakes(Arc::clone(&seen), Arc::clone(&hold))); + assert_eq!(wakes.push(1), Ok(0)); + tokio::task::yield_now().await; + assert_eq!(wakes.push(2), Ok(0)); + assert_eq!(wakes.push(3), Ok(1), "a signal stage drops its oldest wake"); + for _ in 0..2 { + hold.notify_one(); + tokio::task::yield_now().await; + } + assert_eq!(*seen.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 3], "the newest wake is handled"); // test: plain data +} From 689c3a32e8d349a971e73ba8cacfcec6255fba63 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Thu, 29 Oct 2026 16:53:07 -0500 Subject: [PATCH 5/7] fix(flow): close stage after its last producer and drain accepted inputs (#5567) * fix(flow): publish producer closure before waking stage * test(ci): classify flow as an independent workspace leaf --- core/continuum-flow/src/stage.rs | 22 +++++---- core/continuum-flow/src/tests.rs | 48 ++++++++++++++++++++ tools/scripts/tests/ci-change-scope.test.cjs | 13 ++---- 3 files changed, 65 insertions(+), 18 deletions(-) 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 9ae33690a3..eb95a0b3b4 100644 --- a/tools/scripts/tests/ci-change-scope.test.cjs +++ b/tools/scripts/tests/ci-change-scope.test.cjs @@ -9,13 +9,10 @@ const select = (...paths) => { return { rust, installer, publication }; }; -// 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 -// reach them. Kept explicit, so a crate moving in the graph fails here instead of silently -// changing what CI runs. -// Tested crates a kernel change does not reach: the floor (base, host, git, service) and the leaf -// codec continuum-context, which depends on nothing in the workspace. -const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-context', 'continuum-proving-types']; +// Tested crates a kernel change does not reach: the floor (base, host, git, service) and the leaves +// that depend on nothing in the workspace (the codec continuum-context, the flow continuum-flow, the +// proving ground's types continuum-proving-types). +const BELOW_KERNEL = ['continuum-base', 'continuum-host', 'continuum-git', 'continuum-service', 'continuum-context', 'continuum-flow', 'continuum-proving-types']; 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']) @@ -154,7 +151,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 => !['continuum-base', 'continuum-service', 'continuum-context', 'continuum-proving-types'].includes(n)), cli: true }); + assert.deepEqual(scope(['core/continuum-host/src/durable/mod.rs']), { crates: TESTED_CRATES.filter(n => !['continuum-base', 'continuum-service', 'continuum-context', 'continuum-flow', 'continuum-proving-types'].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 -> ... From 29574a6b70f8ea14d0f6b37707444103ae6680c3 Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 08:26:39 -0600 Subject: [PATCH 6/7] continuum-flow: a stage holds one input in hand and one pending (CBAR's double buffer), not a queue it sizes itself `Stage::DEPTH` was a size each stage picked (ONE-BUDGET's self_sized class). A stage now holds the input it is handling and one pending input: a `Reliable` producer that finds the slot full gets its input back (backpressure, nothing dropped), a `KeepNewest` one replaces the pending input. The two stage tests assert the same contracts at that shape. Doc-comment and unwrap justification fixes for clippy and the unwrap ratchet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-flow/src/sim.rs | 1 + core/continuum-flow/src/stage.rs | 43 ++++++++----------- core/continuum-flow/src/tests.rs | 15 +++---- docs/architecture/FLOW-IMPLEMENTATION-PLAN.md | 5 ++- 4 files changed, 27 insertions(+), 37 deletions(-) diff --git a/core/continuum-flow/src/sim.rs b/core/continuum-flow/src/sim.rs index dc6258c36f..67f444e595 100644 --- a/core/continuum-flow/src/sim.rs +++ b/core/continuum-flow/src/sim.rs @@ -4,6 +4,7 @@ //! - prefill: each prefilling job gets `304 / sqrt(n)` tok/s with `n` jobs on the engine (152 at //! four, measured 146-163); //! - a yield costs a page-out (`0.1 s`, fork #70). +//! //! Minds act (prefill, decode, then tools off the engine), directed calls arrive, dreams and //! training run in the gaps. Every case in FLOW-IMPLEMENTATION-PLAN §6 runs here in milliseconds //! and reports what a live read reports. diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs index ad02d45633..7a6e8fc349 100644 --- a/core/continuum-flow/src/stage.rs +++ b/core/continuum-flow/src/stage.rs @@ -4,7 +4,6 @@ //! queue, its bound, waking and shutdown live here, never in the subsystem. use crate::Qos; -use std::collections::VecDeque; use std::future::Future; use std::sync::{Arc, Mutex}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -28,18 +27,18 @@ pub trait Stage: Send + 'static { type Input: Send + 'static; /// Its class, for any capacity it submits to. const QOS: Qos; - /// How many inputs it holds before `OVERFLOW` applies. - const DEPTH: usize = 1; /// What a full stage does: never drops unless a signal stage opts in. const OVERFLOW: Overflow = Overflow::Reliable; fn handle(&mut self, input: Self::Input) -> impl Future + Send; } +/// A stage holds one input in hand (the one it is handling) and one pending: CBAR's double +/// buffer. A producer that finds the pending slot full gets its input back (`Reliable`) or replaces +/// the pending one (`KeepNewest`), so no stage sizes a queue of its own. struct Inbox { producers: AtomicUsize, - items: Mutex>, + pending: Mutex>, signal: Notify, - depth: usize, overflow: Overflow, } @@ -57,25 +56,19 @@ impl Clone for StageInput { } impl StageInput { - /// Insert and signal. A `KeepNewest` stage drops its oldest past its depth and returns how - /// many it dropped; a `Reliable` stage at its depth hands the item back (`Err`) and drops - /// nothing. The lock is held for the insert alone, never across work (CBAR's `addItem`). + /// Put `item` in the pending slot and signal. A `Reliable` stage whose slot is full hands the + /// item back (`Err`) and drops nothing; a `KeepNewest` stage replaces the pending input and + /// returns how many it dropped (0 or 1). The lock is held for the insert alone, never across + /// work (CBAR's `addItem`). pub fn push(&self, item: T) -> Result { let dropped = { - let mut items = self.inbox.items.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned queue still holds plain data: keep serving it - let mut dropped = 0; - if items.len() >= self.inbox.depth { - match self.inbox.overflow { - Overflow::Reliable => return Err(item), - Overflow::KeepNewest => { - while items.len() >= self.inbox.depth { - items.pop_front(); - dropped += 1; - } - } - } - } - items.push_back(item); + let mut pending = self.inbox.pending.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned slot still holds plain data: keep serving it + let dropped = match (pending.is_some(), self.inbox.overflow) { + (true, Overflow::Reliable) => return Err(item), + (true, Overflow::KeepNewest) => 1, + (false, _) => 0, + }; + *pending = Some(item); dropped }; self.inbox.signal.notify_one(); @@ -94,13 +87,13 @@ 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 { producers: AtomicUsize::new(1), items: Mutex::new(VecDeque::new()), signal: Notify::new(), depth: S::DEPTH.max(1), overflow: S::OVERFLOW }); + let inbox = Arc::new(Inbox { producers: AtomicUsize::new(1), pending: Mutex::new(None), signal: Notify::new(), overflow: S::OVERFLOW }); let input = StageInput { inbox: Arc::clone(&inbox) }; tokio::spawn(async move { loop { 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) + let mut pending = inbox.pending.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned slot still holds plain data, as in push + (pending.take(), inbox.producers.load(Ordering::Acquire) == 0) }; match next { Some(item) => stage.handle(item).await, diff --git a/core/continuum-flow/src/tests.rs b/core/continuum-flow/src/tests.rs index f3cb039b24..68d6e017ee 100644 --- a/core/continuum-flow/src/tests.rs +++ b/core/continuum-flow/src/tests.rs @@ -189,9 +189,8 @@ async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newe impl Stage for Results { type Input = u32; const QOS: Qos = Qos::Work; - const DEPTH: usize = 2; async fn handle(&mut self, input: u32) { - self.1.notified().await; // hold the worker so the queue fills + self.1.notified().await; // hold the worker so the pending slot fills self.0.lock().unwrap_or_else(|e| e.into_inner()).push(input); // test: plain data } } @@ -199,7 +198,6 @@ async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newe impl Stage for Wakes { type Input = u32; const QOS: Qos = Qos::Utility; - const DEPTH: usize = 1; const OVERFLOW: Overflow = Overflow::KeepNewest; async fn handle(&mut self, input: u32) { self.1.notified().await; @@ -211,13 +209,12 @@ async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newe assert_eq!(results.push(1), Ok(0)); tokio::task::yield_now().await; // the worker takes 1 and waits on the gate assert_eq!(results.push(2), Ok(0)); - assert_eq!(results.push(3), Ok(0)); - assert_eq!(results.push(4), Err(4), "full: the producer gets its result back, nothing is dropped"); - for _ in 0..3 { + assert_eq!(results.push(3), Err(3), "full: the producer gets its result back, nothing is dropped"); + for _ in 0..2 { gate.notify_one(); tokio::task::yield_now().await; } - assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2, 3]); // test: plain data + assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2]); // test: plain data let (seen, hold) = (Arc::new(Mutex::new(Vec::new())), Arc::new(tokio::sync::Notify::new())); let wakes = spawn_stage(Wakes(Arc::clone(&seen), Arc::clone(&hold))); @@ -243,7 +240,6 @@ async fn simultaneous_last_producers_close_and_drain_the_stage() { 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 { @@ -268,7 +264,6 @@ async fn simultaneous_last_producers_close_and_drain_the_stage() { }); scope.spawn(move || { barrier.wait(); - if queued { assert_eq!(second.push(2), Ok(0)); } drop(second); }); }); @@ -276,6 +271,6 @@ async fn simultaneous_last_producers_close_and_drain_the_stage() { .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![] }); + assert_eq!(seen, if queued { vec![1] } else { vec![] }); } } diff --git a/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md b/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md index 7fb25e40f0..8db12f5690 100644 --- a/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md +++ b/docs/architecture/FLOW-IMPLEMENTATION-PLAN.md @@ -84,10 +84,11 @@ They're short." The reference is `cb-mobile-sdk/cpp/utility/Threads.h` `QueueThr pub trait Stage: Send + 'static { type Input: Send; // what wakes it (a signal, a digest handle, a frame) const QOS: Qos; // its class - const DEPTH: usize = 1; // bounded queue; when full, the oldest is dropped (keep-latest) + const OVERFLOW: Overflow; // Reliable (default: a full slot hands the input back) or KeepNewest (signals) async fn handle(&mut self, input: Self::Input); } -// spawn_stage(stage) -> StageInput: push() inserts, drops the oldest past DEPTH, and signals. +// spawn_stage(stage) -> StageInput: a stage holds one input in hand and one pending (CBAR's +// double buffer); push() fills the pending slot, or hands the input back / replaces it when full, and signals. // A stage that needs a shared capacity (the engine, a TTS model) submits to that capacity's Flow. ``` From 4e11cd0beda1f373954aecadc56daee014ebed4c Mon Sep 17 00:00:00 2001 From: Joel Teply Date: Tue, 3 Nov 2026 08:43:18 -0600 Subject: [PATCH 7/7] continuum-flow: a reliable producer awaits the free slot (send), and a stage whose worker ended hands inputs back (Cormac on #5729) `StageInput::send` waits on the stage's `space` signal (registered before the slot is read, so a take between the read and the wait is never missed) while a `Reliable` slot is taken: backpressure a producer awaits instead of spinning or dropping. `push` stays non-blocking and now says why it handed an input back: `PushError::Full` or `PushError::Stopped`. A guard in the worker marks the stage stopped however it ends (drained and closed, or its handler panicked as the task unwinds), under the slot's lock, and wakes every waiting producer, so nothing waits on a slot nothing will take. Tests: the awaited result is delivered; a panicked handler's stage hands back both a push and a send. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo --- core/continuum-flow/src/lib.rs | 2 +- core/continuum-flow/src/stage.rs | 100 ++++++++++++++++++++++++++----- core/continuum-flow/src/tests.rs | 36 ++++++++++- 3 files changed, 119 insertions(+), 19 deletions(-) diff --git a/core/continuum-flow/src/lib.rs b/core/continuum-flow/src/lib.rs index f255f52339..b2103f0d04 100644 --- a/core/continuum-flow/src/lib.rs +++ b/core/continuum-flow/src/lib.rs @@ -26,7 +26,7 @@ pub mod sim; pub use flow::{Flow, Grant, Refused}; pub use qos::Qos; pub use scheduler::{Aging, Decision, Dropped, Scheduler, Ticket}; -pub use stage::{spawn_stage, Overflow, Stage, StageInput}; +pub use stage::{spawn_stage, Overflow, PushError, Stage, StageInput, Stopped}; #[cfg(test)] mod tests; diff --git a/core/continuum-flow/src/stage.rs b/core/continuum-flow/src/stage.rs index 7a6e8fc349..d97820a233 100644 --- a/core/continuum-flow/src/stage.rs +++ b/core/continuum-flow/src/stage.rs @@ -1,12 +1,12 @@ -//! A stage: CBAR's `QueueThread` (`cb-mobile-sdk/cpp/utility/Threads.h`) in Rust. A bounded -//! input (reliable by default; a signal stage keeps the newest), one worker -//! task that wakes only on a push, and a class. A stage is its handler and nothing else: the -//! queue, its bound, waking and shutdown live here, never in the subsystem. +//! A stage: CBAR's `QueueThread` (`cb-mobile-sdk/cpp/utility/Threads.h`) in Rust. One input in +//! hand and one pending (reliable by default; a signal stage keeps the newest), one worker task that +//! wakes only on a push, and a class. A stage is its handler and nothing else: the slot, waking, +//! backpressure and shutdown live here, never in the subsystem. use crate::Qos; use std::future::Future; use std::sync::{Arc, Mutex}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use tokio::sync::Notify; /// What a full stage does with a new input. Signals and reliable inputs are different types @@ -14,8 +14,8 @@ use tokio::sync::Notify; /// not, because it only references content already committed elsewhere. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Overflow { - /// Never drop. A full stage hands the item back to the producer (backpressure), who must - /// handle it. The default. + /// Never drop. A producer awaits the free slot ([`StageInput::send`]), or `push` hands the + /// item back when the slot is full. The default. Reliable, /// Drop the oldest and keep the newest (CBAR's `QueueThread`). Only for signals whose input /// references content committed elsewhere: a wake, a frame, a "fresh activity" digest handle. @@ -38,10 +38,29 @@ pub trait Stage: Send + 'static { struct Inbox { producers: AtomicUsize, pending: Mutex>, + /// Wakes the worker: an input arrived, or the last producer left. signal: Notify, + /// Wakes a waiting producer: the worker took the pending input, or the stage stopped. + space: Notify, + /// The worker has ended (every producer gone and the slot drained, or its handler panicked): + /// nothing more will be taken, so an input is handed back instead of waiting forever. + stopped: AtomicBool, overflow: Overflow, } +/// Why `push` handed an input back. +#[derive(Debug, PartialEq, Eq)] +pub enum PushError { + /// A `Reliable` stage's pending slot is taken; [`StageInput::send`] waits for it. + Full(T), + /// The stage's worker has ended; nothing will take it. + Stopped(T), +} + +/// The stage's worker has ended; `send` hands the input back. +#[derive(Debug, PartialEq, Eq)] +pub struct Stopped(pub T); + /// The handle producers push into. Cheap to clone. Dropping every clone ends the stage once /// its queued inputs are handled. pub struct StageInput { @@ -56,15 +75,18 @@ impl Clone for StageInput { } impl StageInput { - /// Put `item` in the pending slot and signal. A `Reliable` stage whose slot is full hands the - /// item back (`Err`) and drops nothing; a `KeepNewest` stage replaces the pending input and - /// returns how many it dropped (0 or 1). The lock is held for the insert alone, never across - /// work (CBAR's `addItem`). - pub fn push(&self, item: T) -> Result { + /// Put `item` in the pending slot and signal, without waiting. A `Reliable` stage whose slot is + /// taken hands the item back (`Full`) and drops nothing; a `KeepNewest` stage replaces the + /// pending input and returns how many it dropped (0 or 1); a stopped stage hands it back + /// (`Stopped`). The lock is held for the insert alone, never across work (CBAR's `addItem`). + pub fn push(&self, item: T) -> Result> { let dropped = { let mut pending = self.inbox.pending.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned slot still holds plain data: keep serving it + if self.inbox.stopped.load(Ordering::Acquire) { + return Err(PushError::Stopped(item)); + } let dropped = match (pending.is_some(), self.inbox.overflow) { - (true, Overflow::Reliable) => return Err(item), + (true, Overflow::Reliable) => return Err(PushError::Full(item)), (true, Overflow::KeepNewest) => 1, (false, _) => 0, }; @@ -74,6 +96,27 @@ impl StageInput { self.inbox.signal.notify_one(); Ok(dropped) } + + /// Put `item` in the pending slot, waiting while a `Reliable` stage's slot is taken: the + /// backpressure a producer awaits instead of spinning or dropping. Hands the item back only + /// when the stage has stopped. + pub async fn send(&self, mut item: T) -> Result<(), Stopped> { + loop { + // Registered before the slot is looked at, so a take between the look and the wait + // is never missed. + let space = self.inbox.space.notified(); + tokio::pin!(space); + space.as_mut().enable(); + match self.push(item) { + Ok(_) => return Ok(()), + Err(PushError::Stopped(back)) => return Err(Stopped(back)), + Err(PushError::Full(back)) => { + item = back; + space.await; + } + } + } + } } impl Drop for StageInput { @@ -87,16 +130,30 @@ 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 { producers: AtomicUsize::new(1), pending: Mutex::new(None), signal: Notify::new(), overflow: S::OVERFLOW }); + let inbox = Arc::new(Inbox { + producers: AtomicUsize::new(1), + pending: Mutex::new(None), + signal: Notify::new(), + space: Notify::new(), + stopped: AtomicBool::new(false), + overflow: S::OVERFLOW, + }); let input = StageInput { inbox: Arc::clone(&inbox) }; tokio::spawn(async move { + // Marks the stage stopped however the worker ends: drained and closed, or its handler + // panicked (the task's future is dropped as the panic unwinds). A waiting producer wakes + // and gets its input back instead of waiting on a slot nothing will take. + let _stops = StopsOnExit(Arc::clone(&inbox)); loop { let (next, closed) = { let mut pending = inbox.pending.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned slot still holds plain data, as in push (pending.take(), inbox.producers.load(Ordering::Acquire) == 0) }; match next { - Some(item) => stage.handle(item).await, + Some(item) => { + inbox.space.notify_one(); + stage.handle(item).await; + } None if closed => return, None => inbox.signal.notified().await, } @@ -104,3 +161,16 @@ pub fn spawn_stage(mut stage: S) -> StageInput { }); input } + +struct StopsOnExit(Arc>); + +impl Drop for StopsOnExit { + fn drop(&mut self) { + // Under the slot's lock, so a push either landed before (and is drained or dropped with + // the stage) or sees `stopped` and keeps its input. + let pending = self.0.pending.lock().unwrap_or_else(|e| e.into_inner()); // a poisoned slot still holds plain data, as in push + self.0.stopped.store(true, Ordering::Release); + drop(pending); + self.0.space.notify_waiters(); + } +} diff --git a/core/continuum-flow/src/tests.rs b/core/continuum-flow/src/tests.rs index 68d6e017ee..3e4a459903 100644 --- a/core/continuum-flow/src/tests.rs +++ b/core/continuum-flow/src/tests.rs @@ -209,12 +209,18 @@ async fn a_reliable_stage_never_drops_a_result_and_a_signal_stage_keeps_the_newe assert_eq!(results.push(1), Ok(0)); tokio::task::yield_now().await; // the worker takes 1 and waits on the gate assert_eq!(results.push(2), Ok(0)); - assert_eq!(results.push(3), Err(3), "full: the producer gets its result back, nothing is dropped"); - for _ in 0..2 { + assert_eq!(results.push(3), Err(crate::PushError::Full(3)), "full: push hands the result back, nothing is dropped"); + let waiting = results.clone(); + let sent = tokio::spawn(async move { waiting.send(3).await }); + tokio::task::yield_now().await; + assert!(!sent.is_finished(), "a reliable producer waits for the slot instead of spinning or dropping"); + for _ in 0..3 { gate.notify_one(); tokio::task::yield_now().await; + tokio::task::yield_now().await; } - assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2]); // test: plain data + assert_eq!(sent.await.expect("test: the sender task"), Ok(())); + assert_eq!(*got.lock().unwrap_or_else(|e| e.into_inner()), vec![1, 2, 3], "the awaited result is delivered"); // test: plain data let (seen, hold) = (Arc::new(Mutex::new(Vec::new())), Arc::new(tokio::sync::Notify::new())); let wakes = spawn_stage(Wakes(Arc::clone(&seen), Arc::clone(&hold))); @@ -274,3 +280,27 @@ async fn simultaneous_last_producers_close_and_drain_the_stage() { assert_eq!(seen, if queued { vec![1] } else { vec![] }); } } + +// what this catches (Cormac on #5729): a handler that panics leaving the stage looking full forever, +// so a waiting producer hangs and a pushing one retries a slot nothing will take. +#[tokio::test] +async fn a_stage_whose_handler_panicked_hands_inputs_back() { + struct Breaks; + impl Stage for Breaks { + type Input = u32; + const QOS: Qos = Qos::Work; + async fn handle(&mut self, input: u32) { + assert_ne!(input, 1, "test: the handler breaks on its first input"); + } + } + let stage = spawn_stage(Breaks); + assert_eq!(stage.push(1), Ok(0)); + for _ in 0..50 { + tokio::task::yield_now().await; + if stage.push(2) == Err(crate::PushError::Stopped(2)) { + break; + } + } + assert_eq!(stage.push(2), Err(crate::PushError::Stopped(2)), "a stopped stage keeps nothing"); + assert_eq!(stage.send(3).await, Err(crate::Stopped(3)), "a sender gets its input back instead of waiting"); +}