Kernel communications
This page details every communication channel of a Basthon kernel: who opens it, when, what goes through it and with which technology (comlink, MessageChannel, window.postMessage, SharedArrayBuffer, HTTP). It complements Architecture and security, which explains why the kernel is isolated; here we look at how the pieces talk to each other.
The actors
| # | Channel | Technology | Opened | Used for |
|---|---|---|---|---|
| ① | comlink channel | comlink over a MessageChannel | kernel start | main → worker calls: init, eval, putFile, complete... |
| ② | comm port | MessageChannel, raw postMessage | kernel start | worker → main messages: outputs, displays, inputs, downloads, eval-end... |
| ③ | proxy endpoint | comlink (createEndpoint) | kernel start | the worker fetches Basthon's files through a worker of the site's origin |
| ④ | shared buffer | SharedArrayBuffer + Atomics | kernel start (if available) | synchronous answers: input(), time.sleep, kernel iframe messages |
| ⑤ | ephemeral API | HTTP (synchronous XMLHttpRequest, long polling), AES-GCM | at each wait (fallback) | the same, when the page is not cross-origin isolated |
| ⑥ | kernel port | MessageChannel, port transferred twice | at each kernel iframe | worker ↔ iframe: frames, events, matplotlib/tkinter protocols |
| ⑦ | gui port | MessageChannel given with window.postMessage | at each kernel iframe | iframe → frontend: size requests, relayed messages for a waiting worker |
| ⑧ | camera / audio ports | MessageChannel | at each createCapture, audio context | camera frames to the worker, audio graph mirrored in the page |
The frontend never talks to the worker directly: it only knows the KernelBase API (packages/kernel-base/src/kernel.ts) and its events (eval.output, eval.display, eval.input, eval.finished...), on a per-kernel EventBus (packages/kernel-base/src/events.ts). Everything below the API is the kernel's business.
Loading and initialization
Loading the kernel's code
The page imports the kernel's package for the language (dynamic import(), see packages/kernel-loader/src/main.ts), e.g. @basthon/kernel-python3. Only the main-thread class (Python3Kernel, a KernelMainBase) runs in the page; the worker's code is a separate bundle (comlink-worker.js) loaded by the worker.
Importing kernel-main.ts patches two globals of the page (packages/kernel-base/src/commons.ts):
Workeris replaced bySandboxedWorker:new Worker(url, {sandboxed: true})starts a worker from adata:URL (opaque origin) whose only job is toimportScriptsthe real script;HTMLImageElement.srcunderstandsfilesystem:/URLs (files of the kernel's virtual filesystem).
Starting the kernel
kernel.init() then kernel.start() (KernelBase) call KernelMainBase._start() (packages/kernel-base/src/worker/kernel-main.ts):
Details worth knowing:
- comlink bootstrap. The worker listens to its global
messageevent and exposes the kernel worker class on the firstMessagePortit receives (BrowserWorkerHost.expose,host/worker.ts). The main thread then instantiates the class remotely (await new KernelWorker(options)): the instance lives in the worker, the page holds a comlinkRemote. - Two channels, not one. comlink is request/response: perfect for
eval()orcomplete(), not for the stream of messages the worker emits during an evaluation (outputs, displays, input requests). These go through a second, plainMessageChannel(the "comm port",setCommPort), processed byKernelMainBase.processWorkerMessage. - The proxy. The kernel worker has an opaque origin, so the site's files are cross-origin to it. Its
fetchis replaced (mockFetch): same-site URLs go through a comlink endpoint of a second worker that has the site's origin (ProxyFetch,worker/proxy.ts), which only accepts URLs under the assets directory, without credentials (and images anywhere on the site). Response bodies are transferred, not copied. Other origins (CDN, PyPI) are fetched directly withcredentials: "omit". self.basthon. In the worker, the kernel worker instance is the globalbasthon(self.basthon = this): this is what the language runtime calls through its FFI, e.g.js.basthon.displayKernelIFrame(html)orjs.basthon.input(prompt)from Python.- Restart.
stop()terminates the worker (worker.terminate()), closes the spare ports, stops cameras and audio contexts;start()redoes the whole sequence with a new worker (Python restores a Pyodide memory snapshot to make it fast, see Pyodide snapshots). - Legacy mode (
python3-legacy, kept for Capytale): the "worker" code is imported in the page itself, with the same comlink channel (self._commPort), but no proxy, no shared buffer and no isolation.
An evaluation
- Ordering between channels. Nothing guarantees that the comlink answer arrives after the last message of the comm port: the worker posts
eval-endon the comm port once the evaluation and its pending promises are done, andevalAsyncwaits for it (_channelSyncer) before resolving. Soeval.finishedalways comes after the outputs. - Evaluation data. The frontend's data (a cell id, Jupyter's
parent_header...) travels with the evaluation and is copied into each message (datafield), so outputs reach the right cell even asynchronously (a timer, a kernel iframe event). - The page's state. The worker has no
window.devicePixelRatio: the page sends it with everyevalcall (basthon.devicePixelRatio). - Message types on the comm port (worker → main):
stream,display,clear_output,input,input-cancel,iframe-wait,download,download-svg-as-png,spare-port,camera-open,audio-open,log-validation,breakpoint-move-on,eval-end. The main thread only sendstoplevel-inputthe other way. The page never trusts these messages: downloads must be bytes ordata:URLs, MIME bundles are sanitized or sandboxed by the frontends.
Synchronous waits: input(), sleep, dialogs
A program blocked in input() keeps the worker busy: it can't receive any message (neither comlink nor the comm port). Three mechanisms coexist:
SharedArrayBuffer④ (cross-origin isolated pages, e.g. Basthon Desktop). The worker postsinputon the comm port, thenAtomics.waits on the first 4 bytes of a 64 KiB shared buffer. The page writes the UTF-8 answer after them and sets the flag (1: answer, 2: interrupted →KeyboardInterrupt, 3: end of input →EOFError), thenAtomics.notify.time.sleepis anAtomics.waitwith a timeout.- Ephemeral API ⑤ (otherwise, e.g. Capytale, which has no COOP/COEP). The worker posts
inputwith a random key, then makes synchronousXMLHttpRequests toapi.basthon.fr/ephemeral(long polling, 16 s per request, until an answer comes); the page POSTs the answer under that key. Answers are encrypted with AES-GCM (fallback-cipher.ts), with a key drawn at each start, which never leaves the browser. - Top-level
await(Python withoutSharedArrayBuffer):input()calls at the top level of the code are rewritten intoawait input_async(...)(_console.RewriteAST); the worker then awaits atoplevel-inputmessage on the comm port, no blocking at all. The ephemeral API is only needed forinput()inside a function.
The same machinery serves kernel iframes whose program waits for them (a tkinter dialog: messagebox.askyesno blocks until the user clicks). The iframe can't use its kernel port, since the worker can't read it while blocked, so the answer goes the long way round, see below.
Kernel iframes
Interactive outputs are pages running in their own iframe, talking to the worker directly: matplotlib figures (WebAgg), p5 sketches, tkinter windows, the canvases of OCaml's Graphics and of the JavaScript kernel.
The pieces
- The page is a self-contained HTML string (scripts, styles, images inlined) produced by the kernel: a bundle built in this repository (
canvas/iframe/,p5/src/iframe/,matplotlib-basthon-backend/src/iframe/) or tkinter-web-backend's client. - The iframe is created by the frontend from a
data:URL, with asandboxattribute withoutallow-same-origin(allow-scripts allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-downloads): an opaque origin, no access to the page, its cookies or storage, no top navigation. - Two ports are given to it: the kernel port ⑥ (worker ↔ iframe) and the gui port ⑦ (iframe → frontend).
Display sequence
displayKernelIFrame(html, fallback) (kernel-worker.ts) is the only entry point, called from any language: Python through js.basthon.displayKernelIFrame, OCaml and JavaScript through displayLiveCanvas. It returns the worker's end of the kernel port.
The kernel port is transferred twice (worker → page in the comm message, page → iframe with window.postMessage): the page holds it in between but never uses it.
Notebooks. The Jupyter frontends serialize outputs to JSON, which can't hold a MessagePort. The port is stored in a bus under a random key and the output carries only the key and the HTML (text/json-kernel-iframe in Basthon-Notebook, BypassBus in basthonwebsocket.ts; application/vnd.basthon.kernel-iframe+json in the JupyterLite kernels, packages/base/src/iframe.ts of basthon-jupyterlite-kernels). The renderer pops the port with the key. A notebook reopened from a file has keys that no longer exist: the iframe is replaced by its fallback MIME bundle (e.g. a PNG snapshot).
The gui port ⑦
Created by the frontend (iframeResizeChannel, packages/gui-base/src/main.ts), it carries only two messages, both validated because the iframe is untrusted:
{type: "size", content: {width, height}}: the iframe is resized (numbers only);{type: "iframe-message", key, message}: a message for a worker that waits synchronously for it, relayed withkernel.postIFrameMessage(key, message).
The fullscreen button is added by the frontend around the iframe, not through a message.
The kernel port ⑥: protocols
What travels on the kernel port depends on the output:
- Canvas (
packages/kernel-base/src/canvas/, OCaml, JavaScript): the program draws on anOffscreenCanvasin the worker; a loop (CanvasBridge, the worker'srequestAnimationFrame) sends{type: "frame", bitmap}(transferredImageBitmap) at most once per animation frame and only after the iframe acknowledged the previous one (ready). The iframe sends back serialized DOM events (mouse, touch, keyboard, wheel, blur, resize); move events are coalesced until the worker answersmoved. The worker also tells which default behaviors to prevent (handlers). Types:canvas/protocol.ts. - p5 (
packages/kernel-python3/src/modules/p5/): the canvas protocol, plus a mirror of the sketch's HTML elements. p5.js runs in the worker on an emulated DOM (worker/dom.ts);createButton,createSlider... produce snapshots that the iframe reconciles with real elements, whose events come back. Also the mousecursor. Types:p5/src/protocol.ts. - matplotlib (
matplotlib-basthon-backend): matplotlib's own WebAgg protocol. The kernel port replaces the WebSocket between the Python "server" and mpl.js: JSON strings and PNG frames (Uint8Array) one way, mpl.js events the other way. Basthon adds a few message types (basthon_download,basthon_close). - tkinter (tkinter-web-backend): one iframe per
Tk(); the Tk engine runs in Python in the worker and sends display lists (JSON), the iframe draws the windows on canvases and sends input and window-manager events. The same protocol runs over a WebSocket when tkinter-web-backend is used outside of Basthon.
Waiting for an iframe: the relay
A tkinter dialog blocks the program until the user answers, so the worker can't read the kernel port. The answer takes the synchronous path:
Keys are prefixed by the kernel's secret (<fallbackKey>-iframe-<n>, or sab-iframe-<n>), so the main thread only accepts keys made for this kernel; messages are limited to 1 MiB.
Pitfalls
These are the non-obvious behaviors that shaped the code:
- Ports transferred while the worker is busy (Firefox). Firefox (128, 140) holds the messages of a port that a busy worker transferred until the worker's task ends: a figure updated by
plt.pausein a loop stayed blank. Hence the spare channels: the worker creates up to 4 channels in advance and sends their page ends (spare-port) while it is idle;displayKernelIFramethen only sends a key. - Closing a port in transit. Closing the worker's end while the other end hasn't reached the iframe yet drops the pending messages (a figure shown then closed in the same cell). The worker never closes first: it sends a close message (
basthon_closefor matplotlib) and the iframe closes the port once it has read everything before it. - A busy worker reads nothing. Frames sent during a long computation are only produced if the program yields (p5's draw loop,
plt.pause, tkinter'supdate()); events from the iframe wait in the port's queue until the program returns to the event loop. - Device pixel ratio. The worker has none; the page sends its ratio with each evaluation, and iframes send their own (matplotlib's
set_device_pixel_ratio) since it may differ (hidden iframe, zoom).
Camera and audio ⑧
Both follow the same pattern: the worker creates a MessageChannel, sends one end with a camera-open / audio-open message on the comm port, and keeps the other.
- Camera (
packages/kernel-base/src/camera/): the page asks the user to confirm each request (confirmCamera), opensgetUserMediaand sends frames asImageBitmaps on the port. - Audio (
packages/kernel-base/src/audio/): the Web Audio API is emulated in the worker; the operations on the audio graph are sent on the port and replayed on a realAudioContextof the page.
Where to look
| Topic | Files |
|---|---|
| start sequence, comm port (page side) | packages/kernel-base/src/worker/kernel-main.ts |
worker side, displayKernelIFrame | packages/kernel-base/src/worker/kernel-worker.ts |
| comlink bootstrap | packages/kernel-base/src/host/worker.ts, host/main.ts |
sandboxed worker, mockFetch | packages/kernel-base/src/commons.ts, worker/proxy.ts |
| kernel iframe in the frontends | packages/gui-base/src/main.ts (handleKernelIFrame) |
| canvas protocol | packages/kernel-base/src/canvas/ |
| p5, matplotlib | packages/kernel-python3/src/modules/{p5,matplotlib-basthon-backend}/ |
| tkinter setup | packages/kernel-python3/src/basthon/_patch_modules.py (_TkinterWebBackend) |
| Jupyter frontends | basthon-notebook src/ts/basthonwebsocket.ts, basthon-jupyterlite-kernels packages/base/ |