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
4 changes: 3 additions & 1 deletion rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ Only Rust has:
- Lazy built-in groups: [`LAZY`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/builtins/mod.rs) sets up `RegExp`, `Date`, the typed arrays and the other groups only when a program uses them.
- Optional `locale` feature (`default = ["locale"]`): disable it with `default-features = false` to drop ICU4X's compiled CLDR tables (~5 MB) in lean embedded or `wasm32` builds. With `locale` off and no provider of the host's (below), `locales` and `options` are ignored: `Date.prototype.toLocale*String` returns UTC ISO-8601 strings (`YYYY-MM-DDTHH:mm:ss.sssZ`, date slice, or time slice, or `"Invalid Date"`), `Number`/`BigInt.prototype.toLocaleString` use decimal `toString`, and `String.prototype.localeCompare` compares NFC-normalized UTF-16 code units.
- A pluggable locale provider: [`Runtime::locale`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) sets the [`LocaleProvider`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/locale.rs) (`Send + Sync`) that formats dates for `toLocale*String`, numbers and BigInts for `toLocaleString`, and compares strings for `localeCompare`, in place of the default: `IcuLocale` with `locale`, `FallbackLocale` (the fallbacks above) without it. PsychoScript still reads and validates the locales and options and throws their errors, as with `locale`, so the provider gets the locale tags and the resolved options as plain Rust data and only formats or compares; it checks `timeZone` itself (PsychoScript's zone data checks it only for the defaults), and an `Err` it returns, for what only it can know, is thrown as a `RangeError`. It is host configuration like the globals, not saved with a run. A `wasm32` host without `locale` can hand them to the browser's `Intl` through `wasm-bindgen` (`js_sys::Intl::DateTimeFormat`, `NumberFormat`, `Collator`, or `toLocaleString` on a `js_sys::Date`), turning each option back into its `Intl` name.
- Owned runs that stay on the calling thread: [`Runtime`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/runtime.rs) clones cheaply, [`Program`](https://github.com/anomalyco/psychoscript/blob/dev/rust/crates/psychoscript/src/program.rs) holds a clone so it is `'static`, and `Runtime::offload(false)` keeps a run driven as a future on the thread that polls it, without starting a worker thread, so CPU time counts there.

Only TypeScript has:

Expand Down Expand Up @@ -163,7 +164,8 @@ Known differences:
## Design

- **Threading:** a run stays on the thread that drives it; as a future, compute past 1 ms moves to a worker of the
run's own while host code is always handed back to the executor, in the same order. On wasm32, without threads, the
run's own (unless `Runtime::offload(false)` keeps it on the calling thread) while host code is always handed back to
the executor, in the same order. On wasm32, without threads, the
run yields to its executor there instead, and a thread can't wait: a synchronous run waiting on host work that
isn't ready, or a sync host function's `Returned::Block` work, ends in an `ExecutionFailure` saying so.
- **Memory:** an incremental, non-moving mark-sweep collector (`collector.rs`) frees what a run can no longer reach,
Expand Down
45 changes: 24 additions & 21 deletions rust/crates/psychoscript/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,30 +236,32 @@ impl Suspender {
}
}

/// A program ready to run once. Dropping it interrupts the run and cancels every host call in flight.
pub struct Program<'a> {
rt: &'a Runtime,
/// A program ready to run once. Holds a clone of its [`Runtime`], so it is `'static`. Dropping it interrupts the run
/// and cancels every host call in flight.
pub struct Program {
rt: Runtime,
state: State,
shared: Arc<Shared>,
/// Driven as a future, so a long stretch of compute moves to a worker thread instead of holding the executor's.
/// Driven as a future with offloading enabled, so a long stretch of compute moves to a worker thread instead of
/// holding the executor's.
offload: bool,
worker: Option<offload::Worker>,
/// The stretch of compute in progress continues on the worker.
move_away: bool,
}

impl<'a> Program<'a> {
impl Program {
/// Compiles the program and sets up its globals; nothing runs yet.
pub(crate) fn new(rt: &'a Runtime, code: Code<'_>, options: &ProgramOptions) -> Self {
pub(crate) fn new(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Self {
let started = run::start(rt, code, options);
let state = match started {
Ok(r) => State::Running(r),
Err(outcome) => State::Failed(outcome),
};
Self::with(rt, state)
Self::with(rt.clone(), state)
}

fn with(rt: &'a Runtime, mut state: State) -> Self {
fn with(rt: Runtime, mut state: State) -> Self {
let shared = Arc::<Shared>::default();
if let State::Running(r) = &mut state {
r.vm.host.shared = shared.clone();
Expand All @@ -275,12 +277,9 @@ impl<'a> Program<'a> {
}

/// A program continuing a suspended run's state, checked against this runtime.
pub(crate) fn resume(
rt: &'a Runtime,
state: &Snapshot,
) -> Result<Self, snapshot::SnapshotError> {
pub(crate) fn resume(rt: &Runtime, state: &Snapshot) -> Result<Self, snapshot::SnapshotError> {
let running = restore(rt, state)?;
Ok(Self::with(rt, State::Running(running)))
Ok(Self::with(rt.clone(), State::Running(running)))
}

/// What suspends this run from another thread.
Expand All @@ -298,8 +297,9 @@ impl<'a> Program<'a> {

/// Runs the program as a future on any executor. Asynchronous host calls run on that executor; a timeout wakes
/// the run from a shared timer thread. Dropping the future interrupts the run and every host call in flight. A
/// stretch of compute longer than a millisecond continues on a worker thread, so the executor's thread is free
/// meanwhile; every host function, namespace and accessor still runs on the executor.
/// stretch of compute longer than a millisecond continues on a worker thread, unless [`Runtime::offload`] is
/// `false`, so the executor's thread is free meanwhile; every host function, namespace and accessor still runs on
/// the executor.
pub async fn run_async(self) -> Result<Outcome, Interrupted> {
self.run_resumable_async().await.map(done_or_suspended)
}
Expand All @@ -326,9 +326,10 @@ impl<'a> Program<'a> {
Ok(outcome)
}

/// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does.
/// [`Program::run_resumable`] as a future, which moves long stretches of compute as [`Program::run_async`] does
/// unless [`Runtime::offload`] was set to `false`.
pub async fn run_resumable_async(mut self) -> Result<RunOutcome, Interrupted> {
self.offload = true;
self.offload = cfg!(target_arch = "wasm32") || self.rt.setup().offload;
std::future::poll_fn(|cx| self.advance(cx)).await
}

Expand Down Expand Up @@ -649,7 +650,7 @@ impl<'a> Program<'a> {
let saved = r.vm.heap.len().saturating_sub(r.vm.snapshot_base.heap);
let skip = (saved / 800 + bytes.len() / 400_000) as u32;
let state = snapshot::from_bytes(&bytes).ok()?;
match restore(self.rt, &state) {
match restore(&self.rt, &state) {
Ok(mut fresh) => {
fresh.vm.host.shared = self.shared.clone();
// A round trip is not a pause: the run's clock keeps its start, which the header would
Expand Down Expand Up @@ -693,7 +694,7 @@ impl<'a> Program<'a> {
}
}

impl Drop for Program<'_> {
impl Drop for Program {
/// A run away on its worker is asked to stop at its next safe point and comes back, so it ends here, where its
/// host calls are cancelled.
fn drop(&mut self) {
Expand Down Expand Up @@ -765,8 +766,10 @@ fn roundtrip() -> bool {
const ROUNDTRIP_TICKS: u32 = 64;
const ROUNDTRIP_MAX: u32 = 1 << 16;

// A run's state may move to another thread between steps.
// A run and its state are owned and may move to another thread between steps.
const _: () = {
const fn send<T: Send>() {}
send::<Running>()
const fn owned<T: Send + 'static>() {}
send::<Running>();
owned::<Program>();
};
65 changes: 49 additions & 16 deletions rust/crates/psychoscript/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,15 +213,31 @@ impl ProgramOptions {
type GlobalsFn = dyn Fn(&Run) -> Vec<(String, HostValue)> + Send + Sync;

/// What a runtime shares with every run it starts.
#[derive(Default)]
#[derive(Clone)]
pub(crate) struct Setup {
pub globals: Option<Box<GlobalsFn>>,
pub globals: Option<Arc<GlobalsFn>>,
pub modules: Arc<[(String, String)]>,
pub limits: Limits,
pub translate: Translate,
pub program_lines: Option<(u32, u32)>,
pub locale: Option<Arc<dyn crate::locale::LocaleProvider>>,
pub measure_heap: bool,
pub offload: bool,
}

impl Default for Setup {
fn default() -> Self {
Self {
globals: None,
modules: Arc::from([]),
limits: Limits::default(),
translate: Translate::default(),
program_lines: None,
locale: None,
measure_heap: false,
offload: true,
}
}
}

impl Setup {
Expand All @@ -234,10 +250,11 @@ impl Setup {
}
}

/// A reusable confined runtime over host globals: each run of a program is independent.
#[derive(Default)]
/// A reusable confined runtime over host globals: each run of a program is independent. Cheap to clone, and shared
/// across threads.
#[derive(Clone, Default)]
pub struct Runtime {
setup: Setup,
setup: Arc<Setup>,
}

impl Runtime {
Expand All @@ -257,7 +274,7 @@ impl Runtime {
K: Into<String>,
V: Into<HostValue>,
{
self.setup.globals = Some(Box::new(move |run| {
Arc::make_mut(&mut self.setup).globals = Some(Arc::new(move |run| {
globals(run)
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
Expand All @@ -271,7 +288,7 @@ impl Runtime {
mut self,
modules: impl IntoIterator<Item = (K, V)>,
) -> Self {
self.setup.modules = modules
Arc::make_mut(&mut self.setup).modules = modules
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect::<Vec<_>>()
Expand Down Expand Up @@ -306,13 +323,13 @@ impl Runtime {
limits.max_source_bytes != Some(0),
"max_source_bytes must be at least 1."
);
self.setup.limits = limits;
Arc::make_mut(&mut self.setup).limits = limits;
self
}

/// How host calls' arguments carry functions and promises; see [`Translate`].
pub fn translate(mut self, translate: Translate) -> Self {
self.setup.translate = translate;
Arc::make_mut(&mut self.setup).translate = translate;
self
}

Expand All @@ -322,7 +339,17 @@ impl Runtime {
/// as the call was made), when there is one; so is [`Call::location`](crate::Call::location). Without it every
/// line is the program's.
pub fn program_lines(mut self, first: u32, last: u32) -> Self {
self.setup.program_lines = Some((first, last));
Arc::make_mut(&mut self.setup).program_lines = Some((first, last));
self
}

/// Whether a run driven as a future ([`Runtime::execute_async`], [`Program::run_async`],
/// [`Program::run_resumable_async`]) moves stretches of compute past 1 ms to a worker thread (`true` by default;
/// on wasm32, which yields to its executor instead, either way). Set to `false` to keep the run on the thread that
/// polls it, so its CPU time counts on that thread and no worker thread is started.
/// With `false`, a stretch of compute holds the polling thread until the next host wait or [`Limits::slice_ms`].
pub fn offload(mut self, offload: bool) -> Self {
Arc::make_mut(&mut self.setup).offload = offload;
self
}

Expand All @@ -331,15 +358,15 @@ impl Runtime {
/// [`Limits::max_heap_bytes`](crate::Limits::max_heap_bytes). Off by default; a limit's own measurements are the
/// same either way.
pub fn measure_heap(mut self, on: bool) -> Self {
self.setup.measure_heap = on;
Arc::make_mut(&mut self.setup).measure_heap = on;
self
}

/// What formats dates and numbers and compares strings for the locale-sensitive built-ins, instead of the default
/// ([`IcuLocale`](crate::locale::IcuLocale) with the `locale` feature, else
/// [`FallbackLocale`](crate::locale::FallbackLocale)); see [`LocaleProvider`](crate::locale::LocaleProvider).
pub fn locale(mut self, provider: impl crate::locale::LocaleProvider + 'static) -> Self {
self.setup.locale = Some(Arc::new(provider));
Arc::make_mut(&mut self.setup).locale = Some(Arc::new(provider));
self
}

Expand All @@ -365,8 +392,8 @@ impl Runtime {
}

/// A program, from its source or [compiled](Runtime::compile), ready to run once; nothing runs until
/// [`Program::run`] or [`Program::run_async`].
pub fn program<'c>(&self, code: impl Into<Code<'c>>, options: &ProgramOptions) -> Program<'_> {
/// [`Program::run`] or [`Program::run_async`]. Holds a clone of this runtime, so it is `'static`.
pub fn program<'c>(&self, code: impl Into<Code<'c>>, options: &ProgramOptions) -> Program {
Program::new(self, code.into(), options)
}

Expand All @@ -381,12 +408,12 @@ impl Runtime {
/// are made again for the run with its saved id and metadata. Fails with a [`SnapshotError`] when the state was
/// saved by another build, with other host globals, from a source that no longer compiles the same, or is
/// malformed or changed since it was saved.
pub fn resume(&self, state: &Snapshot) -> Result<Program<'_>, SnapshotError> {
pub fn resume(&self, state: &Snapshot) -> Result<Program, SnapshotError> {
Program::resume(self, state)
}

/// [`Runtime::resume`] from [`to_bytes`](crate::to_bytes).
pub fn resume_bytes(&self, bytes: &[u8]) -> Result<Program<'_>, SnapshotError> {
pub fn resume_bytes(&self, bytes: &[u8]) -> Result<Program, SnapshotError> {
let state = from_bytes(bytes)?;
Program::resume(self, &state)
}
Expand All @@ -395,3 +422,9 @@ impl Runtime {
&self.setup
}
}

// A runtime is shared across threads and cheap to clone.
const _: () = {
const fn shared<T: Clone + Send + Sync + 'static>() {}
shared::<Runtime>()
};
2 changes: 1 addition & 1 deletion rust/crates/psychoscript/tests/hostile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,7 @@ fn malformed_states_are_refused_or_resume_without_panicking() {
fn resumes<'r>(
rt: &'r Runtime,
label: &str,
resume: impl FnOnce(&'r Runtime) -> Result<psychoscript::Program<'r>, psychoscript::SnapshotError>,
resume: impl FnOnce(&'r Runtime) -> Result<psychoscript::Program, psychoscript::SnapshotError>,
) -> Vec<(String, String)> {
guarded(label, || {
if let Ok(program) = resume(rt) {
Expand Down
39 changes: 39 additions & 0 deletions rust/crates/psychoscript/tests/offload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,45 @@ fn later<T: Send + 'static>(ms: u64, value: T) -> impl Future<Output = T> {
})
}

#[test]
fn runtime_clones_and_program_is_static() {
let rt = Runtime::make().globals(|_| {
[(
"bump",
HostFunction::new(|args, _| HostValue::from(args[0].as_f64().unwrap_or(0.0) + 1.0)),
)]
});
let program = rt
.clone()
.offload(false)
.program("return bump(41)", &ProgramOptions::new());
drop(rt);
let future: Pin<Box<dyn Future<Output = _> + Send + 'static>> =
Box::pin(program.run_resumable_async());
let RunOutcome::Done(outcome) = drive(future).unwrap() else {
panic!("expected a completed run");
};
assert_eq!(outcome.json().unwrap(), json!(42));
}

#[test]
fn offload_false_keeps_compute_on_the_calling_thread() {
use psychoscript::thread_clock::ThreadClock;

// Without offloading, a fixed compute loop finishes in the single poll on this thread's CPU clock.
let rt = Runtime::make().offload(false);
let work = "let n = 0; for (let i = 0; i < 6e5; i++) n += i % 3; return n";
let mut run = Box::pin(rt.program(work, &ProgramOptions::new()).run_async());
let clock = ThreadClock::current();
let before = clock.now();
let Poll::Ready(Ok(outcome)) = run.as_mut().poll(&mut Context::from_waker(Waker::noop()))
else {
panic!("expected single-poll completion without offloading");
};
assert_eq!(outcome.json().unwrap(), json!(600_000));
assert!(clock.now() > before);
}

/// Polls a future to its end on this thread, parking until it is woken.
fn drive<F: Future>(future: F) -> F::Output {
struct Unpark(thread::Thread);
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/psychoscript/tests/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ fn options(run_id: &str) -> ProgramOptions {
}

/// Runs `program` on this thread while `during` runs on another with its suspender.
fn background<'a, T: Send>(
program: Program<'a>,
fn background<T: Send>(
program: Program,
during: impl FnOnce(Suspender) -> T + Send,
) -> (RunOutcome, T) {
let suspender = program.suspender();
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/psychoscript/tests/streaming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ impl Waiting {

/// Runs `program` on this thread while `during` runs on another with its suspender.
fn background<T: Send>(
program: Program<'_>,
program: Program,
during: impl FnOnce(Suspender) -> T + Send,
) -> (RunOutcome, T) {
let suspender = program.suspender();
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/psychoscript/tests/value_depth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ fn resumed_argument(depth: usize) -> HostValue {
}

/// Suspends `program` once `ready` says its call has started.
fn suspend<T: Send>(program: psychoscript::Program<'_>, ready: mpsc::Receiver<T>) -> Snapshot {
fn suspend<T: Send>(program: psychoscript::Program, ready: mpsc::Receiver<T>) -> Snapshot {
let suspender = program.suspender();
let outcome = std::thread::scope(|s| {
s.spawn(move || {
Expand Down