Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
e03b498
feat(stdlib): return Option from public index_of lookups
fffonion Nov 14, 2026
6eca4e1
refactor(stdlib): drop the duplicate found flag from LRU results
fffonion Nov 14, 2026
0f2d161
refactor(runtime): report Unit from command-style host calls
fffonion Nov 14, 2026
1989e0a
fix(wasm): return Unit from the sleep completion
fffonion Nov 14, 2026
ace8b06
feat(typing): type builtin guest unions from their host contracts
fffonion Nov 14, 2026
4ac0391
feat(io): report IO outcomes as Result instead of sentinels
fffonion Nov 14, 2026
9b7bc44
test(stdlib): assert LRU row values instead of a -1 sentinel
fffonion Nov 14, 2026
bb719cf
fix(io): keep a closed async handle fatal and migrate the IO call sites
fffonion Nov 14, 2026
16ae08b
test(io): pin the fatal close at the call site, not just in the helper
fffonion Nov 14, 2026
aa2a001
feat(host): port the runtime-owned stack descriptor adapter
fffonion Nov 14, 2026
cc156f3
test(standard): re-pin the catalog fingerprints after the IO Result c…
fffonion Nov 14, 2026
f53bb62
feat(host): port the runtime_owned_pending macro attribute
fffonion Nov 14, 2026
e01ee77
chore(vscode): sync the canonical TextMate grammar with spec master
fffonion Nov 14, 2026
9b86a27
test(examples): move the canonical examples onto the Unit/Option/Resu…
fffonion Nov 14, 2026
fc8b0c8
test(host): cover runtime_owned_pending on the inferred contract path
fffonion Nov 14, 2026
8db4583
refactor(wire): expose the VMBC codec without the runtime feature
fffonion Nov 15, 2026
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
76 changes: 76 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1284,6 +1284,9 @@ fn render_builtin_runtime_dispatch(
.unwrap();
writeln!(&mut out, " }}").unwrap();
writeln!(&mut out, "}}").unwrap();
writeln!(&mut out).unwrap();

render_builtin_guest_return_schema_method(&mut out, builtin_callables);

out
}
Expand Down Expand Up @@ -1647,6 +1650,79 @@ fn render_builtin_static_return_type_method(
writeln!(out).unwrap();
}

/// Emits `guest_return_schema` into the runtime dispatch unit: the guest
/// return schema a namespaced builtin's published descriptor declares.
///
/// A carrier's coarse `ValueType` cannot express its payloads (and the nominal
/// resource keys inside them), so the schema comes from the same descriptor the
/// module catalog publishes — a declared contract when the function has one,
/// otherwise the signature-derived schema. Only `Result` carriers are surfaced
/// to the compiler; every other return keeps the `ValueType` inference.
///
/// The method lives in the dispatch unit because that unit owns the private
/// backend modules (`io`, `math`, `host`, …) the descriptors are declared in.
fn render_builtin_guest_return_schema_method(out: &mut String, builtin_callables: &[CallableDecl]) {
writeln!(out, "impl BuiltinFunction {{").unwrap();
writeln!(
out,
" /// The guest return schema this builtin's published descriptor declares."
)
.unwrap();
writeln!(out, " ///").unwrap();
writeln!(
out,
" /// Only `Result` carriers are reported: a scalar return is already fully"
)
.unwrap();
writeln!(
out,
" /// described by `static_return_type`, while a carrier's payloads and the"
)
.unwrap();
writeln!(
out,
" /// nominal resource keys inside them only exist in the descriptor."
)
.unwrap();
writeln!(
out,
" pub(crate) fn guest_return_schema(self) -> Option<crate::host_api::HostTypeSchema> {{"
)
.unwrap();
writeln!(out, " let schema = match self {{").unwrap();
for callable in builtin_callables
.iter()
.filter(|callable| callable.wrapper.is_some())
{
let variant = builtin_variant_name(&callable.name);
let module = &callable.module;
let wrapper_name = callable
.rust_ident
.strip_suffix("_impl")
.unwrap_or(&callable.rust_ident);
writeln!(
out,
" BuiltinFunction::{variant} => \
{module}::{wrapper_name}_descriptor().schema.return_type,"
)
.unwrap();
}
writeln!(
out,
" _ => crate::host_api::HostTypeSchema::Unknown,"
)
.unwrap();
writeln!(out, " }};").unwrap();
writeln!(
out,
" matches!(schema, crate::host_api::HostTypeSchema::Result {{ .. }}).then_some(schema)"
)
.unwrap();
writeln!(out, " }}").unwrap();
writeln!(out, "}}").unwrap();
writeln!(out).unwrap();
}

fn render_builtin_signature_method(out: &mut String, builtin_variant_order: &[String]) {
writeln!(
out,
Expand Down
83 changes: 70 additions & 13 deletions docs/host-sdk-descriptors.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ One host function declaration produces, in a single macro expansion:
| Part | Meaning |
|---|---|
| `schema` | The guest ABI: parameter names, types, passing modes, return type. This is the only fingerprint input. |
| `binding` | The dispatch class (`Static`, `StaticStack`, `StaticArgs`, `StaticNonYieldingArgs`, `Owned`). |
| `binding` | The dispatch class (`Static`, `StaticStack`, `StaticStackRuntimeOwned`, `StaticArgs`, `StaticNonYieldingArgs`, `Owned`). |
| `adapter` | The concrete adapter or owned-dispatch factory installed into a registry. |
| `effects` | Guest resource effects (borrow/borrow-mut/take-owned/create) and hidden host-state read/write effects. Runtime-only metadata; excluded from the fingerprint. |
| `resource_types` | The concrete resource-type declarations this function contributes. |
Expand Down Expand Up @@ -212,26 +212,48 @@ pub(crate) async fn builtin_io_open(
#[pd_host_context] context: IoPolicyContext,
path: String,
mode: String,
) -> VmResult<vm::HostFutureOutput<i64>> {
) -> VmResult<vm::HostFutureOutput<Value>> {
// Mode validation and `OpenOptions` setup are omitted here.
let path = authorize_io_path(context.policy.as_ref(), &path, writes).await?;
let file = options
.open(path)
.await
.map_err(|error| VmError::HostError(format!("io_open failed: {error}")))?;
let file = match options.open(path).await {
Ok(file) => file,
// A recoverable failure is the contract's `Err` branch, never a VM fault.
Err(error) => return Ok(io_error_output("io_open", error)),
};
let handle = IoHandle::File(BufReader::new(file));
Ok(vm::HostFutureOutput::complete(move |vm| {
let token = vm
.execution_scope()
.push_resource(IoResource::new(handle))
.map_err(|error| VmError::HostError(format!(
"io resource insert failed: {error}"
)))?;
Ok(token.into_handle().raw() as i64)
publish_open_handle(vm, handle, super::io_open_contract().return_type)
}))
}
```

A contract may also declare a fallible return. `io::open`, `io::popen`,
`io::read_all`, `io::read_line`, `io::write`, `io::flush` and `io::close`
declare `Result<T, string>`, where only ordinary file-system outcomes take the
`Err` branch: invalid or closed handles, ownership/scope errors, policy denials,
byte limits, unsupported modes and capability rejections stay fatal `VmError`s.

An owned resource cannot cross the future boundary inside a `GuestResult` (the
macro rejects it), so the async adapter returns the assembled guest carrier
through `vm::HostFutureOutput<Value>` and publishes it with
`crate::result::publish_owned`, which inserts the resource, validates the
carrier against the declared contract and rolls the insertion back on failure.
That path is specific to the successful branch: it is the one that must agree
with `io::open` / `io::popen`'s `Ok(resource<io.file>)` outcome. The `Err`
branches (an unopenable path, a process that cannot be started) are plain
`Value` strings built by the adapter itself, so they carry no resource and are
never routed through `publish_owned` — there is nothing to insert or roll back.
They are not unchecked, though: every return, including these, still passes the
generic `validate_host_call_return` check
(`src/vm/host.rs:2141` → `validate_host_value`) when the operation completes,
which validates the value against the declared `Result` schema. What they
deliberately skip is resource ownership bookkeeping, not schema validation.

`io::read_line`'s success payload is the line **without** its terminator: the
adapter strips one trailing `\n`, so a file ending in `\r\n` leaves the `\r`
in the payload. End of file is `Ok(None)`, and a present but empty line is
`Ok(Some(""))`; the two are never conflated.

When context depends on a resource-token argument, implement
`capture_with_args(vm, args)` to validate the token and clone the owned resource
state before submission. `IoHandleContext`, `SqliteConnectionContext`, and
Expand Down Expand Up @@ -357,6 +379,41 @@ operand draining, callback provenance, isolated callback VM, and transactional
owned-resource transfer. Do not route an owned function through borrowed or
static dispatch.

### Runtime-owned pending dispatch

A stack adapter whose call suspends — the HTTP request and SQLite statement
families are the standard examples — resolves its pending operation from the
generic VM operation/stream registries (submitted host operations and stream
drivers) instead of from a per-function operation driver. Descriptors express
that with `HostBindingKind::StaticStackRuntimeOwned` and the stack adapter:

```rust
HostFunctionDescriptor {
schema: http_request_contract(),
binding: HostBindingDescriptor { kind: HostBindingKind::StaticStackRuntimeOwned },
effects: vec![],
adapter: HostAdapterDescriptor::StaticStackRuntimeOwned(builtin_http_client_request),
resource_types: vec![],
}
```

The adapter is a `StaticHostStackFunction`, exactly like `StaticStack`: the two
classes register identically. The difference is the install step — after the
import registers, the module install path calls
`HostFunctionRegistry::mark_exact_runtime_owned_pending(&name)`, which fails
closed for a name that is not registered:

```
cannot mark unregistered host import '<name>' as runtime-owned
```

The marker records no per-import state: submitted operations are keyed by their
reserved host-operation id, so there is no parallel op-driver table to maintain.
Choose `StaticStackRuntimeOwned` only when the call's pending operation is owned
by those generic registries. A module that schedules its own concrete operation
driver (the `io::*` family) keeps plain `StaticStack`, and an owned-dispatch
function that transfers its operands keeps `Owned`.

## 6. Aggregation and feature gates

A build composes modules through one deterministic list. The standard library's
Expand Down
6 changes: 6 additions & 0 deletions docs/standard-timer-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ are `DEFAULT_MAX_PENDING_TIMERS` (1024) pending registrations and
re-exported at the crate root, and an embedding can install different
`TimerConfig` limits.

`timer::at` / `timer::every` report the logical Unit result. A successful
registration therefore has no payload to inspect: the callback transfer is the
whole effect, and a rejected registration is the ordinary `VmResult` error
(the callback operand returns to the guest exactly once). The synchronous count
queries stay real `int` results.

The callback parameter is typed `fn(bool) -> unknown`: the callback observes the
`premature` flag and its **return value is discarded**, so the declared result
is `unknown` — an `int`/`string`/`map`/`bool`/`()` body compiles and runs,
Expand Down
6 changes: 4 additions & 2 deletions examples/example_complex.rss
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,16 @@ struct PayloadPartial {
let payload_json = json::encode(payload);
let payload_decoded = json::decode::<PayloadPartial>(payload_json);
let json_score = payload_decoded.score;
let sleep_ok = runtime::sleep(100);
// `runtime::sleep` reports the logical Unit result, so there is no success value
// to compare; the completed wait is the whole effect.
runtime::sleep(100);
let io_ok = if true => {
io::exists(".")
} else => {
false
};

if regex_ok && io_ok && sleep_ok && json_score == matched {
if regex_ok && io_ok && json_score == matched {
print(closure_value);
} else {
print(0);
Expand Down
Loading
Loading