Skip to content

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 ​

#ChannelTechnologyOpenedUsed for
①comlink channelcomlink over a MessageChannelkernel startmain → worker calls: init, eval, putFile, complete...
②comm portMessageChannel, raw postMessagekernel startworker → main messages: outputs, displays, inputs, downloads, eval-end...
③proxy endpointcomlink (createEndpoint)kernel startthe worker fetches Basthon's files through a worker of the site's origin
④shared bufferSharedArrayBuffer + Atomicskernel start (if available)synchronous answers: input(), time.sleep, kernel iframe messages
⑤ephemeral APIHTTP (synchronous XMLHttpRequest, long polling), AES-GCMat each wait (fallback)the same, when the page is not cross-origin isolated
⑥kernel portMessageChannel, port transferred twiceat each kernel iframeworker ↔ iframe: frames, events, matplotlib/tkinter protocols
⑦gui portMessageChannel given with window.postMessageat each kernel iframeiframe → frontend: size requests, relayed messages for a waiting worker
⑧camera / audio portsMessageChannelat each createCapture, audio contextcamera 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):

  • Worker is replaced by SandboxedWorker: new Worker(url, {sandboxed: true}) starts a worker from a data: URL (opaque origin) whose only job is to importScripts the real script;
  • HTMLImageElement.src understands filesystem:/ 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 message event and exposes the kernel worker class on the first MessagePort it 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 comlink Remote.
  • Two channels, not one. comlink is request/response: perfect for eval() or complete(), not for the stream of messages the worker emits during an evaluation (outputs, displays, input requests). These go through a second, plain MessageChannel (the "comm port", setCommPort), processed by KernelMainBase.processWorkerMessage.
  • The proxy. The kernel worker has an opaque origin, so the site's files are cross-origin to it. Its fetch is 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 with credentials: "omit".
  • self.basthon. In the worker, the kernel worker instance is the global basthon (self.basthon = this): this is what the language runtime calls through its FFI, e.g. js.basthon.displayKernelIFrame(html) or js.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-end on the comm port once the evaluation and its pending promises are done, and evalAsync waits for it (_channelSyncer) before resolving. So eval.finished always 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 (data field), 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 every eval call (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 sends toplevel-input the other way. The page never trusts these messages: downloads must be bytes or data: 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:

  1. SharedArrayBuffer ④ (cross-origin isolated pages, e.g. Basthon Desktop). The worker posts input on the comm port, then Atomics.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), then Atomics.notify. time.sleep is an Atomics.wait with a timeout.
  2. Ephemeral API ⑤ (otherwise, e.g. Capytale, which has no COOP/COEP). The worker posts input with a random key, then makes synchronous XMLHttpRequests to api.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.
  3. Top-level await (Python without SharedArrayBuffer): input() calls at the top level of the code are rewritten into await input_async(...) (_console.RewriteAST); the worker then awaits a toplevel-input message on the comm port, no blocking at all. The ephemeral API is only needed for input() 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 a sandbox attribute without allow-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 with kernel.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 an OffscreenCanvas in the worker; a loop (CanvasBridge, the worker's requestAnimationFrame) sends {type: "frame", bitmap} (transferred ImageBitmap) 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 answers moved. 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 mouse cursor. 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.pause in 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; displayKernelIFrame then 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_close for 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's update()); 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), opens getUserMedia and sends frames as ImageBitmaps 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 real AudioContext of the page.

Where to look ​

TopicFiles
start sequence, comm port (page side)packages/kernel-base/src/worker/kernel-main.ts
worker side, displayKernelIFramepackages/kernel-base/src/worker/kernel-worker.ts
comlink bootstrappackages/kernel-base/src/host/worker.ts, host/main.ts
sandboxed worker, mockFetchpackages/kernel-base/src/commons.ts, worker/proxy.ts
kernel iframe in the frontendspackages/gui-base/src/main.ts (handleKernelIFrame)
canvas protocolpackages/kernel-base/src/canvas/
p5, matplotlibpackages/kernel-python3/src/modules/{p5,matplotlib-basthon-backend}/
tkinter setuppackages/kernel-python3/src/basthon/_patch_modules.py (_TkinterWebBackend)
Jupyter frontendsbasthon-notebook src/ts/basthonwebsocket.ts, basthon-jupyterlite-kernels packages/base/