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
2 changes: 2 additions & 0 deletions rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ Known differences:
`timeout_ms` and `slice_ms`, as in the reference. `regress` has no step budget; bound untrusted patterns or inputs.
- A saved state changed since it was saved is refused (its header holds a hash of it), but resuming doesn't validate a
forged one in full and may panic (in safe Rust): store saved states as you would code.
- The run drops what a host gives it without recursing, at any depth, but a `HostValue` a host makes and drops itself
drops recursively, like a `serde_json::Value`: one nested past about 10,000 levels is the host's to take apart.
- On wasm32, a run driven as a future that waits on a host call notices its timeout only when it is next polled.
- The round-trip conformance run (`PSYCHOSCRIPT_ROUNDTRIP=1`) failed once on a heavily loaded machine and didn't
reproduce in 52 runs since; its quiet panic hook doesn't name the failing case.
Expand Down
123 changes: 99 additions & 24 deletions rust/crates/psychoscript/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ pub enum Settlement {

/// A host call's outcome, with what converting it needs.
pub struct Settled {
pub result: HostResult,
pub result: Held,
/// Names the call in conversion errors.
pub label: String,
/// The global host function whose `snapshot` hooks save functions in the value, by label.
Expand All @@ -114,6 +114,33 @@ pub struct Settled {
pub site: Option<crate::bytecode::CallSite>,
}

/// A host call's outcome, which the host makes and may nest at any depth: dropped without recursing, unless the program
/// took it (`true`), which leaves nothing deeper than `Limits::max_value_depth`.
pub struct Held(HostResult, bool);

impl std::ops::Deref for Held {
type Target = HostResult;

fn deref(&self) -> &HostResult {
&self.0
}
}

impl Drop for Held {
#[inline]
fn drop(&mut self) {
if !self.1 {
dispose(&mut self.0);
}
}
}

#[cold]
fn dispose(r: &mut HostResult) {
let (Ok(v) | Err(v)) = r;
std::mem::take(v).discard();
}

impl Settlement {
pub(crate) fn host(
result: HostResult,
Expand All @@ -122,7 +149,7 @@ impl Settlement {
site: Option<crate::bytecode::CallSite>,
) -> Self {
Settlement::Host(Box::new(Settled {
result,
result: Held(result, false),
label,
owner,
site,
Expand Down Expand Up @@ -231,6 +258,13 @@ pub struct ResultRoot {
pub functions: std::ops::Range<usize>,
}

// What it keeps is a host's result, which may nest at any depth past what the program took of it.
impl Drop for ResultRoot {
fn drop(&mut self) {
std::mem::take(&mut self.value).discard();
}
}

/// A run's id, shared by its calls and made the first time it is read, when the host gave none.
pub(crate) type RunId = Arc<std::sync::OnceLock<String>>;

Expand Down Expand Up @@ -322,6 +356,9 @@ pub struct RunHost {
pub(crate) promise_like: Option<Id>,
/// Whether a call interrupted the run.
pub interrupted: bool,
/// Set when a host value copied in had an error, whose cause and fields the copy may leave out: the value may then
/// nest past `Limits::max_value_depth`.
pub(crate) partial: bool,
/// Moving long stretches of compute to a worker thread, for a run driven as a future. Boxed: the VM's hot fields
/// sit after this struct, and a few more bytes here measurably slow its dispatch loop.
pub(crate) offload: Option<Box<crate::offload::Offload>>,
Expand Down Expand Up @@ -423,6 +460,7 @@ impl RunHost {
suggestions: FxHashMap::default(),
promise_like: None,
interrupted: false,
partial: false,
unhandled: Vec::new(),
offload: None,
modules_loaded: FxHashMap::default(),
Expand Down Expand Up @@ -624,7 +662,10 @@ fn define_host_global(vm: &mut Vm, name: &str) -> bool {
installed: true,
within: None,
};
from_host(vm, value, name, &place, 0).unwrap_or(Value::Undef)
let v = from_host(vm, value, name, &place, 0).unwrap_or(Value::Undef);
// The runtime keeps its globals, whole or not.
vm.host.partial = false;
v
}
};
global(vm, name, v);
Expand Down Expand Up @@ -663,7 +704,7 @@ pub(crate) fn native(vm: &mut Vm, name: &str, length: u8, f: NativeFn, data: Val
pub enum Start {
Call,
Again,
Wait(Data),
Wait(Kept),
}

/// A promise was rejected with nothing to handle it: a warning, unless something handles it before the run ends.
Expand Down Expand Up @@ -707,28 +748,31 @@ pub fn settle(vm: &mut Vm, p: Id, s: Settlement) {
locate_settled(vm, &e, site, Some(p));
vm.reject(p, e);
}
Settlement::Host(settled) => {
Settlement::Host(mut settled) => {
let Settled {
result,
label,
owner,
site,
} = *settled;
match result {
} = &mut *settled;
match &mut result.0 {
Ok(v) => {
let v = result_from_host(vm, v, &label, owner.as_deref());
let v = result_from_host(vm, v, label, owner.as_deref());
match v {
Ok(v) => vm.fulfill(p, v),
Ok(v) => {
result.1 = true;
vm.fulfill(p, v)
}
Err(e) => {
// The reference converts the value at the call, so its errors point there.
locate_settled(vm, &e, site, Some(p));
locate_settled(vm, &e, *site, Some(p));
vm.reject(p, e)
}
}
}
Err(HostValue::Interrupt) => interrupt(vm),
Err(thrown) => {
let e = thrown_value(vm, &thrown, &label, site, Some(p));
let e = thrown_value(vm, thrown, label, *site, Some(p));
vm.reject(p, e);
}
}
Expand All @@ -745,7 +789,7 @@ fn thrown_value(
site: Option<crate::bytecode::CallSite>,
settled: Option<Id>,
) -> Value {
match thrown {
let e = match thrown {
HostValue::Located(he) => {
let proto = error_proto(vm, he.name.as_str().unwrap_or_default());
let e = vm.failure(
Expand Down Expand Up @@ -773,7 +817,10 @@ fn thrown_value(
e
}
thrown => from_host(vm, thrown, label, &Place::default(), 0).unwrap_or_else(|e| e),
}
};
// The caller discards what was thrown, whole or not.
vm.host.partial = false;
e
}

/// Points an error the VM made, not yet located, at a host call's source site.
Expand Down Expand Up @@ -1071,15 +1118,20 @@ fn sync_result(
interrupt(vm);
Err(Value::Undef)
}
Returned::Now(Ok(v)) => {
Returned::Now(Ok(mut v)) => {
let site = vm.call_location();
let v = result_from_host(vm, v, &target.label, target.owner.as_deref())
.inspect_err(|e| locate_at(vm, e, site))?;
let v = result_from_host(vm, &mut v, &target.label, target.owner.as_deref())
.inspect_err(|e| {
locate_at(vm, e, site);
std::mem::take(&mut v).discard();
})?;
Ok(if f.thenable { promise_like(vm, v) } else { v })
}
Returned::Now(Err(thrown)) => {
let site = vm.call_location();
Err(thrown_value(vm, &thrown, &target.label, site, None))
let e = thrown_value(vm, &thrown, &target.label, site, None);
thrown.discard();
Err(e)
}
Returned::Pending(work) => {
let site = vm.call_location();
Expand Down Expand Up @@ -1291,7 +1343,7 @@ fn spawn_call(vm: &mut Vm, p: Id, f: &Callee, mut r: Restart, holds_functions: b
};
let (d2, phase, waiting) = (d.clone(), data.clone(), durable.clone());
let started: BoxFuture<'static, Result<Data, HostValue>> = match again {
Some(data) => Box::pin(async move { Ok(data) }),
Some(data) => Box::pin(async move { Ok(data.into_inner()) }),
None => match &home {
None => (d.start)(r.args.clone(), call),
Some(home) => {
Expand Down Expand Up @@ -2033,6 +2085,7 @@ fn error_proto(vm: &mut Vm, name: &str) -> Id {
}

fn error_from_host(vm: &mut Vm, e: &HostError, label: &str, depth: usize) -> Result<Value, Value> {
vm.host.partial = true;
let next = |key: &str| format!("{label}.{key}");
let proto = error_proto(vm, e.name.as_str().unwrap_or_default());
let err = vm.make_error(proto, &e.message.to_run_text());
Expand Down Expand Up @@ -2352,10 +2405,10 @@ fn response_fn(vm: &mut Vm, f: HostFunction, label: &str, place: &Place) -> Valu
}

/// A host call's result copied in. When it is saved by an owner's `snapshot` hooks and holds functions, the value is
/// kept so a suspend can save them.
/// kept so a suspend can save them. What is left of a value it refuses may nest at any depth: the caller discards it.
fn result_from_host(
vm: &mut Vm,
v: HostValue,
v: &mut HostValue,
label: &str,
owner: Option<&str>,
) -> Result<Value, Value> {
Expand All @@ -2365,18 +2418,25 @@ fn result_from_host(
installed: false,
within: owner.map(str::to_owned),
};
let out = from_host(vm, &v, label, &place, 0);
let out = from_host(vm, v, label, &place, 0);
// The buffers its typed arrays matched are done with.
vm.lends.clear();
let end = vm.host.functions.len();
if let Some(owner) = owner
&& end > start
&& out.is_ok()
{
vm.host.results.push(ResultRoot {
owner: owner.to_owned(),
value: v,
value: std::mem::take(v),
functions: start..end,
});
vm.host.partial = false;
} else if vm.host.partial {
// An error copied without parts it couldn't take: it may nest at any depth. Copied in whole, it is no deeper
// than `max_value_depth`, and drops as Rust drops it.
vm.host.partial = false;
std::mem::take(v).discard();
}
out
}
Expand Down Expand Up @@ -2416,13 +2476,26 @@ fn own_properties(
};
for (k, item) in properties {
let path = format!("{label}.{}", k.to_string_lossy());
let val = from_host(vm, item, &path, &place.child(Some(k)), depth + 1)?;
let val = from_host(vm, item, &path, &place.child(Some(k)), depth + 1)
.inspect_err(|_| shed_properties(vm, id))?;
let key = vm.atoms.intern(&k.to_run_text());
vm.define(id, key, val);
}
Ok(made)
}

/// A function whose own properties the program refused keeps none: they may nest at any depth, and the value they came
/// in, which the caller discards, is left their only holder.
#[cold]
fn shed_properties(vm: &mut Vm, id: Id) {
if let Value::Num(index) = vm.native_data(id) {
match &mut vm.host.functions[index as usize].f {
Callee::Fn(f) => f.properties = Arc::new([]),
Callee::Durable(f) => f.properties = Arc::new([]),
}
}
}

/// A host function as a program function, at `label`. A host function made with no name is named by where it is.
/// A constructible one is called the same way by `new`.
fn wrap(vm: &mut Vm, f: Callee, label: &str, place: &Place, owner: Option<String>) -> Value {
Expand Down Expand Up @@ -2734,6 +2807,8 @@ pub(crate) fn namespace_keys(vm: &mut Vm, id: Id) -> Result<Vec<HostString>, Val
listed.map_err(|thrown| {
let label = vm.ns_label(&ns);
let site = vm.call_location();
thrown_value(vm, &thrown, &label, site, None)
let e = thrown_value(vm, &thrown, &label, site, None);
thrown.discard();
e
})
}
75 changes: 75 additions & 0 deletions rust/crates/psychoscript/src/host_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,81 @@ pub enum HostValue {
Interrupt,
}

/// How deep `HostValue::discard` recurses at a time, as `Data::discard`.
const LEVELS: usize = 64;

impl HostValue {
/// Drops the value recursing at most `LEVELS` deep at a time: a value the host makes may nest deeper than a
/// recursive drop gets on any stack, so what the run drops of the host's, it drops with this.
#[inline(never)]
pub(crate) fn discard(self) {
let mut deeper = Vec::new();
self.drop_within(LEVELS, &mut deeper);
while let Some(v) = deeper.pop() {
v.drop_within(LEVELS, &mut deeper);
}
}

/// Drops `levels` levels of the value, leaving what is deeper in `deeper`.
fn drop_within(self, levels: usize, deeper: &mut Vec<HostValue>) {
match self {
v if levels == 0 && v.holds_values() => deeper.push(v),
HostValue::Array(items) => items
.into_iter()
.flatten()
.for_each(|i| i.drop_within(levels - 1, deeper)),
HostValue::Object(fields) => fields
.into_iter()
.for_each(|(_, v)| v.drop_within(levels - 1, deeper)),
HostValue::Map(entries) => entries.into_iter().for_each(|(k, v)| {
k.drop_within(levels - 1, deeper);
v.drop_within(levels - 1, deeper);
}),
HostValue::Set(items) => items
.into_iter()
.for_each(|i| i.drop_within(levels - 1, deeper)),
HostValue::Error(e) | HostValue::Located(e) => {
let HostError { cause, fields, .. } = *e;
if let Some(c) = cause {
(*c).drop_within(levels - 1, deeper);
}
fields
.into_iter()
.for_each(|(_, v)| v.drop_within(levels - 1, deeper));
}
HostValue::Function(mut f) => drop_properties(&mut f.properties, levels, deeper),
HostValue::Durable(mut f) => drop_properties(&mut f.properties, levels, deeper),
_ => {}
}
}

/// Whether it holds other values.
#[inline]
fn holds_values(&self) -> bool {
matches!(
self,
HostValue::Array(_)
| HostValue::Object(_)
| HostValue::Map(_)
| HostValue::Set(_)
| HostValue::Error(_)
| HostValue::Located(_)
| HostValue::Function(_)
| HostValue::Durable(_)
)
}
}

/// Drops `levels` levels of a function's own properties, leaving what is deeper in `deeper`, when it is their only
/// holder; others drop them when they're done.
fn drop_properties(properties: &mut Properties, levels: usize, deeper: &mut Vec<HostValue>) {
if let Some(items) = Arc::get_mut(properties) {
items
.iter_mut()
.for_each(|(_, v)| std::mem::take(v).drop_within(levels - 1, deeper));
}
}

impl HostValue {
pub fn object<K: Into<HostString>>(fields: impl IntoIterator<Item = (K, HostValue)>) -> Self {
HostValue::Object(fields.into_iter().map(|(k, v)| (k.into(), v)).collect())
Expand Down
4 changes: 2 additions & 2 deletions rust/crates/psychoscript/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ impl Enc<'_> {
owner,
site,
} = h.as_ref();
let (ok, v) = match result {
let (ok, v) = match &**result {
Ok(v) => (true, v),
Err(v) => (false, v),
};
Expand Down Expand Up @@ -3146,7 +3146,7 @@ fn restore_host(vm: &mut Vm, dec: &Dec, j: &J, base: Base) -> R<()> {
vm.host.key(call)
)));
}
host::Start::Wait(data_from(at(start, 1)?)?)
host::Start::Wait(crate::data::Kept(data_from(at(start, 1)?)?))
}
_ => return Err(invalid("a call in flight is unknown.")),
};
Expand Down
Loading