Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions rust/crates/psychoscript/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1895,6 +1895,7 @@ mod tests {
&crate::snapshot::Capture {
code: CODE,
active_ms: 0,
carried: Default::default(),
},
);
let Ok(saved) = saved else {
Expand Down
30 changes: 25 additions & 5 deletions rust/crates/psychoscript/src/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<Mark>,
/// 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<Instant>,
Expand All @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
12 changes: 6 additions & 6 deletions rust/crates/psychoscript/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ pub struct Limits {
pub max_source_bytes: Option<usize>,
/// 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<u64>,
}

Expand Down
15 changes: 12 additions & 3 deletions rust/crates/psychoscript/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -739,18 +745,20 @@ 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"))
}
}

fn restore(rt: &Runtime, state: &Snapshot) -> Result<Box<Running>, 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)
Expand All @@ -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,
}
Expand Down
21 changes: 21 additions & 0 deletions rust/crates/psychoscript/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand Down Expand Up @@ -595,12 +596,21 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result<Snapshot, Refusal> {
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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -2538,6 +2549,10 @@ pub fn header(snapshot: &Snapshot) -> R<Restored> {
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),
Expand Down Expand Up @@ -2569,6 +2584,12 @@ pub fn header(snapshot: &Snapshot) -> R<Restored> {
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"),
},
})
}

Expand Down
46 changes: 46 additions & 0 deletions rust/crates/psychoscript/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Instant> {
Expand Down
Loading