fix(daemon): run the long lanes off the tick path #7

Merged
vhaudiquet merged 1 commits from kosmos/rhema-claw:fix/forge-pass-off-tick into main 2026-11-22 01:44:39 +00:00
+200 -17
View File
@@ -22,6 +22,7 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration; use std::time::Duration;
use rhema_autonomous_agent::{Driver, Source, SourceError}; use rhema_autonomous_agent::{Driver, Source, SourceError};
@@ -150,6 +151,59 @@ pub fn forge_dispatch() -> DispatcherConfig {
} }
} }
/// Hands one driver pass to its own task, so a turn does not stop the
/// clock.
///
/// [`Driver::run_once`] awaits every run it admits, which is exactly right
/// for a cron pass and wrong for a resident: a forge turn clones a repo
/// and may build a slicer, a coding job runs a session — tens of minutes
/// either way — and everything else the loop does (detecting, and so
/// polling the forges, recording watch health, firing due tasks, reading
/// the calendar, delivering to the phone) waits behind it. With a 60s
/// tick and a ten-minute turn, the daemon polls once per turn.
///
/// One pass per lane at a time. `busy` is held for the pass's whole
/// duration, and a tick that finds it held leaves its events where they
/// are: the dispatcher's inbox is the queue, so nothing is dropped — the
/// next tick admits them. Starting a second pass anyway would only lose
/// lease acquisitions to the first and log the loss.
fn spawn_pass(driver: Arc<Driver>, label: &'static str, busy: Arc<AtomicBool>) {
if busy.swap(true, Ordering::AcqRel) {
return;
}
let held = BusyFlag(busy);
tokio::spawn(async move {
// Dropped however this task ends, a panic included: a lane whose
// flag never cleared would never run again.
let _held = held;
match driver.run_once().await {
Ok(outcomes) => {
let handled = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Handled))
.count();
let failed = outcomes
.iter()
.filter(|outcome| matches!(outcome, Outcome::Failed(_)))
.count();
if handled + failed > 0 {
eprintln!("[claw] {label} pass: {handled} handled, {failed} failed");
}
}
Err(err) => eprintln!("[claw] warning: {label} pass failed: {err}"),
}
});
}
/// Clears a lane's in-flight flag when its spawned pass ends.
struct BusyFlag(Arc<AtomicBool>);
impl Drop for BusyFlag {
fn drop(&mut self) {
self.0.store(false, Ordering::Release);
}
}
/// The resident daemon: the extension set's sources (the forge watches, /// The resident daemon: the extension set's sources (the forge watches,
/// the task scheduler, the coding jobs, the calendar reminders), the /// the task scheduler, the coding jobs, the calendar reminders), the
/// three drivers, and the HTTP surface. /// three drivers, and the HTTP surface.
@@ -166,6 +220,10 @@ pub struct Daemon {
forge_driver: Arc<Driver>, forge_driver: Arc<Driver>,
interactive_driver: Arc<Driver>, interactive_driver: Arc<Driver>,
jobs_driver: Arc<Driver>, jobs_driver: Arc<Driver>,
/// Whether a forge pass is running off the tick (see [`spawn_pass`]).
forge_pass_busy: Arc<AtomicBool>,
/// Whether a jobs pass is running off the tick.
jobs_pass_busy: Arc<AtomicBool>,
poll_interval: Duration, poll_interval: Duration,
listen: String, listen: String,
http: ClawState, http: ClawState,
@@ -477,6 +535,8 @@ impl Daemon {
forge_driver, forge_driver,
interactive_driver, interactive_driver,
jobs_driver, jobs_driver,
forge_pass_busy: Arc::new(AtomicBool::new(false)),
jobs_pass_busy: Arc::new(AtomicBool::new(false)),
// A zero poll interval would spin detect passes against the // A zero poll interval would spin detect passes against the
// forge API; one second is the floor. // forge API; one second is the floor.
poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)), poll_interval: Duration::from_secs(config.poll_interval_secs.max(1)),
@@ -522,19 +582,16 @@ impl Daemon {
Ok(()) Ok(())
} }
/// One pass: every source detects (due tasks first — a reminder is /// One pass, awaited to the end: every source detects (due tasks
/// the user-facing clock), the forge driver runs every key the /// first — a reminder is the user-facing clock), the forge driver
/// debounce released, and the interactive driver drains as a /// runs every key the debounce released, and the interactive driver
/// backstop — a message delivered live into a running turn waits at /// drains as a backstop. The shape a `--once` run and the tests
/// the key for a pass like this one. /// drive, where "the pass is over" has to mean the work is over.
///
/// The resident loop uses [`Daemon::resident_tick`] instead: same
/// detection, but the long lanes are not awaited.
pub async fn tick(&self) -> Result<TickReport, ClawError> { pub async fn tick(&self) -> Result<TickReport, ClawError> {
// The tick only detects — every timer here drives let detected = self.detect().await?;
// deterministic detection, and the set's order is the contract:
// due tasks before the calendar reminders that fire for them.
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
// A queued coding job starts before the forge pass: it is the // A queued coding job starts before the forge pass: it is the
// thing someone just asked for. // thing someone just asked for.
if let Err(err) = self.jobs_driver.run_once().await { if let Err(err) = self.jobs_driver.run_once().await {
@@ -554,6 +611,50 @@ impl Daemon {
"[claw] pass: {detected} event(s) detected, {handled} handled, {failed} failed" "[claw] pass: {detected} event(s) detected, {handled} handled, {failed} failed"
); );
} }
self.drain_interactive().await;
Ok(TickReport { detected, outcomes })
}
/// The resident loop's pass: the same detection, with the two lanes
/// whose runs last minutes or hours handed to their own tasks.
///
/// Detection is the part that must keep its cadence — the forge polls
/// and the health rows they write, the due tasks, the calendar
/// reminders, the phone delivery all ride it — and detection alone is
/// quick. Awaiting a turn inside it means every one of those timers
/// stops for as long as the turn runs. See [`spawn_pass`].
pub async fn resident_tick(&self) -> Result<(), ClawError> {
self.detect().await?;
// A queued coding job starts before the forge pass: it is the
// thing someone just asked for.
spawn_pass(
self.jobs_driver.clone(),
"jobs",
self.jobs_pass_busy.clone(),
);
spawn_pass(
self.forge_driver.clone(),
"forge",
self.forge_pass_busy.clone(),
);
self.drain_interactive().await;
Ok(())
}
/// Detection only: every source, in set order. The tick's order is
/// the contract — due tasks before the calendar reminders that fire
/// for them — and the sources carry it.
async fn detect(&self) -> Result<usize, ClawError> {
let mut detected = 0usize;
for source in &self.sources {
detected += source.detect().await?;
}
Ok(detected)
}
/// The interactive driver, drained as a backstop: a message delivered
/// live into a running turn waits at the key for a pass like this one.
async fn drain_interactive(&self) {
match self.interactive_driver.run_once().await { match self.interactive_driver.run_once().await {
Ok(runs) if !runs.is_empty() => { Ok(runs) if !runs.is_empty() => {
eprintln!("[claw] interactive: {} queued run(s) drained", runs.len()); eprintln!("[claw] interactive: {} queued run(s) drained", runs.len());
@@ -561,13 +662,13 @@ impl Daemon {
Ok(_) => {} Ok(_) => {}
Err(err) => eprintln!("[claw] warning: interactive pass failed: {err}"), Err(err) => eprintln!("[claw] warning: interactive pass failed: {err}"),
} }
Ok(TickReport { detected, outcomes })
} }
/// The resident loop: the HTTP surface comes up first (a resident is /// The resident loop: the HTTP surface comes up first (a resident is
/// talked to), then detect, run, sleep, until ctrl-c. A failed pass /// talked to), then detect, hand the long lanes to their own tasks,
/// is logged, not fatal — a forge outage or a dead backend must not /// sleep, until ctrl-c. A failed pass is logged, not fatal — a forge
/// end a daemon whose next pass may simply succeed. /// outage or a dead backend must not end a daemon whose next pass may
/// simply succeed.
pub async fn run(&self) -> Result<(), ClawError> { pub async fn run(&self) -> Result<(), ClawError> {
self.bootstrap().await?; self.bootstrap().await?;
let listener = tokio::net::TcpListener::bind(&self.listen).await?; let listener = tokio::net::TcpListener::bind(&self.listen).await?;
@@ -580,7 +681,7 @@ impl Daemon {
}); });
eprintln!("[claw] http listening on {addr}"); eprintln!("[claw] http listening on {addr}");
loop { loop {
if let Err(err) = self.tick().await { if let Err(err) = self.resident_tick().await {
eprintln!("[claw] warning: pass failed: {err}"); eprintln!("[claw] warning: pass failed: {err}");
} }
tokio::select! { tokio::select! {
@@ -615,6 +716,88 @@ pub async fn run_once(
mod tests { mod tests {
use super::*; use super::*;
/// A handler that holds its key until the test lets it go, and counts
/// the runs it served.
struct GatedHandler {
runs: std::sync::atomic::AtomicUsize,
started: tokio::sync::Semaphore,
release: tokio::sync::Semaphore,
}
#[rhema_autonomous_agent::async_trait]
impl rhema_autonomous_agent::Handler for GatedHandler {
async fn handle(&self, _ctx: &mut rhema_autonomous_agent::SessionContext) -> Outcome {
self.runs.fetch_add(1, Ordering::SeqCst);
self.started.add_permits(1);
let _ = self.release.acquire().await;
Outcome::Handled
}
}
/// A pass handed to its own task keeps the tick free, holds its lane
/// while it runs, and does not stack: a tick that fires mid-pass
/// leaves its events in the dispatcher's inbox for the next one.
#[tokio::test]
async fn a_spawned_pass_holds_its_lane_instead_of_stacking() {
let dispatcher = Arc::new(Dispatcher::new(
DispatcherConfig {
debounce_window_millis: 0,
..DispatcherConfig::default()
},
Arc::new(SystemClock),
Arc::new(rhema_rsd::VolatileStore::new()),
));
let handler = Arc::new(GatedHandler {
runs: std::sync::atomic::AtomicUsize::new(0),
started: tokio::sync::Semaphore::new(0),
release: tokio::sync::Semaphore::new(0),
});
// The dispatcher resolves an event's key through its source's key
// function; nothing ingests before its source is registered.
dispatcher.register_source(
"test",
Arc::new(|event: &rhema_rsd::Event| {
rhema_rsd::ResourceKey::from(format!("test:{}", event.id))
}),
);
let driver = Arc::new(Driver::new(dispatcher.clone(), handler.clone()));
dispatcher
.ingest(rhema_rsd::Event {
id: "e1".to_owned(),
source: "test".to_owned(),
payload: serde_json::json!({}),
received_at: 0,
})
.expect("event lands");
let busy = Arc::new(AtomicBool::new(false));
spawn_pass(driver.clone(), "test", busy.clone());
// The pass runs on its own task: the caller is already back, and
// the lane reads as held while the turn is under way.
tokio::time::timeout(Duration::from_secs(5), handler.started.acquire())
.await
.expect("the pass starts within five seconds")
.expect("the pass starts")
.forget();
assert!(
busy.load(Ordering::SeqCst),
"the lane is held for the whole pass"
);
spawn_pass(driver.clone(), "test", busy.clone());
handler.release.add_permits(1);
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while busy.load(Ordering::SeqCst) {
assert!(
tokio::time::Instant::now() < deadline,
"the flag clears when the pass ends"
);
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert_eq!(handler.runs.load(Ordering::SeqCst), 1, "one pass, not two");
}
#[test] #[test]
fn the_forge_dispatcher_leases_for_a_turn_not_a_step() { fn the_forge_dispatcher_leases_for_a_turn_not_a_step() {
let dispatch = forge_dispatch(); let dispatch = forge_dispatch();