| @@ -0,0 +1,97 @@ |
| 1 | +# ADR 0015: C callbacks and bindings |
| 2 | + |
| 3 | +**Status:** Proposed — 2026-10-09 (issue #48); needs engineering review (#44). |
| 4 | + |
| 5 | +## Context |
| 6 | +- [ADR 0005](0005-ffi.md) left callbacks from C back into tilcayo out of v0: many C APIs take one (a sort comparator, a visitor, a log hook). They need re-entry into tilcayo code from C frames. |
| 7 | +- Its Revision 1 made the extern convention `tl_value sym(tl_ctx *ctx, tl_value a, ...)`, with a few lines of C per library (the *shim*) converting values. Callbacks fit the same model: the shim gives C a *trampoline*, a C function of the library's callback type, which converts its arguments and calls the tilcayo function. |
| 8 | +- Generated code runs on an actor's fiber. That fiber may suspend (preemption, `receive`, sockets, `blocking` externs), and may resume on another scheduler thread. |
| 9 | +- Panics, exit signals and `final ctl` operations unwind by yield-bubbling ([ADR 0003](0003-effect-lowering.md) Revision 2): each frame checks `ctx->yielding` after a call and returns. C frames do no such check. |
| 10 | + |
| 11 | +## Decision |
| 12 | + |
| 13 | +### The tilcayo side: a function-typed extern parameter |
| 14 | +An extern takes a callback as an ordinary parameter of function type: |
| 15 | + |
| 16 | +```tilcayo |
| 17 | +@extern(c, "fx_sort") |
| 18 | +fn sort(xs: List<Int>, compare: fn(Int, Int) -> Int / <ffi>) -> List<Int> / <ffi> |
| 19 | +``` |
| 20 | + |
| 21 | +The checker rejects (`E0113`): |
| 22 | +- a callback whose row is not closed or holds anything but `ffi` (total callbacks are fine); |
| 23 | +- a callback on a `blocking` extern; |
| 24 | +- a callback that performs `ffi` on an extern whose own row lacks `ffi`; |
| 25 | +- a parameter that only *contains* a function (`List<fn(Int) -> Int>`): functions reach C only as parameters, so the compiler knows which calls may call back. |
| 26 | + |
| 27 | +Type aliases of function types count as function types. |
| 28 | + |
| 29 | +### The C side: `tl_callback` as the trampoline's environment |
| 30 | +`tilrt.h` gives the shim a small struct and three functions: |
| 31 | + |
| 32 | +```c |
| 33 | +tl_value fx_sort(tl_ctx *ctx, tl_value xs, tl_value cmp) { |
| 34 | + ... |
| 35 | + tl_callback cb; |
| 36 | + tl_callback_begin(ctx, &cb, cmp); |
| 37 | + qsort_r(a, n, sizeof *a, compare, &cb); /* compare(x, y, &cb) */ |
| 38 | + tl_value sorted = ...; |
| 39 | + return tl_callback_end(&cb, sorted); |
| 40 | +} |
| 41 | + |
| 42 | +static int compare(const void *x, const void *y, void *env) { |
| 43 | + tl_value args[2] = {tl_int(*(const int64_t *)x), tl_int(*(const int64_t *)y)}; |
| 44 | + int64_t order = tl_int_get(tl_callback_call(env, 2, args)); |
| 45 | + return (order > 0) - (order < 0); |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +- **Which context and actor:** the callback runs in the actor that called into C, with its `tl_ctx`, on its fiber's stack, on the same OS thread, and only while that extern call is in progress (between `tl_callback_begin` and `tl_callback_end`). |
| 50 | +- **Ownership:** the closure is the extern's argument, so it is *borrowed* for the duration of the call (externs borrow their arguments). `tl_callback_call` duplicates it for each call, because closure calls consume `self`. It consumes its arguments and returns an owned result, which the trampoline converts and drops. C must not keep the `tl_callback *` after the call returns. |
| 51 | +- **The C library needs a `void *` environment** (`qsort_r`, not `qsort`). A library without one would need a global or thread-local slot in the shim; that is the shim's business, and `tilc bindgen` (below) does not support it. |
| 52 | + |
| 53 | +### While a callback is possible, the actor's fiber does not suspend |
| 54 | +C frames are on the fiber between the extern call and the callback. C code may rely on its thread (thread-locals, `errno`, locks it holds), and another actor on the same thread could re-enter a library that is not reentrant. So from `tl_callback_begin` to `tl_callback_end` (counted per actor, so they nest): |
| 55 | +- **Preemption** only refills the reduction budget: the whole extern call is one slice, like any long extern call. |
| 56 | +- **Exit signals** wait for the call to return; they are delivered at the next preemption point. |
| 57 | +- **`blocking` externs** called from the callback run inline on the scheduler thread instead of parking the actor. |
| 58 | +- **Effects:** callbacks are limited to `<ffi>`, so they cannot perform `proc` operations or use sockets (`<io>`), which park. The runtime aborts with a message if an actor parks anyway (a hand-written shim breaking the rules). Handlers *inside* the callback are fine: `ctl` handlers switch fibers on the same thread. |
| 59 | + |
| 60 | +### A panic unwinds to the trampoline, then continues after the C call |
| 61 | +Unwinding never crosses a C frame: |
| 62 | +1. A panic in the callback unwinds its tilcayo frames to `tl_callback_call`, which returns unit to the trampoline. `ctx->yielding` stays set. |
| 63 | +2. While it is set, further `tl_callback_call`s drop their arguments and return unit at once, without running any tilcayo code. `tl_callback_failed(cb)` tells the shim, which may stop the library early if the library allows it. |
| 64 | +3. C runs to completion with the unit results (zero for an `Int`). Sorting tolerates a comparator that returns 0; a library that cannot tolerate dummy results needs its shim to check `tl_callback_failed`. |
| 65 | +4. `tl_callback_end` drops the shim's result and returns unit. |
| 66 | +5. The compiler treats a call to an extern that takes a callback as one that may unwind (Core's `Program::reentrant`), so the generated code checks `ctx->yielding` after it and keeps unwinding. The actor crashes with the callback's message, as for any panic. |
| 67 | + |
| 68 | +The panic is not turned into an error *value*: that would need a `Result` in every callback-taking extern's type, and the panic semantics of the rest of the language already isolate it to the actor. |
| 69 | + |
| 70 | +### `blocking` externs take no callbacks |
| 71 | +A blocking extern runs on the blocking pool's threads while its actor is parked, so a callback would run tilcayo code on another thread than its actor's, concurrently with the scheduler. The checker forbids it, and `tl_callback_begin` aborts on a pool thread. |
| 72 | + |
| 73 | +### Runtime guards |
| 74 | +These abort with a message. They catch shim bugs, not user errors: |
| 75 | +- `tl_callback_call` on another thread than the extern call's (C calling back from its own threads); |
| 76 | +- `tl_callback_call` after `tl_callback_end` (best effort: the struct is on the shim's stack); |
| 77 | +- `tl_callback_begin` on the blocking pool; |
| 78 | +- parking inside a callback; |
| 79 | +- more than 31 callback arguments (five registers and the 26 `xargs` slots). |
| 80 | + |
| 81 | +## Consequences |
| 82 | +- **Binding a callback API** takes one function-typed parameter and a trampoline in the shim. The trampoline converts types, so it is per C signature; `tilc bindgen` generates it for simple signatures. |
| 83 | +- **Cost:** one predictable branch after each call to a callback-taking extern. Nothing changes for other externs. |
| 84 | +- **Fairness:** with one scheduler thread, other actors wait for a long C call with callbacks, as for any long extern call. With several, they run on other threads. |
| 85 | +- **Kills are delayed** until the C call returns. |
| 86 | +- **After a panic,** C still iterates: each remaining callback call returns at once, but a long C loop still runs to its end. |
| 87 | +- **Not supported:** |
| 88 | + - callbacks stored by C and called later (event loops, signal handlers). They would need a closure kept alive past the call and a message to the actor; |
| 89 | + - callbacks called from C's own threads; |
| 90 | + - the interpreter, which cannot call C at all (as for every native dependency): these tests are native. |
| 91 | + |
| 92 | +## Alternatives considered |
| 93 | +- **A trampoline generated by the compiler** from a C signature written in the attribute. This would put C types in the compiler next to one uniform convention; the shim (written or generated by `tilc bindgen`) keeps C types out. |
| 94 | +- **Running the callback in another actor**, by sending it a message. The calling actor is blocked inside C waiting for the result, so this needs a second actor and a synchronous round trip per call, and every captured value must be sendable. |
| 95 | +- **Allowing any effect, and suspending inside callbacks.** C frames would move between threads with the fiber. This breaks C code using thread-locals or holding locks, and lets another actor re-enter the same library on the same thread. |
| 96 | +- **Unwinding through C** with `longjmp` or forced unwinding. C frames would release nothing (locks, allocations), and Rust forbids unwinding across `extern "C"` frames. |
| 97 | +- **Aborting the process** on a panic in a callback. It is simpler, but it turns one actor's error into a crash of all of them. |