diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index b3cdbce7..749b95ac 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1894,7 +1894,7 @@ mod tests { &vm, &crate::snapshot::Capture { code: CODE, - active_ms: 0, + active: std::time::Duration::ZERO, carried: Default::default(), }, ); diff --git a/rust/crates/psychoscript/src/cpu.rs b/rust/crates/psychoscript/src/cpu.rs index d3ff0c20..fc5bd0a9 100644 --- a/rust/crates/psychoscript/src/cpu.rs +++ b/rust/crates/psychoscript/src/cpu.rs @@ -17,16 +17,17 @@ use std::time::Duration; use crate::thread_clock::ThreadClock; use crate::time::Instant; -/// `Limits::slice_ms`: the stretch in progress. +/// `Limits::slice_ms`: the stretch in progress, or `wall: None` while the run waits on the host. /// -/// On the wall clock, `wall` is where it began, moved on by the host calls since, so its elapsed time is the -/// stretch's own. Under `Clock::ThreadCpu`, `wall` is where it began until `from` is read, once the stretch has run -/// `SLICE_SLACK` of the slice: the run's CPU time without host calls and with them (`CpuMeter::read`). The stretch is -/// measured from there, against the slice and, with host calls, `WAIT_BACKSTOP` times it; `wall` is then the -/// earliest it could be over either, as a thread uses no more CPU time than passes, and the clock isn't read before. +/// On the wall clock, `wall` is `Some(at)` where the stretch began, moved on by the host calls since, so its elapsed +/// time is the stretch's own. Under `Clock::ThreadCpu`, `wall` is `Some(at)` where it began until `from` is read, once +/// the stretch has run `SLICE_SLACK` of the slice: the run's CPU time without host calls and with them +/// (`CpuMeter::read`). The stretch is measured from there, against the slice and, with host calls, `WAIT_BACKSTOP` +/// times it; `wall` is then `Some(at)` for the earliest it could be over either, as a thread uses no more CPU time +/// than passes, and the clock isn't read before. While waiting on the host (`wall: None`), no stretch is in progress. pub(crate) struct Slice { pub(crate) from: Option<(Duration, Duration)>, - pub(crate) wall: Instant, + pub(crate) wall: Option, } /// What a run spent besides its active time, saved with its state so that a resume goes on from it rather than from @@ -151,22 +152,16 @@ impl CpuMeter { mark.wall = Instant::now(); } - /// The CPU time the run used, without host calls. - pub(crate) fn used(&mut self) -> Duration { - self.fold(); - self.used - } - /// The CPU time the run used, without host calls and with them. pub(crate) fn read(&mut self) -> (Duration, Duration) { self.fold(); (self.used, self.total) } - /// The CPU time the run used with host calls, and the wall-clock time it spent waiting on them. - pub(crate) fn spent(&mut self) -> (Duration, Duration) { + /// The CPU time the run used without host calls, with them, and the wall-clock time it spent waiting on them. + pub(crate) fn totals(&mut self) -> (Duration, Duration, Duration) { self.fold(); - (self.total, self.waited) + (self.used, self.total, self.waited) } /// Wall-clock time spent in a wait on the calling thread, which used no CPU time meanwhile. diff --git a/rust/crates/psychoscript/src/host.rs b/rust/crates/psychoscript/src/host.rs index 8d0c4210..457ed7a3 100644 --- a/rust/crates/psychoscript/src/host.rs +++ b/rust/crates/psychoscript/src/host.rs @@ -362,6 +362,15 @@ pub(crate) enum Queued { /// Starts the calls made since the last handover, in the order they were made: the reference hands its queued calls /// to the driver at every stop. pub fn launch(vm: &mut Vm) { + if vm.host.queued.is_empty() { + return; + } + let span = vm.host_span(); + launch_inner(vm); + vm.end_host_span(span); +} + +fn launch_inner(vm: &mut Vm) { for queued in std::mem::take(&mut vm.host.queued) { match queued { Queued::Call(p, f, r, holds) => spawn_call(vm, p, &f, *r, holds), @@ -1025,7 +1034,7 @@ fn call_host( // The run waits for the work: the reference's driver takes over, starting the calls queued so far. Returned::Block(work) => { vm.host.next_epoch(); - launch(vm); + launch_inner(vm); Returned::Now(block(vm, work)) } returned => returned, diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 096c3983..24e0af27 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -383,7 +383,7 @@ impl Program { } let capture = snapshot::Capture { code: &r.code, - active_ms: 0, + active: Duration::ZERO, carried: Default::default(), }; snapshot::capture(&r.vm, &capture).map_err(|refusal| refused(&r.vm, refusal)) @@ -510,7 +510,10 @@ impl Program { run::call_main(&mut r.vm); } } - for (p, s) in r.vm.host.tasks.poll_ready() { + let span = r.vm.host_span(); + let ready = r.vm.host.tasks.poll_ready(); + r.vm.end_host_span(span); + for (p, s) in ready { r.vm.host.settled(p); if let crate::host::Settlement::Interrupted = s { crate::host::interrupt(&mut r.vm); @@ -695,14 +698,13 @@ impl Program { r.skip -= 1; return None; } - let used = r.vm.time_used(); - let active_ms = used.max(r.active_before).as_millis() as u64; - let carried = r.vm.carried(); + let (used, carried) = r.vm.budget_used(); + let active = used.max(r.active_before); let captured = snapshot::capture( &r.vm, &snapshot::Capture { code: &r.code, - active_ms, + active, carried, }, ); @@ -859,7 +861,7 @@ impl Program { }; let c = snapshot::Capture { code: &r.code, - active_ms: 0, + active: Duration::ZERO, carried: Default::default(), }; snapshot::capture(&r.vm, &c).unwrap_or_else(|_| panic!("the state can't be saved")) @@ -868,11 +870,11 @@ impl Program { fn restore(rt: &Runtime, state: &Snapshot) -> Result, snapshot::SnapshotError> { let restored = snapshot::header(state)?; - let (active_ms, carried) = (restored.active_ms, restored.carried); + let (active, carried) = (restored.active, restored.carried); let mut started = run::start_for_resume(rt, restored)?; snapshot::restore(&mut started.running.vm, state, &started.bytecode)?; let mut r = started.running; - r.active_before = Duration::from_millis(active_ms); + r.active_before = active; r.carried = carried; // The program's body already started: what runs next comes from the saved frames and jobs. r.mark_resumed(); diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index a9eb1933..11526277 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -514,7 +514,7 @@ fn cross(c: &crate::cross::Cross) -> J { /// What a capture needs to know beyond the VM. pub struct Capture<'c> { pub code: &'c str, - pub active_ms: u64, + pub active: std::time::Duration, pub carried: crate::cpu::Carried, } @@ -589,7 +589,10 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { "timeoutMs": limits.timeout_ms, "maxOutputBytes": limits.max_output_bytes, }, - "budget": { "activeMs": c.active_ms }, + "budget": { + "activeMs": c.active.as_millis() as u64, + "activeUs": c.active.as_micros() as u64, + }, "base": base.json(), "state": state_hash(&state), }); @@ -2524,7 +2527,7 @@ pub struct Restored { /// The shape of the host globals it was saved with (`hosts_id`). pub hosts: String, pub limits: Limits, - pub active_ms: u64, + pub active: std::time::Duration, pub carried: crate::cpu::Carried, } @@ -2588,7 +2591,13 @@ pub fn header(snapshot: &Snapshot) -> R { // Not saved: it bounds the source a run starts from, and a state brings its own. max_source_bytes: None, }, - active_ms: field(budget, "activeMs")?.as_u64().unwrap_or(0), + active: { + let active_ms = field(budget, "activeMs")?.as_u64().unwrap_or(0); + match budget.get("activeUs").and_then(J::as_u64) { + Some(us) => std::time::Duration::from_micros(us), + None => std::time::Duration::from_millis(active_ms).max(us("stretchUs")), + } + }, carried: crate::cpu::Carried { stretch: us("stretchUs"), stretch_total: us("stretchTotalUs"), @@ -3015,9 +3024,14 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> { /// The calls a resumed run restarts, in the order they were in flight, so their futures start on the run's executor. pub fn restart_calls(vm: &mut Vm) { + if vm.host.restarts.is_empty() { + return; + } + let span = vm.host_span(); for r in std::mem::take(&mut vm.host.restarts) { host::restart(vm, r); } + vm.end_host_span(span); } #[cfg(test)] diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index da8f790b..3cb0dd79 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -1220,14 +1220,6 @@ impl Vm { } } - /// The time the run used, of the clock its timeout counts. - pub(crate) fn time_used(&mut self) -> Duration { - match &mut self.cpu { - Some(c) => c.used(), - None => self.start.elapsed(), - } - } - pub fn check_time(&mut self) -> Result<(), Value> { if self.fatal.is_some() { return Err(Value::Undef); @@ -1266,21 +1258,24 @@ impl Vm { let (Some(s), cpu) = (self.slice.as_deref_mut(), self.cpu.as_deref_mut()) else { return false; }; + let Some(wall) = s.wall else { + return false; + }; let Some(c) = cpu else { - return s.wall.elapsed() >= limit; + return wall.elapsed() >= limit; }; let backstop = limit * crate::cpu::WAIT_BACKSTOP; match s.from { None => { - if s.wall.elapsed() >= limit / crate::cpu::SLICE_SLACK { + if wall.elapsed() >= limit / crate::cpu::SLICE_SLACK { s.from = Some(c.read()); - s.wall = Instant::now() + limit; + s.wall = Some(Instant::now() + limit); } false } Some((used0, total0)) => { let now = Instant::now(); - if now < s.wall { + if now < wall { return false; } let (used, total) = c.read(); @@ -1288,7 +1283,7 @@ impl Vm { if used >= limit || total >= backstop { return true; } - s.wall = now + (limit - used).min(backstop - total); + s.wall = Some(now + (limit - used).min(backstop - total)); false } } @@ -1301,25 +1296,51 @@ impl Vm { if self.limits.slice_ms.is_none() { return; } - let wall = Instant::now(); + let wall = Some(Instant::now()); match self.slice.as_deref_mut() { Some(s) => (s.from, s.wall) = (None, wall), None => self.slice = Some(Box::new(crate::cpu::Slice { from: None, wall })), } } + /// With `Limits::slice_ms`, the stretch in progress ends as the run stops to wait on the host. + #[cold] + #[inline(never)] + pub(crate) fn slice_pause(&mut self) { + if let Some(s) = self.slice.as_deref_mut() { + s.from = None; + s.wall = None; + } + } + /// With `Limits::slice_ms`, the run starts: a stretch starts, or, for a resumed run, the one in progress when it was /// suspended goes on from where it was (`carried`). #[cold] #[inline(never)] pub(crate) fn slice_start(&mut self, carried: &crate::cpu::Carried) { + if self.limits.slice_ms.is_none() { + return; + } + // A resumed run with no frames or jobs left is waiting on the host: no stretch is in progress until an outcome + // arrives. + if self.resumed && self.frames.is_empty() && self.jobs.is_empty() { + self.slice = Some(Box::new(crate::cpu::Slice { + from: None, + wall: None, + })); + return; + } self.slice_restart(); let resumed = self.resumed; let (Some(s), cpu) = (self.slice.as_deref_mut(), self.cpu.as_deref_mut()) else { return; }; match cpu { - None => s.wall = s.wall.checked_sub(carried.stretch).unwrap_or(s.wall), + None => { + if let Some(wall) = s.wall { + s.wall = Some(wall.checked_sub(carried.stretch).unwrap_or(wall)); + } + } // Measured from the resume on, against where it was: a run resumed again before each stretch had run the // part of the slice that isn't would never be. Some(c) if resumed => { @@ -1333,42 +1354,61 @@ impl Vm { } } - /// What the run spent besides its active time, for its saved state (see `cpu::Carried`). - pub(crate) fn carried(&mut self) -> crate::cpu::Carried { + /// The run's active time and what it spent besides, from one reading of its clock, for its saved state. + pub(crate) fn budget_used(&mut self) -> (Duration, crate::cpu::Carried) { let mut carried = crate::cpu::Carried::default(); - if let Some(c) = self.cpu.as_deref_mut() { - (carried.total, carried.waited) = c.spent(); - } - if let Some(s) = self.slice.as_deref() { - match (s.from, self.cpu.as_deref_mut()) { - (_, None) => carried.stretch = s.wall.elapsed(), - (Some((used0, total0)), Some(c)) => { - let (used, total) = c.read(); + let used = match self.cpu.as_deref_mut() { + Some(c) => { + let (used, total, waited) = c.totals(); + carried.total = total; + carried.waited = waited; + if let Some(s) = self.slice.as_deref() + && let Some((used0, total0)) = s.from + { carried.stretch = used.saturating_sub(used0); carried.stretch_total = total.saturating_sub(total0); } - // Not measured yet: within the part of the slice every stretch runs before it is. - (None, Some(_)) => {} + used } - } - carried + None => { + if let Some(s) = self.slice.as_deref() + && let Some(wall) = s.wall + { + carried.stretch = wall.elapsed(); + } + self.start.elapsed() + } + }; + (used, carried) } - /// A synchronous host call starts, which neither the CPU time (`Clock::ThreadCpu`) nor a stretch under - /// `Limits::slice_ms` counts: when it started on the wall clock, as each leaves out its wall-clock duration. + /// Host work starts, which neither the CPU time (`Clock::ThreadCpu`) nor a stretch under `Limits::slice_ms` counts: + /// when it started on the wall clock, as each leaves out its wall-clock duration. + #[inline] pub(crate) fn host_span(&mut self) -> Option { (self.cpu.is_some() || self.slice.is_some()).then(Instant::now) } - /// The host call that began at `span` ends. + /// The host work that began at `span` ends. + #[inline] pub(crate) fn end_host_span(&mut self, span: Option) { let Some(at) = span else { return; }; + self.record_host_span(at); + } + + #[cold] + #[inline(never)] + fn record_host_span(&mut self, at: Instant) { let wall = at.elapsed(); match (self.cpu.as_deref_mut(), self.slice.as_deref_mut()) { (Some(c), _) => c.host(wall), - (None, Some(s)) => s.wall += wall, + (None, Some(s)) => { + if let Some(w) = &mut s.wall { + *w += wall; + } + } (None, None) => {} } } @@ -5005,6 +5045,9 @@ impl Vm { continue; } if self.host.waiting() { + if self.slice.is_some() { + self.slice_pause(); + } return Ok(()); } let e = self.make_error( diff --git a/rust/crates/psychoscript/tests/clock.rs b/rust/crates/psychoscript/tests/clock.rs index 69089f0e..9d9f538f 100644 --- a/rust/crates/psychoscript/tests/clock.rs +++ b/rust/crates/psychoscript/tests/clock.rs @@ -516,6 +516,192 @@ fn a_resumed_run_keeps_its_cpu_time_with_host_calls() { assert!(timed_out(&o), "{:?}", o.result); } +/// A future that stays pending for `duration` and wakes its task from another thread. +fn after(duration: Duration) -> impl Future + Send + 'static { + struct Timer { + state: Arc)>>, + } + impl Future for Timer { + type Output = (); + fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + let mut g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if g.0 { + Poll::Ready(()) + } else { + g.1 = Some(cx.waker().clone()); + Poll::Pending + } + } + } + let state = Arc::new(std::sync::Mutex::new((false, None::))); + let wakeup = state.clone(); + thread::spawn(move || { + thread::sleep(duration); + let waker = { + let mut g = wakeup.lock().unwrap_or_else(|e| e.into_inner()); + g.0 = true; + g.1.take() + }; + if let Some(w) = waker { + w.wake(); + } + }); + Timer { state } +} + +#[test] +fn wall_slice_excludes_async_host_waits() { + let _quiet = quiet(); + let rt = Runtime::make() + .limits(sliced(50, Clock::Wall)) + .globals(|_| { + [ + ( + "slow", + HostFunction::new_async(|_, _| async { + after(Duration::from_millis(120)).await; + Ok(HostValue::Number(42.0)) + }), + ), + ( + "slow_poll", + HostFunction::new_async(|_, _| async { + thread::sleep(Duration::from_millis(120)); + Ok(HostValue::Number(7.0)) + }), + ), + ] + }); + for code in ["return await slow()", "return await slow_poll()"] { + let expected = if code.contains("slow_poll") { 7 } else { 42 }; + let o = rt.program(code, &ProgramOptions::new()).run().unwrap(); + assert_eq!(o.result.unwrap(), json!(expected), "run: {code}"); + let o = drive(rt.program(code, &ProgramOptions::new()).run_async()).unwrap(); + assert_eq!(o.result.unwrap(), json!(expected), "run_async: {code}"); + } +} + +#[test] +fn wall_slice_excludes_async_host_waits_across_suspend_and_resume() { + let _quiet = quiet(); + // 30 ms async wait -> suspend -> bytes -> resume -> 30 ms async wait, under a 50 ms wall slice. + let attempt = Arc::new(std::sync::atomic::AtomicU32::new(0)); + let rt = Runtime::make() + .limits(sliced(50, Clock::Wall)) + .globals(move |_| { + let attempt = attempt.clone(); + [( + "slow", + HostValue::from( + HostFunction::new_async(move |_, _| { + let n = attempt.fetch_add(1, Ordering::Relaxed); + async move { + let ms = if n == 0 { 100 } else { 30 }; + after(Duration::from_millis(ms)).await; + Ok(HostValue::Number(1.0)) + } + }) + .idempotent(), + ), + )] + }); + let program = rt.program("return await slow()", &ProgramOptions::new()); + let suspender = program.suspender(); + let outcome = thread::scope(|s| { + let running = s.spawn(move || program.run_resumable().unwrap()); + thread::sleep(Duration::from_millis(30)); + let _ = suspender.suspend(None); + running.join().unwrap() + }); + let RunOutcome::Suspended(suspended) = outcome else { + panic!("expected Suspended, got {outcome:?}"); + }; + assert_eq!(suspended.state.0["header"]["budget"]["stretchUs"], json!(0)); + let bytes = psychoscript::to_bytes(&suspended.state); + let resumed = rt.resume_bytes(&bytes).unwrap(); + let _keep = resumed.suspender(); + let resumed = resumed.run().unwrap(); + assert_eq!(resumed.result.unwrap(), json!(1)); + + // 80 ms async wait (> 50 ms wall slice) -> suspend() must suspend cleanly instead of SliceExceeded. + let wait_rt = waiting(sliced(50, Clock::Wall)); + let program = wait_rt.program("return await wait()", &ProgramOptions::new()); + let suspender = program.suspender(); + let outcome = thread::scope(|s| { + let running = s.spawn(move || program.run_resumable().unwrap()); + thread::sleep(Duration::from_millis(80)); + let reply = suspender.suspend(None).unwrap(); + let joined = running.join().unwrap(); + assert!(matches!(reply, RunOutcome::Suspended(_)), "{reply:?}"); + joined + }); + let RunOutcome::Suspended(suspended) = outcome else { + panic!("expected Suspended after 80ms wait, got {outcome:?}"); + }; + assert_eq!(suspended.state.0["header"]["budget"]["stretchUs"], json!(0)); +} + +#[test] +fn thread_cpu_slice_accumulates_across_sub_ms_resumes() { + let _quiet = quiet(); + let rt = Runtime::make().limits(sliced(50, Clock::ThreadCpu)); + let mut program = rt.program("while (true) {}", &ProgramOptions::new()); + let mut sub_ms_steps = 0u32; + let mut prev_active_us = 0u64; + let mut prev_stretch_us = 0u64; + let mut last_stretch_total_us = 0u64; + let mut done = None; + for resumes in 0..300u32 { + let suspender = program.suspender(); + let outcome = thread::scope(|s| { + let running = s.spawn(move || program.run_resumable().unwrap()); + let until = Instant::now() + Duration::from_micros(400); + while !running.is_finished() && Instant::now() < until { + std::hint::spin_loop(); + } + while !running.is_finished() && suspender.suspend(None).is_err() { + std::hint::spin_loop(); + } + running.join().unwrap() + }); + match outcome { + RunOutcome::Done(o) => { + done = Some((o, resumes)); + break; + } + RunOutcome::Suspended(s) => { + let budget = &s.state.0["header"]["budget"]; + let active_ms = budget["activeMs"].as_u64().unwrap(); + let active_us = budget["activeUs"].as_u64().unwrap(); + let stretch_us = budget["stretchUs"].as_u64().unwrap(); + last_stretch_total_us = budget["stretchTotalUs"].as_u64().unwrap(); + assert_eq!(active_ms, active_us / 1000); + assert!( + active_us >= stretch_us, + "activeUs ({active_us}) < stretchUs ({stretch_us}) at resume {resumes}" + ); + if stretch_us > prev_stretch_us && active_us.saturating_sub(prev_active_us) < 1000 { + sub_ms_steps += 1; + } + prev_active_us = active_us; + prev_stretch_us = stretch_us; + let bytes = psychoscript::to_bytes(&s.state); + program = rt.resume_bytes(&bytes).unwrap(); + } + } + } + let (o, resumes) = done.expect("loop ran 300 resumes without hitting SliceExceeded"); + assert!(sliced_out(&o), "{:?} after {resumes} resumes", o.result); + assert!( + sub_ms_steps >= 10, + "expected sub-1ms resumes advancing stretchUs (got {sub_ms_steps} in {resumes} resumes)" + ); + assert!( + last_stretch_total_us < 100_000, + "stretchTotalUs grew too far before SliceExceeded: {last_stretch_total_us}us ({resumes} resumes)" + ); +} + /// The thread's CPU, and pinning to it, on Linux. #[cfg(target_os = "linux")] mod pin {