Switch to dark theme

The life of a call

Read How values cross first. This page follows one call, from the macro that plans it to the value that comes back.

One plan

The macros check each exported signature once (types::Signature in bimetal-macros/src/types/callable.rs), for the contract and every host, and plan every wrapper with one planner, wrapper::plan in bimetal-macros/src/export/wrapper.rs. It decodes the arguments, reaches the resource value, calls Rust, and converts the result, the same way for sync and async calls, free functions and resource members.

Where hosts differ, it asks the host (HostBackend in export/host_backend.rs) instead of branching on it, and each host's item shells live in their own file: export/python.rs, export/node.rs and export/wasm.rs. The wrappers carry the final host names of their parameters, which their argument errors use.

Into Rust

Python. A scalar, a container of scalars, bytes, a buffer or an Arrow value crosses as it is, and so does an absent optional argument, as None. A resource crosses as its native object, and a function as itself, unless an argument that Rust passes it reaches a buffer, which host_callback has Pydantic restore. The extension also reads a model instance of its generated class, a generated variant of an enum with data, a datetime, a date and a duration as Python holds them, field by field, by a plan of the type that each call site keeps (bimetal/src/convert/python_plan.rs), stopping at 128 levels of nesting so native recursion can't overflow the stack. An argument that the plan can't read, such as a dictionary passed for a model or a deeper value, raises Revalidate, and the generated code calls again with Pydantic's dump of it inside a Dumped. Pydantic validates the value, so that it meets the model's rules, and writes it in its JSON mode, which Rust reads with pythonize. An argument that reaches a buffer, and a serde_json::Value, always cross as that dump, because the plan doesn't read them. A serde_json::Value has rules of its own, which its type JsonValue applies only in a dump that crosses. Rust then checks the field rules, skipping types that carry none at compile time.

Each generated module keeps its native functions, and an Adapter for each type that it validates or writes, in constants that it defines once below its imports. An adapter builds Pydantic's TypeAdapter at its first call, so a call neither evaluates an annotation nor looks a validator up, and importing the package builds none. A brief function whose Python function would only pass its arguments on is the native function itself, which the module binds in its place, so a call crosses no Python frame.

TypeScript. checkArgument checks the outermost type of each argument. A scalar, a string enum, a scalar alias, a list or tuple of those, or a typed array crosses as it is, and prepareHost walks every other value with its schema, which a constant of the module holds, referencing models by index in nativeSchemas. That table holds only the models that the generated modules reach, and omits fields and variants whose schema is null. prepareHost visits only the fields whose schema asks for a change, and checks that each Option field that its model marks required is present, since Serde would read a missing one as None. It returns the caller's value itself where nothing in it changes, and copies an array or an object only once one of its items changes, or when an object is not a plain one. Then serde-wasm-bindgen reads it, and Rust checks its field rules. The addon reads it with bimetal::convert::node, whose deserializer follows serde-wasm-bindgen's checks, order and messages, stops at 128 levels of nesting, where native recursion could overflow the stack, and copies bytes and buffers once out of their typed arrays.

Out of Rust

Python. Rust checks the field rules, and the extension makes the value by the plan of its type: a model becomes an instance of its generated class, a date-time becomes a datetime, and a direct buffer (or Option of one) is a bytearray wrapped with a cached numpy.frombuffer without a copy, so the generated code neither restores nor validates them. A compound value that reaches a buffer is the exception: pythonize writes it, restore_host makes its buffers from bytearrays via the same cached numpy.frombuffer, and Pydantic validates it. A typed error is an instance of the generated package's exception class, which the extension makes without calling the class. An extension loaded without its generated package makes plain values, as pythonize does.

TypeScript. Rust checks the field rules. In the Wasm module, serde-wasm-bindgen writes the value, with maps as Maps, and restoreHost turns each map into a plain object, where a __proto__ key stays data, restores bytes and buffers, and freezes the rest of the value in place, since nothing else holds what Rust made. The addon makes each object, array and map with one call into JavaScript, already frozen, so restoreHost returns such a value as it is. It copies bytes and buffers once into plain typed arrays, never a Node.js Buffer.

Arrow

Python. The Arrow PyCapsule interface, both ways, without a copy (bimetal/src/convert/python_arrow.rs), around the C Data Interface code in convert/arrow_ffi.rs. Imports are validated. Rust exports small objects that pa.array, pa.record_batch, pa.table, pa.schema and pa.RecordBatchReader.from_stream import.

A RecordBatchStream (bimetal/src/arrow/record_batch_stream.rs) holds an async stream or a blocking reader. Exported, it is an ArrowArrayStream whose get_next waits on the calling thread, with the interpreter lock released if that thread holds it: a blocking reader runs there, and an async stream is polled there inside Bimetal's runtime, with a Tokio worker's other work handed away first. The first failure or panic is kept, so every later get_next fails with its message, and the source drops when the stream ends. In a forked child the stream fails and leaks its source, as Abort leaves the parent's tasks alone. Imported, a stream reads its schema at once and its batches as Rust asks: synchronous code calls get_next on its own thread, and a poll_next hands the call to a blocking thread of the runtime that polls it.

TypeScript streams. Both backends share arrow_ipc's Outgoing and Feed and the adapters in arrow.js; only the object that carries them differs, closures in convert/wasm_arrow.rs and two classes that the addon registers in convert/node/arrow.rs. A returned stream is an object whose schema is an IPC stream and whose next() resolves with each batch as an IPC stream of its own, which the generated RecordBatchStream decodes. A stream argument is a source that the async wrapper opens: Rust gives its start a feed, whose asked() resolves when Rust polls for a batch and resolves false once the stream drops, and the source answers with write, finish or fail. The addon's asked() doesn't hold the event loop, since Rust's own calls do while it reads. A synchronous call can't wait for JavaScript, so blocking code that reads such a stream fails rather than hangs: in Wasm when the stream waits for anything, and on the addon when it waits on the JavaScript thread. An async call that reads a stream it already holds, but doesn't take as an argument, is the exception: it makes its first poll on that thread. An async read there, as in Rows::sum, returns Pending (executor::in_first_poll), and the call continues on a worker. A blocking read inside that poll, as in Rows::sum_at_once, clears the mark until it ends (executor::leave_first_poll, which block_on holds), so it fails there too. A panic ends a returned stream, as a failure does. Wasm reads go through checkNative and nativePromise, so a trap rejects them as it rejects calls.

TypeScript. An Arrow IPC stream (bimetal/src/convert/arrow_ipc.rs): tableToIPC and one copy into Rust memory, where the decoder keeps aligned buffers, and on return one copy out and tableFromIPC, which keeps views. JavaScript can't keep a view into Wasm memory, because growing it detaches the views, and apache-arrow has no C Data Interface for the addon.

Async on Python

bimetal::runtime::python::awaitable polls the future once on the caller's thread, without the interpreter lock and inside Bimetal's shared Tokio runtime (executor::first_poll in bimetal/src/runtime/executor.rs). A future that is ready settles its asyncio future there, and no worker runs it, though the first call starts the runtime's threads. A future that waits becomes a task of the runtime, whose first poll replaces the waker of the caller's poll. The asyncio future waits in a slot that only code holding the interpreter lock touches, and a done callback aborts the task when the caller cancels the future. A Callback argument is the exception to the task owning no Python object: if its last clone drops on a worker, PyO3 defers the release to its reference pool.

The worker that finishes a call posts it to its event loop's mailbox (bimetal/src/runtime/mailbox.rs), and wakes the loop only when the mailbox was empty. On Unix the loop watches one end of a socket pair with add_reader, and the worker writes a byte to the other end without the interpreter lock, so a result reaches the loop with one wake-up. The loop then converts every result in the mailbox and settles each future, so calls that finish together settle in one turn of the loop. A loop without add_reader, such as Windows' proactor, is woken by a blocking thread that takes the interpreter lock and calls call_soon_threadsafe, once for each batch. A mailbox belongs to the process that made it: a forked child leaks the parent's mailboxes, whose locks a worker may have held at the fork, and makes its own.

Each async export keeps a pace (bimetal/src/runtime/pace.rs): a running average of the time that its calls spend in their polls, and the count of its calls that run on workers. A call starts on a worker when its export works for more than 2.5 times the 25 µs that a hand-off costs, or for more than the hand-off while other calls of it run on workers, so long work leaves the event loop free and concurrent calls spread over cores. While an export works for 6 µs or more, each of its calls times itself, and so does the call after one that took that long; otherwise one call in eight does. A call counts as the lesser of its time and that of the last timed call, so a call that the scheduler stalled moves no later call. Each counted call moves the average a quarter of the way, so calls of more than about 250 µs move their export after two in a row, and shorter long calls after a few more.

A call that takes a Callback or a RecordBatchStream gets no first poll on the caller's thread: the macros pass executor::Start::Runtime, and a worker makes it (Param::waits_for_host in bimetal-macros/src/types/callable.rs). Before its first wait, such a call could wait for the event loop, which runs on the caller's thread, as a Python function that waits for a coroutine on the loop does. A blocking read of a stream there would stop the loop while a Python source makes each batch, and on the addon it would wait for JavaScript, which writes on that thread. The caller's poll has a waker that wakes no one, so a future must register its waker on every poll, as the futures of Tokio and futures do. A body is no Tokio task before its first wait, so tokio::task::id() panics there.

Synchronous constructors and factories enter the same runtime, so they can spawn tasks. Synchronous functions and methods don't, so a package without resources or async calls never starts it. A forked child starts its own runtime, because the parent's worker threads don't exist in it. The result of a call converts on the event loop's thread, whether it finished at once or waited, so no Tokio worker waits for the interpreter lock to deliver a result. An async method's resource lock goes when the Rust call returns, since a synchronous method that waits for the lock waits on that thread.

Async on the addon

The addon polls the future once on the JavaScript thread, as the extension does on the caller's, and settles the promise of a future that is ready there. A call that takes a Callback or a stream starts on a worker, as on Python, and a call of an export that works long starts on one by the export's pace. The addon runs a future that waits on the same kind of Tokio runtime. Each environment has one thread-safe function, its courier (bimetal/src/runtime/node/courier.rs), which the module initializer makes, and through which the worker that finishes a call hands its result to the JavaScript thread, which converts it and settles the promise (bimetal/src/runtime/node/promise.rs). A Callback that a worker calls goes through the courier too. The courier does not keep the event loop alive by itself: each pending call holds it, as a pending timer does, until its result settles. A returned stream's next() starts on the JavaScript thread too, by a pace of its own, and a blocking reader pulls each batch on a blocking thread.

Async on Wasm

A synchronous export returns the promise of bimetal::convert::wasm::promise. wasm-bindgen 0.2.126's own async exports read their arguments only when the future first runs, so Bimetal doesn't use them.

Traps

The CLI routes every call that native.js makes into the module, including the async executor's microtasks and the finalizers, through the runtime's guard. An exception that leaves the module means a trap cut a call short, so the guard aborts the module: it rejects every pending promise, which the trap would leave pending, checkNative keeps every later wrapper call out, and the guard rejects any other export called directly while returning 0 only for host callbacks such as microtasks and finalizers. The panic hook first gives the guard the panic's message.

Panics on native hosts

A panic must not unwind into a host. So every native host catches at its boundary, through executor::catch, which drops the caught payload in turn, and leaks it only if its own drop panics. Python raises PanicException, in bimetal/src/runtime/python.rs and for a panic while a Tokio worker polls, in executor.rs. The addon catches every call from Node.js into Rust in bimetal/src/runtime/node/: the callbacks, the module initializer, the conversion of an async result and the finalizers.