diff --git a/core/continuum-cognition/src/cognition/deferred_faculty.rs b/core/continuum-cognition/src/cognition/deferred_faculty.rs index 536073d2d5..92317c809b 100644 --- a/core/continuum-cognition/src/cognition/deferred_faculty.rs +++ b/core/continuum-cognition/src/cognition/deferred_faculty.rs @@ -7,15 +7,16 @@ //! last-good result (reprojected forward via feature-history). This is the //! cognition analog, at the faculty layer. //! -//! A [`DeferredFaculty`] wraps an inner [`Faculty`] so that the inner's -//! expensive work runs on its **own** `tokio` task, while the hot-path -//! `contribute()` is non-blocking: +//! A [`DeferredFaculty`] wraps an inner [`Faculty`] as a stage on the kernel's stage runner +//! (`continuum_kernel::runtime::stage`, the M0 stage contract): the inner's expensive work runs +//! on the stage's **own** task, while the hot-path `contribute()` is non-blocking: //! -//! 1. `contribute()` publishes the current world at the background task through a -//! `watch` channel (always-latest, never blocks, never drops the newest), and -//! 2. returns the inner faculty's **most recent finding** from another `watch` -//! snapshot — already stamped with the (possibly older) [`CycleId`] it was -//! computed against — or `None` until the first compute lands. +//! 1. `contribute()` submits the current world to the stage (latest wins, never blocks, +//! never drops the newest), and +//! 2. returns the stage's **most recent published finding** — stamped with the (possibly +//! older) [`CycleId`] it was computed against, published under the stage contract's rule +//! that an output from older input never replaces a newer one — or `None` until the first +//! run lands. //! //! So a slow faculty sits in the SAME `faculties` Vec as the fast ones and the //! per-tick `join_all` barrier in [`WorkspaceCycle::run_in_room`] never waits on @@ -31,33 +32,24 @@ //! every tick; the slow lane lands late, honestly stamped, and is merged in //! rather than blocking the spoken turn. //! -//! Conforms to `docs/architecture/CONCURRENCY-STYLE-GUIDE.md`: own `tokio::spawn` -//! task, `catch_unwind` around the loop body, `watch` for state in BOTH -//! directions (no `Arc` across `await`), event-triggered (not a -//! sleep-loop), and a quarantine after repeated inner panics. +//! The concurrency discipline (own task, `catch_unwind` around each run, `watch` in both +//! directions, event-triggered, quarantine after repeated panics) is the stage runner's, once, +//! for every stage. use std::sync::Arc; use async_trait::async_trait; -use futures_util::FutureExt; -use tokio::sync::watch; +use continuum_kernel::runtime::stage::{ + Cost, ExecutionCost, InputRevision, MindId, Provenance, Ran, ResidencyCost, RunOutcome, Stage, + StageContext, StageId, StageIncarnation, StageRunner, TopicName, Triggers, +}; use uuid::Uuid; use crate::cognition::workspace::{Contribution, CycleId, Faculty, FacultyId, Workspace}; -/// The slice of world-state the background task recomputes against. Carried -/// through a `watch` so the hot path always overwrites with the latest (no -/// backlog, no dropped-newest) and the worker chews the freshest burst it can. -#[derive(Debug, Clone)] -struct DeferredInput { - world_state: String, - room_id: Uuid, - activity_room_id: Uuid, - /// The cycle this input belongs to — the worker stamps its finding with it, - /// so a finding always carries the moment it reasoned about, not the moment - /// it finished. - cycle: CycleId, -} +/// The topic a deferred faculty reads: the world as of a cycle (a replaceable snapshot; only the +/// newest matters, and its revision is the cycle). +const WORLD: TopicName = TopicName("cognition.world"); /// A finding tagged with both wake and resolved activity rooms so /// the hot path can refuse to serve it into a DIFFERENT room. This is the @@ -73,134 +65,111 @@ pub(crate) struct StampedFinding { contribution: Contribution, } -/// A faculty whose inner work is taken off the cognition hot path (see module -/// docs). Drops the background task when dropped. -pub struct DeferredFaculty { - id: FacultyId, - /// Hot path reads the inner faculty's last-good finding here, lock-free. - latest: watch::Receiver>, - /// Hot path pushes the current world here for the worker to recompute against. - world_tx: watch::Sender>, - /// The wrapped faculty, retained for the DIRECTED-turn bypass: an addressed - /// question runs the inner faculty SYNCHRONOUSLY on ITS OWN burst (the - /// orienting response — acute stimulus interrupts), because the deferred - /// lane structurally serves the PREVIOUS turn's finding, so an acute - /// question could never benefit from its own recall (glass-boxed live - /// 2026-07-10: the fact surfaced at z=5.5σ one turn too late; the rendered - /// prompt had no [recall]; she confabulated "port 3001" and her peer - /// absorbed it as shared truth). Ambient turns keep the cheap lane. +/// A perception faculty as a stage: its input is the world as of a cycle, its output the finding +/// stamped with the cycle and rooms it reasoned about. +struct FacultyStage { inner: Arc, - /// The cold-start self-warm's publish handle: the FIRST tick's synchronous - /// finding lands in `latest` through this, so subsequent ambient ticks - /// serve it as last-good instead of re-paying the synchronous cost until - /// the background worker's first publish. - warm_tx: watch::Sender>, - /// Owns the worker task so it's aborted when this faculty is dropped — no - /// orphaned compute outliving the mind it served. - _worker: DropGuard, + id: StageId, } -/// Aborts the held task on drop. Keeps the worker's lifetime tied to the faculty. -struct DropGuard(tokio::task::JoinHandle<()>); -impl Drop for DropGuard { - fn drop(&mut self) { - self.0.abort(); +#[async_trait] +impl Stage for FacultyStage { + type Input = Workspace; + type Output = Option; + + fn id(&self) -> StageId { + self.id + } + + fn triggers(&self) -> Triggers { + Triggers { + inputs: vec![WORLD], + ..Triggers::default() + } + } + + fn cost(&self, _revisions: &[InputRevision]) -> Cost { + Cost { + execution: ExecutionCost::Cpu { measured: None }, + residency: ResidencyCost::default(), + } + } + + async fn run( + &self, + ctx: &StageContext, + ws: &Workspace, + revisions: &[InputRevision], + ) -> RunOutcome> { + let finding = self.inner.contribute(ws).await.map(|mut c| { + // Stamp with the cycle it reasoned against AND the room it reasoned about: the late + // finding carries its own moment and its own place, so the hot path can refuse to + // serve it into a different context. + c.cycle = ws.cycle; + StampedFinding { + room_id: ws.room_id, + activity_room_id: ws.activity_room_id, + contribution: c, + } + }); + RunOutcome::Produced(vec![( + finding, + Provenance { + by: ctx.run, + from: revisions.to_vec(), + }, + )]) } } -/// After this many consecutive inner panics the worker stops recomputing and the -/// faculty just serves its last-good (or `None`) — a bad backend degrades the -/// lane to stale, it never crashes the mind. Matches the guide's quarantine -/// discipline (the monitor's 3-strike rule). -const QUARANTINE_AFTER: u32 = 3; +/// The input revision a workspace is: the world as of its cycle. +fn world_revision(ws: &Workspace) -> Vec { + vec![InputRevision { + topic: WORLD, + through: ws.cycle.0, + }] +} + +/// A faculty whose inner work is taken off the cognition hot path (see module docs): the inner +/// faculty runs as a stage on the kernel's stage runner (own task, latest-wins input, the +/// publication rule, panic quarantine), and the hot path reads its last published finding. +pub struct DeferredFaculty { + id: FacultyId, + runner: StageRunner, +} impl DeferredFaculty { - /// Wrap `inner` and spawn its background worker. The inner faculty must be a - /// **perception-tier** faculty (`reacts_to_broadcast() == false`): the worker - /// reconstructs a minimal [`Workspace`] from the raw world-state, with an - /// empty broadcast, so a deliberation-tier inner (which reads the assembled - /// broadcast) would run blind. We force `reacts_to_broadcast() == false` on - /// the wrapper to keep it in the perception phase regardless. + /// Wrap `inner` and start its stage. The inner faculty must be a **perception-tier** + /// faculty (`reacts_to_broadcast() == false`): background runs see a minimal [`Workspace`] + /// rebuilt from the raw world-state, with an empty broadcast, so a deliberation-tier inner + /// (which reads the assembled broadcast) would run blind. The wrapper reports + /// `reacts_to_broadcast() == false` to keep it in the perception phase regardless. pub fn spawn(inner: Arc) -> Self { let id = inner.id(); - let (world_tx, mut world_rx) = watch::channel::>(None); - let (latest_tx, latest) = watch::channel::>(None); - let warm_tx = latest_tx.clone(); - - let inner_for_hot_path = Arc::clone(&inner); - let worker = tokio::spawn(async move { - let mut consecutive_panics: u32 = 0; - // Event-triggered, not a sleep-loop: wake only when the hot path - // publishes a new world. `changed()` skips the initial sentinel. - while world_rx.changed().await.is_ok() { - if consecutive_panics >= QUARANTINE_AFTER { - // Quarantined: stop recomputing, keep the last-good. Draining - // the receiver here would spin; just stop reacting. - break; - } - // Take the freshest burst (watch already coalesced to latest). - let Some(input) = world_rx.borrow_and_update().clone() else { - continue; // no published burst yet - }; - if input.cycle == CycleId::UNSTAMPED { - continue; // sentinel / not a real burst - } - // A real burst always carries a real room (#425 — the sentinel was - // already skipped above). If a nil somehow arrives, skip the tick and - // say so: this lane degrades, it never panics (concurrency guide). - let Ok(room) = crate::identity::ActivityRoom::from_uuid(input.room_id) else { - continuum_base::probe!( - class = "cognition.deferred.roomless_input_skipped", - "deferred faculty received a nil-room input — tick skipped (#425)", - ); - continue; - }; - let mut ws = Workspace::from_burst(crate::cognition::workspace::Burst::raw_in( - room, - input.world_state, - )) - .with_cycle(input.cycle); - ws.activity_room_id = input.activity_room_id; - - // The inner faculty's contribute is async (real inference/IPC). - // Catch a panic so a flawed backend degrades the lane to stale, - // never kills the runtime (guide: catch_unwind around the body). - let outcome = AssertUnwindSafeFut(inner.contribute(&ws)) - .catch_unwind() - .await; - - match outcome { - Ok(finding) => { - consecutive_panics = 0; - // Stamp with the cycle it reasoned against AND the room it - // reasoned about — the late finding carries its own moment - // (cycle) and its own place (room), so the hot path can - // refuse to serve it into a different context. - let stamped = finding.map(|mut c| { - c.cycle = input.cycle; - StampedFinding { - room_id: room.as_uuid(), - activity_room_id: input.activity_room_id, - contribution: c, - } - }); - // Ignore send error: no receivers left = faculty dropped. - let _ = latest_tx.send(stamped); - } - Err(_) => { - consecutive_panics += 1; - } - } - } - }); - + let stage = FacultyStage { + id: StageId::named(&format!("deferred.{}", id.as_str())), + inner, + }; + let incarnation = StageIncarnation { + stage: stage.id, + mind: MindId(Uuid::nil()), + epoch: 0, + }; Self { id, - warm_tx, - latest, - world_tx, - inner: inner_for_hot_path, - _worker: DropGuard(worker), + runner: StageRunner::spawn(Arc::new(stage), incarnation), + } + } + + /// Run the inner faculty on this workspace now, under the stage's publication rule. + async fn run_now(&self, ws: &Workspace) -> Option { + match self.runner.run_inline(ws, &world_revision(ws)).await { + Ran::Produced { accepted, .. } => accepted + .into_iter() + .flatten() + .next() + .map(|found| found.contribution), + _ => None, } } } @@ -226,16 +195,9 @@ impl Faculty for DeferredFaculty { // outcome — glass-boxed 2026-07-10: a directed silver-harbor question // 30s after boot produced NO recall bid and the seam was dark; whether // the inner ran-and-found-nothing vs never-ran was unattributable. - let found = self.inner.contribute(ws).await; - if let Some(c) = &found { - // A directed run's fresh finding seeds last-good too — the next - // ambient tick serves it non-blocking instead of a cold miss. - let _ = self.warm_tx.send(Some(StampedFinding { - room_id: ws.room_id, - activity_room_id: ws.activity_room_id, - contribution: c.clone(), - })); - } + // A directed run's fresh finding is published as last-good too: the next ambient + // tick serves it non-blocking instead of a cold miss. + let found = self.run_now(ws).await; continuum_base::probe!( class = "deferred.serve", faculty = %self.id.as_str(), @@ -245,23 +207,45 @@ impl Faculty for DeferredFaculty { ); return found; } - // Publish the current world for the worker (always-latest, never blocks). - // Ignore send error: worker gone = serve whatever last-good we have. - let _ = self.world_tx.send(Some(DeferredInput { - world_state: ws.world_state.clone(), - room_id: ws.room_id, - activity_room_id: ws.activity_room_id, - cycle: ws.cycle, - })); + // Hand the current world to the stage's background run (latest wins, never blocks). A + // real burst always carries a real room and a stamped cycle (#425); anything else is + // skipped here, said, and never submitted: this lane degrades, it never panics. + match crate::identity::ActivityRoom::from_uuid(ws.room_id) { + Ok(room) if ws.cycle != CycleId::UNSTAMPED => { + let mut minimal = Workspace::from_burst( + crate::cognition::workspace::Burst::raw_in(room, ws.world_state.clone()), + ) + .with_cycle(ws.cycle); + minimal.activity_room_id = ws.activity_room_id; + self.runner.submit(minimal, world_revision(ws)); + } + _ => continuum_base::probe!( + class = "cognition.deferred.roomless_input_skipped", + "deferred faculty received an unstamped or nil-room world — not submitted (#425)", + ), + } // Context guard: serve the last-good ONLY if it was computed for the room // the mind is in NOW, including its resolved activity. A different scope is // irrelevant — withhold it rather than inject a cross-context // memory into this turn. A same-room-but-stale finding is REPROJECTED // forward (slice 3, below); a different-room finding is simply not ours. let cold = { - let guard = self.latest.borrow(); - match guard.as_ref() { - Some(found) + // The outer Option is "has a run published?"; the inner is "did it find anything?". + // A published empty finding is WARM (Codex at d627b8af): it serves nothing, and never + // re-pays the synchronous cold start on every tick after an empty recall. + let published = self.runner.latest().map(|published| published.output); + match published.as_ref().map(Option::as_ref) { + Some(None) => { + continuum_base::probe!( + class = "deferred.serve", + faculty = %self.id.as_str(), + mode = "last-good-empty", + found = false, + "deferred lane served" + ); + return None; + } + Some(Some(found)) if found.room_id == ws.room_id && found.activity_room_id == ws.activity_room_id => { @@ -275,7 +259,7 @@ impl Faculty for DeferredFaculty { ); return served; } - Some(_) => { + Some(Some(_)) => { continuum_base::probe!( class = "deferred.serve", faculty = %self.id.as_str(), @@ -297,16 +281,9 @@ impl Faculty for DeferredFaculty { // faculty synchronously ONCE (the same move the orienting response // makes for directed turns); the bg worker takes over from tick 2. // Boot pays one slow first tick; the room keeps its continuity. - let found = self.inner.contribute(ws).await; - if let Some(c) = &found { - // Publish the warm finding as last-good so the NEXT ambient tick - // serves it non-blocking — the cold cost is paid exactly once. - let _ = self.warm_tx.send(Some(StampedFinding { - room_id: ws.room_id, - activity_room_id: ws.activity_room_id, - contribution: c.clone(), - })); - } + // The warm finding is published as last-good, so the NEXT ambient tick serves it + // non-blocking: the cold cost is paid exactly once. + let found = self.run_now(ws).await; continuum_base::probe!( class = "deferred.serve", faculty = %self.id.as_str(), @@ -427,24 +404,6 @@ fn lexical_relevance(finding: &str, current: &str) -> f32 { hits as f32 / f.len() as f32 } -/// `Future` adapter that asserts unwind-safety so an async body can be -/// `catch_unwind`'d. The captured `&Workspace` and `Arc` are only -/// read across the await, so this is sound for our use. -struct AssertUnwindSafeFut(F); -impl std::future::Future for AssertUnwindSafeFut { - type Output = F::Output; - fn poll( - self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll { - // SAFETY: structural pin projection of the single field; we never move it. - let inner = unsafe { self.map_unchecked_mut(|s| &mut s.0) }; - inner.poll(cx) - } -} -impl std::panic::UnwindSafe for AssertUnwindSafeFut {} -impl std::panic::RefUnwindSafe for AssertUnwindSafeFut {} - #[cfg(test)] mod tests { use super::*; @@ -472,6 +431,60 @@ mod tests { } } + /// A perception faculty that finds nothing, counting how often it ran. + struct EmptyRecall(std::sync::atomic::AtomicUsize); + #[async_trait] + impl Faculty for EmptyRecall { + fn id(&self) -> FacultyId { + FacultyId::Recall + } + async fn contribute(&self, _ws: &Workspace) -> Option { + // Counted at the END of a run that takes a while: an inline run has counted before + // contribute() returns; a background run cannot have finished by then. + tokio::time::sleep(std::time::Duration::from_millis(30)).await; + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + None + } + } + + // what this catches: a published EMPTY finding read as "never ran", so every ambient tick + // after an empty recall re-pays the synchronous cold start (Codex at d627b8af). The first + // tick runs inline once; later ambient ticks serve the warm empty without an inline run. + #[tokio::test] + async fn an_empty_recall_is_warm_and_never_repeats_the_cold_start() { + let inner = Arc::new(EmptyRecall(std::sync::atomic::AtomicUsize::new(0))); + let deferred = DeferredFaculty::spawn(Arc::clone(&inner) as Arc); + let room = Uuid::new_v4(); + assert!(deferred + .contribute(&Workspace::in_room("first", room).with_cycle(CycleId(1))) + .await + .is_none()); + assert_eq!( + inner.0.load(std::sync::atomic::Ordering::Relaxed), + 1, + "the cold start ran inline once" + ); + let mut published = deferred.runner.subscribe(); + for cycle in 2..5 { + let before = inner.0.load(std::sync::atomic::Ordering::Relaxed); + assert!(deferred + .contribute(&Workspace::in_room("again", room).with_cycle(CycleId(cycle))) + .await + .is_none()); + // Each ambient tick submits to the background run and returns at once: the inner + // count rises only when the background run lands, never inside contribute(). + assert_eq!( + inner.0.load(std::sync::atomic::Ordering::Relaxed), + before, + "no inline cold start on tick {cycle}" + ); + tokio::time::timeout(std::time::Duration::from_secs(2), published.changed()) + .await + .expect("test: the background run publishes") // test: the assertion failing loudly + .expect("test: the runner stays alive"); // test: the assertion failing loudly + } + } + // what this catches: a slow faculty wrapped as Deferred never blocks the hot // path — contribute() returns immediately with the last-good (None until the // first compute lands), and when the late finding arrives it carries the @@ -590,17 +603,11 @@ mod tests { let activity = Uuid::new_v4(); let mut original = Workspace::in_room("original activity", wake).with_cycle(CycleId(1)); original.activity_room_id = activity; - let mut completed = deferred.latest.clone(); - // Exercise the actual worker without a synchronous cold-start seed. + let mut completed = deferred.runner.subscribe(); + // Exercise the actual background run without a synchronous cold-start seed. deferred - .world_tx - .send(Some(DeferredInput { - world_state: original.world_state.clone(), - room_id: wake, - activity_room_id: activity, - cycle: original.cycle, - })) - .unwrap(); + .runner + .submit(original.clone(), world_revision(&original)); let mut switched = Workspace::in_room("new activity, same wake", wake).with_cycle(CycleId(2)); switched.activity_room_id = Uuid::new_v4(); diff --git a/core/continuum-kernel/src/runtime/mod.rs b/core/continuum-kernel/src/runtime/mod.rs index 786460fa92..8507874122 100644 --- a/core/continuum-kernel/src/runtime/mod.rs +++ b/core/continuum-kernel/src/runtime/mod.rs @@ -66,6 +66,7 @@ pub mod runtime; pub mod service_module; pub mod share_controller; pub mod shared_compute; +pub mod stage; pub mod storage_provider; pub mod params; diff --git a/core/continuum-kernel/src/runtime/stage/control.rs b/core/continuum-kernel/src/runtime/stage/control.rs new file mode 100644 index 0000000000..a7b9f7a2b9 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/control.rs @@ -0,0 +1,41 @@ +//! Control requests and the receipts that prove a stop. A request is not a stop: only a receipt +//! from the run's owner proves which stop happened. + +use super::identity::RunId; + +/// What a running stage may be asked to do at its next yield point. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ControlRequest { + Continue, + Pause, + Yield, + Cancel, +} + +/// Proof of a stop, owned by the task and runtime owner across a caller returning, a forgotten +/// handle and restart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StopReceipt { + /// Quiescent; its continuation is retained; execution and residency both stay charged. + Paused { run: RunId }, + /// Its continuation is retained; execution capacity was released; residency stays as named. + Yielded { + run: RunId, + residency_kept: super::cost::ResidencyCost, + }, + /// Terminal after quiescence; the effects it had already committed are recorded. + Cancelled { run: RunId, committed_effects: u64 }, + /// The request could not be honoured as asked; never a silent drop presented as a stop. + Refused { run: RunId, refusal: StopRefusal }, +} + +/// Why a stop request was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StopRefusal { + /// This stage, or the engine under it, cannot pause the same execution. + PauseUnsupported, + /// The run had already ended. + AlreadyTerminal, + /// The request came from a superseded incarnation. + StaleIncarnation, +} diff --git a/core/continuum-kernel/src/runtime/stage/cost.rs b/core/continuum-kernel/src/runtime/stage/cost.rs new file mode 100644 index 0000000000..cfa567293b --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/cost.rs @@ -0,0 +1,34 @@ +//! What a run costs. Execution and residency are separate claims on the one resource authority: +//! paused or yielded state still holds bytes after execution capacity is released. + +use std::time::Duration; + +/// The model tier a call needs; the resource authority maps it to a lane and a model. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ModelTier { + Small, + Mid, + Large, +} + +/// Executing: CPU time (its measured cost, `None` until measured: never claimed free, never a +/// guessed number) or a model call at a tier. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ExecutionCost { + Cpu { measured: Option }, + Model { tier: ModelTier }, +} + +/// Keeping state resident across a pause or yield: bytes that stay charged, by kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ResidencyCost { + pub host_bytes: u64, + pub device_bytes: u64, +} + +/// One run's claim: what executing costs, and what staying resident costs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Cost { + pub execution: ExecutionCost, + pub residency: ResidencyCost, +} diff --git a/core/continuum-kernel/src/runtime/stage/identity.rs b/core/continuum-kernel/src/runtime/stage/identity.rs new file mode 100644 index 0000000000..eba1187543 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/identity.rs @@ -0,0 +1,51 @@ +//! Who a stage is, which instance of it is running, and which run produced a result. + +use uuid::Uuid; + +/// A brain function's identity, stable across restarts and nodes: derived from its name, which +/// is kept beside it as an attribute, never parsed from it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct StageId(Uuid); + +impl StageId { + /// The one derivation: the same name yields the same id everywhere. + pub fn named(name: &str) -> Self { + Self(Uuid::new_v5( + &Uuid::NAMESPACE_OID, + format!("continuum.stage.{name}").as_bytes(), + )) + } + + pub fn as_uuid(self) -> Uuid { + self.0 + } +} + +/// The mind a stage serves. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct MindId(pub Uuid); + +/// One running instance of a stage for one mind. A new incarnation (restart, migration, +/// re-host) adopts the previous one's open obligations with a durable receipt and fences its +/// mutations; `epoch` orders incarnations of the same (stage, mind). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct StageIncarnation { + pub stage: StageId, + pub mind: MindId, + pub epoch: u64, +} + +impl StageIncarnation { + /// Whether `other` is a later incarnation of the same stage for the same mind: the one rule + /// that fences a stale incarnation's mutations. + pub fn is_superseded_by(&self, other: &StageIncarnation) -> bool { + self.stage == other.stage && self.mind == other.mind && other.epoch > self.epoch + } +} + +/// One run within an incarnation: what a dispatch, a stop receipt and an output are tied to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct RunId { + pub incarnation: StageIncarnation, + pub seq: u64, +} diff --git a/core/continuum-kernel/src/runtime/stage/mod.rs b/core/continuum-kernel/src/runtime/stage/mod.rs new file mode 100644 index 0000000000..c87d794547 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/mod.rs @@ -0,0 +1,31 @@ +//! The stage contract (M0): every brain function is a stage on one substrate. +//! +//! A stage declares its inputs (typed topics), its triggers, its cost (execution and residency, +//! claimed from the one resource authority) and its yield points; the substrate gives it +//! delivery, scheduling, fusion, interruption and capture once, for all stages +//! (docs/architecture/STAGE-CONTRACT.md, THE-WHOLE-MIND §1b). +//! +//! This module owns the contract's types and the pure rules every stage shares (identity, +//! provenance, the publication compare-and-set). The task lifetime and delivery owner and the +//! resource authority implement their halves behind these types. + +mod control; +mod cost; +mod identity; +mod publication; +mod runner; +mod stage; +mod topic; +mod triggers; + +pub use control::{ControlRequest, StopReceipt, StopRefusal}; +pub use cost::{Cost, ExecutionCost, ModelTier, ResidencyCost}; +pub use identity::{MindId, RunId, StageId, StageIncarnation}; +pub use publication::{Publication, Published}; +pub use runner::{PublishedOutput, PublishedState, Ran, StageRunner}; +pub use stage::{RunOutcome, Stage, StageContext}; +pub use topic::{InputRevision, Provenance, TopicKind, TopicName}; +pub use triggers::Triggers; + +#[cfg(test)] +mod tests; diff --git a/core/continuum-kernel/src/runtime/stage/publication.rs b/core/continuum-kernel/src/runtime/stage/publication.rs new file mode 100644 index 0000000000..c5d9a2603e --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/publication.rs @@ -0,0 +1,40 @@ +//! The publication rule: within one incarnation, an output derived from older input never +//! overwrites state derived from newer input (overlapping runs, a late result). + +use std::collections::BTreeMap; + +use super::topic::{InputRevision, TopicName}; + +/// The input revisions the currently published state was derived from, per topic. +#[derive(Debug, Clone, Default)] +pub struct Publication { + derived_from: BTreeMap, +} + +/// What an attempt to publish did. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Published { + /// The output's inputs are at least as new as the published state's on every topic: it is + /// now the published state. + Accepted, + /// Some topic it read is older than what the published state already reflects: refused. + Stale, +} + +impl Publication { + /// Compare and set: publish only if no topic the output read is behind the published state. + pub fn try_publish(&mut self, from: &[InputRevision]) -> Published { + let behind = from.iter().any(|input| { + self.derived_from + .get(&input.topic) + .is_some_and(|&published| input.through < published) + }); + if behind { + return Published::Stale; + } + for input in from { + self.derived_from.insert(input.topic, input.through); + } + Published::Accepted + } +} diff --git a/core/continuum-kernel/src/runtime/stage/runner.rs b/core/continuum-kernel/src/runtime/stage/runner.rs new file mode 100644 index 0000000000..68a67a03d5 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/runner.rs @@ -0,0 +1,261 @@ +//! One stage, run on its own task: the machinery every stage gets once (own task, latest-wins +//! input, provenance on every output, the publication compare-and-set, panic quarantine), moved +//! here from the cognition deferred lane. +//! +//! Scope, deliberately narrow (Codex at f5611b59): this runner serves SELF-CONTAINED stages, +//! whose run produces outputs and leaves no work behind it (recall). It is not the lifetime +//! owner of dispatched work: a run returning [`RunOutcome::Dispatched`] is a contract violation +//! here, said and counted, until the task owner's registration and completion interface exists +//! (Codex's seam). Dropping the runner aborts its task with no quiescence receipt, which is +//! honest only for stages with no committed effects. It accepts no control requests yet: a +//! request is observable control only once its receipt reaches the task owner. +//! +//! Conforms to the concurrency style guide: own `tokio::spawn` task, `catch_unwind` around every +//! run (background and inline alike), `watch` channels (no lock held across an await), +//! event-triggered by input changes (never a sleep loop), and a quarantine after repeated panics. + +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::Arc; + +use futures_util::FutureExt; +use tokio::sync::watch; + +use super::control::{ControlRequest, StopReceipt}; +use super::identity::{RunId, StageIncarnation}; +use super::publication::{Publication, Published}; +use super::stage::{RunOutcome, Stage, StageContext}; +use super::topic::{InputRevision, Provenance}; + +/// After this many consecutive panics a stage stops running and keeps serving its last +/// published output: a bad backend degrades the stage to stale, it never takes the mind down +/// (moved unchanged from the cognition deferred lane; the monitor's three-strike rule). +const QUARANTINE_AFTER: u32 = 3; + +/// An input handed to the stage, with the revisions that say exactly which versions it is. +#[derive(Clone)] +struct Submitted { + input: I, + revisions: Vec, +} + +/// The latest output the stage published, with its provenance. +#[derive(Debug, Clone, PartialEq)] +pub struct PublishedOutput { + pub output: O, + pub provenance: Provenance, +} + +/// What a stage has published: the compare-and-set state and the visible output, held in ONE +/// watch value so accepting a revision and replacing the output are one critical section (the +/// watch's own lock). Two publishers can never accept in one order and become visible in the +/// other. +#[derive(Debug, Clone)] +pub struct PublishedState { + publication: Publication, + pub latest: Option>, +} + +/// What one run did, typed, for the caller (inline) or the last-outcome watch (background). +#[derive(Debug, Clone, PartialEq)] +pub enum Ran { + /// Outputs the publication rule accepted, and how many it refused as older than published. + Produced { + accepted: Vec, + refused: usize, + }, + Idle, + Stopped(StopReceipt), + /// The run panicked; `consecutive` counts toward the quarantine. + Panicked { + consecutive: u32, + }, + /// Quarantined: the stage did not run, and serves its last published output. + Quarantined, + /// The run handed work to the task layer, which this runner cannot own (see module docs). + DispatchedUnowned, +} + +/// What the background task and an inline run share: one stage, one run sequence, one panic +/// count, one published state. +struct Shared { + stage: Arc, + incarnation: StageIncarnation, + seq: AtomicU64, + panics: AtomicU32, + published: watch::Sender>, + last_run: watch::Sender)>>, + control: watch::Receiver, +} + +impl Shared { + /// Run once under the panic boundary and quarantine, publish what it produced, and record + /// the outcome. The one path both the background task and an inline caller take. + async fn run_once(&self, input: &S::Input, revisions: &[InputRevision]) -> Ran { + if self.panics.load(Ordering::Acquire) >= QUARANTINE_AFTER { + return Ran::Quarantined; + } + let seq = self.seq.fetch_add(1, Ordering::Relaxed) + 1; + let run = RunId { + incarnation: self.incarnation, + seq, + }; + let ctx = StageContext { + run, + control: self.control.clone(), + }; + let caught = std::panic::AssertUnwindSafe(self.stage.run(&ctx, input, revisions)) + .catch_unwind() + .await; + let ran = match caught { + Err(_) => { + let consecutive = self.panics.fetch_add(1, Ordering::AcqRel) + 1; + continuum_base::probe!( + class = "stage.run.panicked", + stage = %self.incarnation.stage.as_uuid(), + consecutive = consecutive as u64, + "a stage run panicked; at the quarantine count it stops and serves its last good" + ); + Ran::Panicked { consecutive } + } + Ok(outcome) => { + self.panics.store(0, Ordering::Release); + match outcome { + RunOutcome::Produced(outputs) => self.publish(outputs), + RunOutcome::Idle => Ran::Idle, + RunOutcome::Stopped(receipt) => Ran::Stopped(receipt), + RunOutcome::Dispatched => { + continuum_base::probe!( + class = "stage.run.dispatched_unowned", + stage = %self.incarnation.stage.as_uuid(), + "a stage dispatched work through a runner that cannot own it (task owner interface pending)" + ); + Ran::DispatchedUnowned + } + } + } + }; + self.last_run + .send_replace(Some((run, ran.without_outputs()))); + ran + } + + /// Publish each output under the compare-and-set, atomically with making it visible. + fn publish(&self, outputs: Vec<(S::Output, Provenance)>) -> Ran { + let (mut accepted, mut refused) = (Vec::new(), 0); + for (output, provenance) in outputs { + self.published.send_if_modified(|state| { + let fresh = state.publication.try_publish(&provenance.from) == Published::Accepted; + if fresh { + accepted.push(output.clone()); + state.latest = Some(PublishedOutput { output, provenance }); + } else { + refused += 1; + } + fresh + }); + } + Ran::Produced { accepted, refused } + } +} + +impl Ran { + fn without_outputs(&self) -> Ran<()> { + match self { + Ran::Produced { accepted, refused } => Ran::Produced { + accepted: vec![(); accepted.len()], + refused: *refused, + }, + Ran::Idle => Ran::Idle, + Ran::Stopped(receipt) => Ran::Stopped(receipt.clone()), + Ran::Panicked { consecutive } => Ran::Panicked { + consecutive: *consecutive, + }, + Ran::Quarantined => Ran::Quarantined, + Ran::DispatchedUnowned => Ran::DispatchedUnowned, + } + } +} + +/// A running self-contained stage. Dropping it aborts its background task (see module docs). +pub struct StageRunner { + shared: Arc>, + input_tx: watch::Sender>>, + task: tokio::task::JoinHandle<()>, +} + +impl Drop for StageRunner { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl StageRunner { + /// Start `stage` as `incarnation` on its own task. + pub fn spawn(stage: Arc, incarnation: StageIncarnation) -> Self { + let (input_tx, mut input_rx) = watch::channel::>>(None); + let (published, _) = watch::channel(PublishedState { + publication: Publication::default(), + latest: None, + }); + let (last_run, _) = watch::channel(None); + // No control requests are accepted yet (module docs); every run sees Continue. + let (_control_tx, control) = watch::channel(ControlRequest::Continue); + let shared = Arc::new(Shared { + stage, + incarnation, + seq: AtomicU64::new(0), + panics: AtomicU32::new(0), + published, + last_run, + control, + }); + let worker = Arc::clone(&shared); + let task = tokio::spawn(async move { + while input_rx.changed().await.is_ok() { + let Some(submitted) = input_rx.borrow_and_update().clone() else { + continue; + }; + worker + .run_once(&submitted.input, &submitted.revisions) + .await; + } + }); + Self { + shared, + input_tx, + task, + } + } + + /// Hand the stage a new input for its background task (latest wins: an input it has not + /// started yet is replaced). + pub fn submit(&self, input: S::Input, revisions: Vec) { + let _ = self.input_tx.send(Some(Submitted { input, revisions })); // a send fails only once the task ended, which drop already stopped + } + + /// Run the stage now, in the caller's task, on the same path as the background task (run + /// sequence, panic boundary, quarantine, publication rule): for a caller that must have this + /// input's result before it goes on (an addressed turn's orienting response, a cold start). + pub async fn run_inline( + &self, + input: &S::Input, + revisions: &[InputRevision], + ) -> Ran { + self.shared.run_once(input, revisions).await + } + + /// The latest published output, with provenance; `None` until the first lands. + pub fn latest(&self) -> Option> { + self.shared.published.borrow().latest.clone() + } + + /// A receiver that wakes when a new output is published. + pub fn subscribe(&self) -> watch::Receiver> { + self.shared.published.subscribe() + } + + /// The last run's typed outcome (outputs elided), from either path. + pub fn last_run(&self) -> Option<(RunId, Ran<()>)> { + self.shared.last_run.borrow().clone() + } +} diff --git a/core/continuum-kernel/src/runtime/stage/stage.rs b/core/continuum-kernel/src/runtime/stage/stage.rs new file mode 100644 index 0000000000..0a50ec936e --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/stage.rs @@ -0,0 +1,56 @@ +//! The trait every brain function implements, and what a run can return. + +use async_trait::async_trait; + +use super::control::{ControlRequest, StopReceipt}; +use super::cost::Cost; +use super::identity::{RunId, StageId}; +use super::topic::{InputRevision, Provenance}; +use super::triggers::Triggers; + +/// What the substrate hands a run: its identity and the control requests it checks at its yield +/// points. The authorized capability for its admitted execution and residency is added by the +/// resource authority's half of the contract. +pub struct StageContext { + pub run: RunId, + pub control: tokio::sync::watch::Receiver, +} + +impl StageContext { + /// The request to honour at this yield point. + pub fn requested(&self) -> ControlRequest { + *self.control.borrow() + } +} + +/// What one run produced. +#[derive(Debug)] +pub enum RunOutcome { + /// Outputs to publish under the publication rule, each with its provenance. + Produced(Vec<(O, Provenance)>), + /// Work handed to the task owner; its completion re-triggers the stage. + Dispatched, + /// Nothing to do for these inputs. + Idle, + /// Stopped at a yield point; the receipt proves which stop. + Stopped(StopReceipt), +} + +/// A brain function on the substrate. Long work is a task (the shared task owner) whose +/// completion re-triggers the stage. +#[async_trait] +pub trait Stage: Send + Sync + 'static { + /// The typed payload a run reads (a snapshot it was handed, or a page drained from an event + /// topic); its revisions say exactly which versions it is. + type Input: Send + Sync + Clone + 'static; + type Output: Send + Sync + Clone + 'static; + fn id(&self) -> StageId; + fn triggers(&self) -> Triggers; + fn cost(&self, revisions: &[InputRevision]) -> Cost; + async fn run( + &self, + ctx: &StageContext, + input: &Self::Input, + revisions: &[InputRevision], + ) -> RunOutcome; +} diff --git a/core/continuum-kernel/src/runtime/stage/tests.rs b/core/continuum-kernel/src/runtime/stage/tests.rs new file mode 100644 index 0000000000..3452c3cd01 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/tests.rs @@ -0,0 +1,385 @@ +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use uuid::Uuid; + +use super::*; + +fn incarnation(epoch: u64) -> StageIncarnation { + StageIncarnation { + stage: StageId::named("recall"), + mind: MindId(Uuid::from_u128(7)), + epoch, + } +} + +fn rev(topic: &'static str, through: u64) -> InputRevision { + InputRevision { + topic: TopicName(topic), + through, + } +} + +// what this catches: a stage id that differs across restarts or nodes (an id parsed from or +// randomised at startup), which would break adoption of an old incarnation's obligations. +#[test] +fn a_stage_id_is_the_same_wherever_its_name_is() { + assert_eq!(StageId::named("recall"), StageId::named("recall")); + assert_ne!(StageId::named("recall"), StageId::named("reflex")); +} + +// what this catches: a stale incarnation mutating after a newer one took over, and a fence +// that wrongly crosses stages or minds. +#[test] +fn only_a_later_incarnation_of_the_same_stage_and_mind_supersedes() { + assert!(incarnation(1).is_superseded_by(&incarnation(2))); + assert!(!incarnation(2).is_superseded_by(&incarnation(1))); + assert!(!incarnation(1).is_superseded_by(&incarnation(1))); + let other_mind = StageIncarnation { + mind: MindId(Uuid::from_u128(8)), + ..incarnation(9) + }; + assert!(!incarnation(1).is_superseded_by(&other_mind)); +} + +// what this catches: triggers that choose one condition instead of composing (a stage with an +// input AND a completion AND a floor must wake on any of them), and a floor that fires early. +#[test] +fn triggers_compose_and_the_floor_is_only_a_floor() { + let t = Triggers { + inputs: vec![TopicName("perception")], + completions: true, + floor: Some(Duration::from_secs(60)), + }; + assert!(t.fires(&[TopicName("perception")], false, Duration::ZERO)); + assert!(t.fires(&[], true, Duration::ZERO)); + assert!(t.fires(&[], false, Duration::from_secs(60))); + assert!(!t.fires(&[TopicName("board")], false, Duration::from_secs(59))); +} + +// what this catches: a late or overlapping run overwriting state derived from newer input +// (both ways: newer input publishes, older is refused, an unrelated topic is independent). +#[test] +fn an_output_from_older_input_never_overwrites_newer_state() { + let mut published = Publication::default(); + assert_eq!( + published.try_publish(&[rev("perception", 10)]), + Published::Accepted + ); + assert_eq!( + published.try_publish(&[rev("perception", 9)]), + Published::Stale + ); + assert_eq!( + published.try_publish(&[rev("perception", 12), rev("board", 3)]), + Published::Accepted + ); + assert_eq!( + published.try_publish(&[rev("perception", 12), rev("board", 2)]), + Published::Stale + ); + assert_eq!( + published.try_publish(&[rev("board", 3)]), + Published::Accepted, + "equal input republishes" + ); +} + +/// A stage that does a unit of work per yield point and honours control at each. +struct Counting; + +#[async_trait] +impl Stage for Counting { + type Input = (); + type Output = u64; + fn id(&self) -> StageId { + StageId::named("counting") + } + fn triggers(&self) -> Triggers { + Triggers { + inputs: vec![TopicName("numbers")], + ..Triggers::default() + } + } + fn cost(&self, _input: &[InputRevision]) -> Cost { + Cost { + execution: ExecutionCost::Cpu { + measured: Some(Duration::from_millis(1)), + }, + residency: ResidencyCost::default(), + } + } + async fn run( + &self, + ctx: &StageContext, + _input: &(), + input: &[InputRevision], + ) -> RunOutcome { + for _ in 0..3 { + match ctx.requested() { + ControlRequest::Continue => {} + ControlRequest::Yield => { + return RunOutcome::Stopped(StopReceipt::Yielded { + run: ctx.run, + residency_kept: ResidencyCost::default(), + }) + } + ControlRequest::Cancel => { + return RunOutcome::Stopped(StopReceipt::Cancelled { + run: ctx.run, + committed_effects: 0, + }) + } + ControlRequest::Pause => { + return RunOutcome::Stopped(StopReceipt::Refused { + run: ctx.run, + refusal: StopRefusal::PauseUnsupported, + }) + } + } + } + RunOutcome::Produced(vec![( + input.len() as u64, + Provenance { + by: ctx.run, + from: input.to_vec(), + }, + )]) + } +} + +// what this catches: a stage that ignores control at its yield points, and a pause the stage +// cannot honour being reported as paused instead of refused (both ways: it runs to completion +// when left alone, and stops with the right receipt when asked). +#[tokio::test] +async fn a_stage_honours_control_with_the_receipt_that_proves_it() { + let run = RunId { + incarnation: incarnation(1), + seq: 1, + }; + let input = [rev("numbers", 4)]; + let (tx, rx) = tokio::sync::watch::channel(ControlRequest::Continue); + let ctx = StageContext { run, control: rx }; + match Counting.run(&ctx, &(), &input).await { + RunOutcome::Produced(out) => assert_eq!( + out[0].1, + Provenance { + by: run, + from: input.to_vec() + } + ), + other => panic!("left alone it completes: {other:?}"), // test: the assertion failing loudly + } + tx.send(ControlRequest::Yield) + .expect("test: the receiver is alive"); // test: a fixture step that must succeed + assert!(matches!( + Counting.run(&ctx, &(), &input).await, + RunOutcome::Stopped(StopReceipt::Yielded { .. }) + )); + tx.send(ControlRequest::Pause) + .expect("test: the receiver is alive"); // test: a fixture step that must succeed + assert!(matches!( + Counting.run(&ctx, &(), &input).await, + RunOutcome::Stopped(StopReceipt::Refused { + refusal: StopRefusal::PauseUnsupported, + .. + }) + )); +} + +/// A stage that echoes its input, or panics when asked to. +struct Echo; + +#[async_trait] +impl Stage for Echo { + type Input = i64; + type Output = i64; + fn id(&self) -> StageId { + StageId::named("echo") + } + fn triggers(&self) -> Triggers { + Triggers { + inputs: vec![TopicName("numbers")], + ..Triggers::default() + } + } + fn cost(&self, _revisions: &[InputRevision]) -> Cost { + Cost { + execution: ExecutionCost::Cpu { + measured: Some(Duration::from_millis(1)), + }, + residency: ResidencyCost::default(), + } + } + async fn run( + &self, + ctx: &StageContext, + input: &i64, + revisions: &[InputRevision], + ) -> RunOutcome { + assert!(*input >= 0, "test: a negative input panics the run"); // test: the deliberate panic under test + RunOutcome::Produced(vec![( + *input, + Provenance { + by: ctx.run, + from: revisions.to_vec(), + }, + )]) + } +} + +async fn published(runner: &StageRunner, want: i64) -> PublishedOutput { + let mut sub = runner.subscribe(); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + if let Some(out) = sub.borrow_and_update().latest.clone() { + if out.output == want { + return out; + } + } + sub.changed().await.expect("test: the runner is alive"); // test: a fixture step that must succeed + } + }) + .await + .expect("test: the output is published in time") // test: the assertion failing loudly +} + +// what this catches: a stage's output landing without provenance, or a late output derived from +// older input replacing a newer one (the deferred lane's stale-finding guard, now the one rule). +#[tokio::test] +async fn the_runner_publishes_with_provenance_and_refuses_older_input() { + let runner = StageRunner::spawn(Arc::new(Echo), incarnation(1)); + runner.submit(5, vec![rev("numbers", 5)]); + let out = published(&runner, 5).await; + assert_eq!(out.provenance.from, vec![rev("numbers", 5)]); + assert_eq!(out.provenance.by.incarnation, incarnation(1)); + runner.submit(3, vec![rev("numbers", 3)]); // older input, arriving late + runner.submit(9, vec![rev("numbers", 9)]); + assert_eq!( + published(&runner, 9).await.provenance.from, + vec![rev("numbers", 9)] + ); + assert_eq!( + runner.latest().map(|o| o.output), + Some(9), + "the older input never replaced the newer" + ); +} + +// what this catches: a stage whose backend keeps failing taking the mind down, or losing its last +// good output; both ways: a panic is survived, and three in a row quarantine it on its last good. +#[tokio::test] +async fn a_panicking_stage_is_quarantined_on_its_last_good_output() { + let runner = StageRunner::spawn(Arc::new(Echo), incarnation(1)); + runner.submit(1, vec![rev("numbers", 1)]); + published(&runner, 1).await; + for (n, through) in [(-1, 2), (-2, 3), (-3, 4)] { + runner.submit(n, vec![rev("numbers", through)]); + tokio::time::sleep(Duration::from_millis(50)).await; + } + runner.submit(7, vec![rev("numbers", 5)]); + tokio::time::sleep(Duration::from_millis(100)).await; + assert_eq!( + runner.latest().map(|o| o.output), + Some(1), + "quarantined: serves its last good, runs no more" + ); +} + +// what this catches: a caller's inline run (an addressed turn's orienting response, a cold +// start) publishing around the one rule: it lands like a background run, and an inline run on +// input older than what is published is refused (both ways). +#[tokio::test] +async fn an_inline_run_publishes_under_the_same_rule() { + let runner = StageRunner::spawn(Arc::new(Echo), incarnation(1)); + assert_eq!( + runner.run_inline(&4, &[rev("numbers", 4)]).await, + Ran::Produced { + accepted: vec![4], + refused: 0 + } + ); + assert_eq!(runner.latest().map(|o| o.output), Some(4)); + assert_eq!( + runner.run_inline(&2, &[rev("numbers", 2)]).await, + Ran::Produced { + accepted: vec![], + refused: 1 + }, + "older input refused inline too, and the refusal is reported" + ); + assert_eq!(runner.latest().map(|o| o.output), Some(4)); + runner.submit(6, vec![rev("numbers", 6)]); + assert_eq!( + published(&runner, 6).await.provenance.by.seq, + 3, + "inline and background runs share one sequence" + ); +} + +// what this catches: the publication compare-and-set and the visible output separating, so two +// publishers accept in one order and become visible in the other (Codex at f5611b59). Many +// concurrent inline publishers in a fixed shuffled order: the visible output never moves +// backwards and ends on the newest input. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn concurrent_publishers_never_expose_an_older_output() { + let runner = Arc::new(StageRunner::spawn(Arc::new(Echo), incarnation(1))); + let mut watcher = runner.subscribe(); + let seen = tokio::spawn(async move { + let mut high = 0i64; + while watcher.changed().await.is_ok() { + let now = watcher + .borrow_and_update() + .latest + .as_ref() + .map_or(0, |o| o.output); + assert!( + now >= high, + "visible output moved backwards: {high} -> {now}" + ); + high = now; + if high == 200 { + break; + } + } + high + }); + let mut order: Vec = (1..=200).collect(); + order.reverse(); + order.rotate_left(73); + let runs: Vec<_> = order + .into_iter() + .map(|n| { + let runner = Arc::clone(&runner); + tokio::spawn(async move { runner.run_inline(&n, &[rev("numbers", n as u64)]).await }) + }) + .collect(); + for run in runs { + run.await.expect("test: a publisher task completes"); // test: a fixture step that must succeed + } + assert_eq!(runner.latest().map(|o| o.output), Some(200)); + let high = tokio::time::timeout(Duration::from_secs(2), seen) + .await + .expect("test: the watcher sees the newest in time"); // test: the assertion failing loudly + assert_eq!(high.expect("test: the watcher completes"), 200); // test: the assertion failing loudly +} + +// what this catches: an inline run escaping the panic boundary the background path has (Codex +// at f5611b59): an inline panic is caught, counts toward the one quarantine, and a quarantined +// stage refuses inline runs too. +#[tokio::test] +async fn an_inline_panic_is_caught_and_counts_toward_the_quarantine() { + let runner = StageRunner::spawn(Arc::new(Echo), incarnation(1)); + for (n, consecutive) in [(-1, 1), (-2, 2), (-3, 3)] { + assert_eq!( + runner.run_inline(&n, &[rev("numbers", 1)]).await, + Ran::Panicked { consecutive } + ); + } + assert_eq!( + runner.run_inline(&5, &[rev("numbers", 5)]).await, + Ran::Quarantined + ); + assert_eq!(runner.latest(), None, "nothing was ever published"); +} diff --git a/core/continuum-kernel/src/runtime/stage/topic.rs b/core/continuum-kernel/src/runtime/stage/topic.rs new file mode 100644 index 0000000000..5c8bc24f64 --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/topic.rs @@ -0,0 +1,30 @@ +//! What a stage reads, and the provenance of what it writes. + +use super::identity::RunId; + +/// A topic's routing name. Routing is by this header, never by reading a payload. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TopicName(pub &'static str); + +/// How a topic is read: every item of an event stream matters and is read through a cursor; only +/// the latest of a snapshot matters and is read by revision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TopicKind { + ReplayableEvents, + ReplaceableSnapshot, +} + +/// The exact input a run saw: a topic and the cursor or revision it read through, captured at +/// dispatch. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct InputRevision { + pub topic: TopicName, + pub through: u64, +} + +/// Which run produced an output, from which inputs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Provenance { + pub by: RunId, + pub from: Vec, +} diff --git a/core/continuum-kernel/src/runtime/stage/triggers.rs b/core/continuum-kernel/src/runtime/stage/triggers.rs new file mode 100644 index 0000000000..e278edd0bf --- /dev/null +++ b/core/continuum-kernel/src/runtime/stage/triggers.rs @@ -0,0 +1,23 @@ +//! When a stage runs. Triggers compose: a stage declares every condition that wakes it. + +use std::time::Duration; + +use super::topic::TopicName; + +/// The conditions that run a stage, together: an input topic moved, a task it dispatched +/// completed, and the never-comatose cadence floor (a floor, never the main trigger). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Triggers { + pub inputs: Vec, + pub completions: bool, + pub floor: Option, +} + +impl Triggers { + /// Whether any declared condition is met. + pub fn fires(&self, moved: &[TopicName], completed: bool, since_last_run: Duration) -> bool { + moved.iter().any(|topic| self.inputs.contains(topic)) + || (self.completions && completed) + || self.floor.is_some_and(|floor| since_last_run >= floor) + } +}