From e2340014fd81c8df498e683761b6ab812e8d014f Mon Sep 17 00:00:00 2001 From: OpenCode Agent Date: Wed, 2 Dec 2026 23:07:59 +0100 Subject: [PATCH] fix(rust): a resume goes on with the slice's stretch and the CPU clock's backstops Limits::slice_ms started a new stretch on every resume, and Clock::ThreadCpu's backstops (CPU time with host calls, waits) started again from zero, so a run suspended and resumed often enough never ended. The header's budget saves them (stretchUs, stretchTotalUs, totalUs, waitedUs, only where they apply; missing reads as zero), and a resume goes on from there. The round-trip test mode restores through them too, and its swapped-in VM now enters the CPU meter. --- rust/README.md | 3 +- rust/crates/psychoscript/src/collector.rs | 1 + rust/crates/psychoscript/src/cpu.rs | 30 ++++- rust/crates/psychoscript/src/diagnostic.rs | 12 +- rust/crates/psychoscript/src/program.rs | 15 ++- rust/crates/psychoscript/src/snapshot.rs | 21 ++++ rust/crates/psychoscript/src/vm.rs | 46 +++++++ rust/crates/psychoscript/tests/clock.rs | 132 ++++++++++++++++++++- 8 files changed, 244 insertions(+), 16 deletions(-) diff --git a/rust/README.md b/rust/README.md index 2f441f29..587edd10 100644 --- a/rust/README.md +++ b/rust/README.md @@ -179,7 +179,8 @@ Known differences: on host calls count on the wall clock, up to ten times the timeout. The check reads the thread's clock only when the wall time since its last reading could have used up the budget. `Limits::slice_ms` bounds each stretch between awaits of the host the same way, also leaving out host calls, and stops the run with `SliceExceeded`, so a host - needn't watch the run from outside. Under `ThreadCpu` a stretch's CPU time is measured from when it has run a + needn't watch the run from outside. A suspend saves how far the stretch in progress had gone, and under `ThreadCpu` + the CPU time with host calls and the waits, so a resume goes on from there instead of starting them again. Under `ThreadCpu` a stretch's CPU time is measured from when it has run a sixteenth of the slice, so it may run up to that much past it. On wasm32 the clocks are `performance.now()` and `Date.now()` (`web-time`), and `ThreadCpu` counts wall-clock time. - **Compiling:** the parser recurses once a level of syntax and has no guard of its own, so a program is parsed on a diff --git a/rust/crates/psychoscript/src/collector.rs b/rust/crates/psychoscript/src/collector.rs index a9317c00..b3cdbce7 100644 --- a/rust/crates/psychoscript/src/collector.rs +++ b/rust/crates/psychoscript/src/collector.rs @@ -1895,6 +1895,7 @@ mod tests { &crate::snapshot::Capture { code: CODE, active_ms: 0, + carried: Default::default(), }, ); let Ok(saved) = saved else { diff --git a/rust/crates/psychoscript/src/cpu.rs b/rust/crates/psychoscript/src/cpu.rs index 923a71c5..d3ff0c20 100644 --- a/rust/crates/psychoscript/src/cpu.rs +++ b/rust/crates/psychoscript/src/cpu.rs @@ -29,6 +29,18 @@ pub(crate) struct Slice { pub(crate) wall: Instant, } +/// What a run spent besides its active time, saved with its state so that a resume goes on from it rather than from +/// nothing: under `Limits::slice_ms`, how far the stretch in progress is, on the run's clock and, under +/// `Clock::ThreadCpu`, with host calls (none while it hasn't been measured); and under `Clock::ThreadCpu`, the run's +/// CPU time with host calls and its waits, which the backstops bound. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct Carried { + pub(crate) stretch: Duration, + pub(crate) stretch_total: Duration, + pub(crate) total: Duration, + pub(crate) waited: Duration, +} + /// The part of the slice a stretch runs before its CPU time is measured (so that the many short ones never read the /// thread's clock); what it used meanwhile isn't counted, so a stretch may run up to that much past the slice. pub(crate) const SLICE_SLACK: u32 = 16; @@ -50,13 +62,13 @@ struct Mark { pub(crate) struct CpuMeter { /// CPU time used before the stretch in progress, and before the run was resumed, without host calls. used: Duration, - /// CPU time used since the run started or resumed, with host calls. + /// CPU time used, before the run was resumed too, with host calls. total: Duration, /// The stretch in progress, or `None` between stretches (or if reading the thread clock failed). mark: Option, /// The wall-clock time of the host calls since the last reading. host: Duration, - /// Wall-clock time spent waiting on host calls. + /// Wall-clock time spent waiting on host calls, before the run was resumed too. waited: Duration, /// When the wait in progress began. wait_since: Option, @@ -78,9 +90,11 @@ impl CpuMeter { } } - /// The run starts, having used `used` before it was resumed. - pub(crate) fn start(&mut self, used: Duration) { + /// The run starts, having used `used`, and spent what `carried` says, before it was resumed. + pub(crate) fn start(&mut self, used: Duration, carried: &Carried) { self.used = used; + self.total = carried.total; + self.waited = carried.waited; } /// A stretch of the run starts on the calling thread; a wait in progress ends. @@ -143,12 +157,18 @@ impl CpuMeter { self.used } - /// The CPU time the run used without host calls, and since it started or resumed with them. + /// 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) { + self.fold(); + (self.total, self.waited) + } + /// Wall-clock time spent in a wait on the calling thread, which used no CPU time meanwhile. pub(crate) fn waited(&mut self, wait: Duration) { self.waited += wait; diff --git a/rust/crates/psychoscript/src/diagnostic.rs b/rust/crates/psychoscript/src/diagnostic.rs index c0f8a77c..0eec80e1 100644 --- a/rust/crates/psychoscript/src/diagnostic.rs +++ b/rust/crates/psychoscript/src/diagnostic.rs @@ -23,12 +23,12 @@ pub struct Limits { pub max_source_bytes: Option, /// What `timeout_ms` and `slice_ms` count; [`Clock::Wall`] by default. pub clock: Clock, - /// The longest a run may compute without awaiting the host: from its start or resume, or from when a host call it - /// awaited delivers its outcome, to the next. Promise jobs don't end it, and synchronous host calls in between don't - /// count. A run past it stops with [`DiagnosticKind::SliceExceeded`]. Under [`Clock::ThreadCpu`] a stretch's CPU - /// time is measured once it has run a sixteenth of the slice, so it may run up to that much past it, and its host - /// calls are left out as for the timeout: with them, it may use ten times the slice. `None` (the default) is no - /// limit. + /// The longest a run may compute without awaiting the host: from its start, or from when a host call it awaited + /// delivers its outcome, to the next. Promise jobs don't end it, nor does a suspend and resume, and synchronous host + /// calls in between don't count. A run past it stops with [`DiagnosticKind::SliceExceeded`]. Under + /// [`Clock::ThreadCpu`] a stretch's CPU time is measured once it has run a sixteenth of the slice, so it may run up + /// to that much past it, and its host calls are left out as for the timeout: with them, it may use ten times the + /// slice. `None` (the default) is no limit. pub slice_ms: Option, } diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index c175ce06..42a3b4b0 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -32,6 +32,8 @@ pub(crate) struct Running { timer_armed: bool, /// Active time earlier runs of the same execution used, before a resume. pub active_before: Duration, + /// What they spent besides, before a resume (see `cpu::Carried`). + pub carried: crate::cpu::Carried, /// Back-edges until the next round trip, in the round-trip test mode. round_trip_every: u32, /// Round trips still to skip after one that saved a large state. @@ -395,9 +397,11 @@ impl Program { .checked_sub(r.active_before) .unwrap_or_else(Instant::now); if let Some(c) = &mut r.vm.cpu { - c.start(r.active_before); + c.start(r.active_before, &r.carried); + // A run a round trip swapped in mid-poll starts its stretch here. + c.enter(); } - r.vm.slice_restart(); + r.vm.slice_start(&r.carried); if round_trips(&self.shared) { r.vm.start_roundtrip(r.round_trip_every); } @@ -586,11 +590,13 @@ impl Program { } let used = r.vm.time_used(); let active_ms = used.max(r.active_before).as_millis() as u64; + let carried = r.vm.carried(); let captured = snapshot::capture( &r.vm, &snapshot::Capture { code: &r.code, active_ms, + carried, }, ); match request { @@ -739,6 +745,7 @@ impl Program { let c = snapshot::Capture { code: &r.code, active_ms: 0, + carried: Default::default(), }; snapshot::capture(&r.vm, &c).unwrap_or_else(|_| panic!("the state can't be saved")) } @@ -746,11 +753,12 @@ impl Program { fn restore(rt: &Runtime, state: &Snapshot) -> Result, snapshot::SnapshotError> { let restored = snapshot::header(state)?; - let active_ms = restored.active_ms; + let (active_ms, carried) = (restored.active_ms, 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.carried = carried; // The program's body already started: what runs next comes from the saved frames and jobs. r.mark_resumed(); Ok(r) @@ -764,6 +772,7 @@ impl Running { started: false, timer_armed: false, active_before: Duration::ZERO, + carried: Default::default(), round_trip_every: ROUNDTRIP_TICKS, skip: 0, } diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 8d957e77..48a7568b 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -515,6 +515,7 @@ fn cross(c: &crate::cross::Cross) -> J { pub struct Capture<'c> { pub code: &'c str, pub active_ms: u64, + pub carried: crate::cpu::Carried, } struct Enc<'v> { @@ -595,12 +596,21 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { if let Some(n) = limits.max_heap_bytes { header["limits"]["maxHeapBytes"] = json!(n); } + // What the run spent besides its active time, in microseconds, so that a resume goes on from it (`cpu::Carried`): + // a round trip makes one, which would lose a stretch rounded to milliseconds. + let us = |d: std::time::Duration| json!(d.as_micros() as u64); // The run's time is its CPU time (`activeMs` too); a wall-clock run's header is as it always was. if limits.clock == crate::Clock::ThreadCpu { header["limits"]["clock"] = json!("threadCpu"); + header["budget"]["totalUs"] = us(c.carried.total); + header["budget"]["waitedUs"] = us(c.carried.waited); } if let Some(ms) = limits.slice_ms { header["limits"]["sliceMs"] = json!(ms); + header["budget"]["stretchUs"] = us(c.carried.stretch); + if limits.clock == crate::Clock::ThreadCpu { + header["budget"]["stretchTotalUs"] = us(c.carried.stretch_total); + } } if let Some(n) = limits.max_value_depth { header["limits"]["maxValueDepth"] = json!(n); @@ -2510,6 +2520,7 @@ pub struct Restored { pub hosts: String, pub limits: Limits, pub active_ms: u64, + pub carried: crate::cpu::Carried, } /// Reads a state's header, checking it belongs to this build and its source matches its hash; the run's setup then @@ -2538,6 +2549,10 @@ pub fn header(snapshot: &Snapshot) -> R { let limits = field(header, "limits")?; let opt = |name: &str| field(limits, name).map(J::as_u64); let budget = field(header, "budget")?; + // Saved only where they apply, and not before this build: none is nothing spent. + let us = |name: &str| { + std::time::Duration::from_micros(budget.get(name).and_then(J::as_u64).unwrap_or(0)) + }; Ok(Restored { code, run_id: field(header, "runId")?.as_str().map(str::to_owned), @@ -2569,6 +2584,12 @@ pub fn header(snapshot: &Snapshot) -> R { max_source_bytes: None, }, active_ms: field(budget, "activeMs")?.as_u64().unwrap_or(0), + carried: crate::cpu::Carried { + stretch: us("stretchUs"), + stretch_total: us("stretchTotalUs"), + total: us("totalUs"), + waited: us("waitedUs"), + }, }) } diff --git a/rust/crates/psychoscript/src/vm.rs b/rust/crates/psychoscript/src/vm.rs index f2226540..36153f5f 100644 --- a/rust/crates/psychoscript/src/vm.rs +++ b/rust/crates/psychoscript/src/vm.rs @@ -1305,6 +1305,52 @@ impl Vm { } } + /// 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) { + 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), + // 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 => { + let (used, total) = c.read(); + s.from = Some(( + used.saturating_sub(carried.stretch), + total.saturating_sub(carried.stretch_total), + )); + } + Some(_) => {} + } + } + + /// What the run spent besides its active time, for its saved state (see `cpu::Carried`). + pub(crate) fn carried(&mut self) -> 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(); + 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(_)) => {} + } + } + 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. pub(crate) fn host_span(&mut self) -> Option { diff --git a/rust/crates/psychoscript/tests/clock.rs b/rust/crates/psychoscript/tests/clock.rs index 31c1bdc2..69089f0e 100644 --- a/rust/crates/psychoscript/tests/clock.rs +++ b/rust/crates/psychoscript/tests/clock.rs @@ -80,12 +80,23 @@ fn a_busy_loop_is_stopped_at_its_cpu_budget() { o.result.unwrap_err().message_lossy(), "Execution timed out after 300ms." ); + // In the round-trip test mode the thread also saves and restores the run every few milliseconds, which isn't + // the run's time, as a resume isn't. + let most = match roundtrip() { + true => Duration::from_secs(3), + false => Duration::from_millis(600), + }; assert!( - used >= Duration::from_millis(300) && used < Duration::from_millis(600), + used >= Duration::from_millis(300) && used < most, "{used:?}" ); } +/// Whether the round-trip test mode is on (`PSYCHOSCRIPT_ROUNDTRIP=1`). +fn roundtrip() -> bool { + std::env::var_os("PSYCHOSCRIPT_ROUNDTRIP").is_some_and(|v| v == "1") +} + #[test] fn a_busy_loop_on_the_run_s_worker_is_stopped_at_its_cpu_budget() { let _quiet = quiet(); @@ -386,6 +397,125 @@ fn a_suspended_run_keeps_its_clock() { ); } +/// Runs `code`, suspending it about every 40 ms and resuming it from its state's bytes until it ends: its outcome, how +/// many times it resumed, and the wall-clock time it was running. +fn resumed_every_40ms(rt: &Runtime, code: &str) -> (psychoscript::Outcome, u32, Duration) { + let mut program = rt.program(code, &ProgramOptions::new()); + let mut running_for = Duration::ZERO; + for resumes in 0.. { + let suspender = program.suspender(); + let start = Instant::now(); + let outcome = thread::scope(|s| { + let running = s.spawn(move || program.run_resumable().unwrap()); + thread::sleep(Duration::from_millis(40)); + while !running.is_finished() && suspender.suspend(None).is_err() { + thread::sleep(Duration::from_millis(1)); + } + running.join().unwrap() + }); + running_for += start.elapsed(); + match outcome { + RunOutcome::Done(o) => return (o, resumes, running_for), + RunOutcome::Suspended(s) => { + let bytes = psychoscript::to_bytes(&s.state); + program = rt.resume_bytes(&bytes).unwrap(); + } + } + } + unreachable!() +} + +#[test] +fn a_run_resumed_again_and_again_keeps_its_slice_its_timeout_and_its_waits() { + let _quiet = quiet(); + // Resumed every 40 ms, a run ends once it has run `ms` in all. + let ends = + |rt: Runtime, code: &str, ms: u64, over: fn(&psychoscript::Outcome) -> bool, what: &str| { + let budget = Duration::from_millis(ms); + let (o, resumes, running_for) = resumed_every_40ms(&rt, code); + assert!(over(&o), "{what}: {:?} after {resumes} resumes", o.result); + assert!( + resumes >= 1 + && running_for >= budget + && running_for < budget + Duration::from_secs(3), + "{what}: {resumes} resumes, {running_for:?}" + ); + }; + let busy = "await tick(); while (true) {}"; + for clock in [Clock::Wall, Clock::ThreadCpu] { + let slice = format!("{clock:?} slice"); + ends(ticking(sliced(300, clock)), busy, 300, sliced_out, &slice); + let timeout = format!("{clock:?} timeout"); + ends(ticking(limits(300, clock)), busy, 300, timed_out, &timeout); + } + // A stretch's CPU time isn't measured before it has run a sixteenth of the slice, here 200 ms, longer than the run + // goes between resumes: each resume measures it from there on. + let slow = ticking(sliced(3200, Clock::ThreadCpu)); + ends( + slow, + busy, + 3200, + sliced_out, + "ThreadCpu slice past its slack", + ); + // Waits under a 30 ms CPU timeout end the run at the backstop, ten times it. + ends( + waiting(limits(30, Clock::ThreadCpu)), + "await wait()", + 300, + timed_out, + "waits", + ); +} + +#[test] +fn a_resumed_run_keeps_its_cpu_time_with_host_calls() { + let _quiet = quiet(); + // `spend(ms)` uses that much CPU time in a host call; `wait()` never settles the first time, and at once after. + let ms = |args: &[HostValue]| args.first().and_then(HostValue::as_f64).unwrap_or(0.0) as u64; + let waited = Arc::new(AtomicBool::new(false)); + let rt = Runtime::make() + .limits(limits(30, Clock::ThreadCpu)) + .globals(move |_| { + let waited = waited.clone(); + [ + ( + "spend", + HostValue::from(HostFunction::new(move |args, _| { + let clock = psychoscript::thread_clock::ThreadClock::current(); + let until = clock.now() + Duration::from_millis(ms(&args)); + while clock.now() < until { + std::hint::spin_loop(); + } + HostValue::Undefined + })), + ), + ( + "wait", + HostValue::from( + HostFunction::new_async(move |_, _| { + let again = waited.swap(true, Ordering::Relaxed); + async move { + if !again { + std::future::pending::<()>().await; + } + Ok(HostValue::Undefined) + } + }) + .idempotent(), + ), + ), + ] + }); + // 200 ms of CPU time in host calls before the suspend and 200 ms after, under a 30 ms timeout: past the backstop, + // ten times it, in all. + let code = "spend(200); await wait(); spend(200); await wait(); return 1"; + let state = suspend_waiting(&rt, code); + assert!(state.0["header"]["budget"]["totalUs"].as_u64().unwrap() >= 200_000); + let o = rt.resume(&state).unwrap().run().unwrap(); + assert!(timed_out(&o), "{:?}", o.result); +} + /// The thread's CPU, and pinning to it, on Linux. #[cfg(target_os = "linux")] mod pin {