@gmitch215/folio 0.0.0-stage โ†’ 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gregory Mitchell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,483 @@
1
- # Temporary Holding Version
1
+ # ๐Ÿš‹ Folio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > โšก Shared WebAssembly memory and ordered speculative execution across isolates
4
+
5
+ Folio runs native WebAssembly across several V8 isolates that share one physical memory allocation.
6
+ It finds inline memory regions and pure calls in ordinary programs, validates the ones it cannot
7
+ prove independent, and keeps the serial result. Scalar results, control flow and opaque state stay
8
+ in the original Wasm instance. A portable client connects workerd and managed Cloudflare Workers to
9
+ the same engine.
10
+
11
+ ## Table of Contents
12
+
13
+ - [Why Folio](#-why-folio)
14
+ - [Features](#-features)
15
+ - [Install](#-install)
16
+ - [Getting Started](#-getting-started)
17
+ - [Asynchronous Host Effects](#-asynchronous-host-effects)
18
+ - [Execution Host](#-execution-host)
19
+ - [Managed Workers](#-managed-workers)
20
+ - [Browser Execution and Page Leases](#-browser-execution-and-page-leases)
21
+ - [Task Pool](#-task-pool)
22
+ - [Baked Boot Images](#-baked-boot-images)
23
+ - [Execution and Memory](#-execution-and-memory)
24
+ - [API Reference](#-api-reference)
25
+ - [Consumer Harness](#-consumer-harness)
26
+ - [Measured Results](#-measured-results)
27
+ - [Development](#-development)
28
+ - [Contributing](#-contributing)
29
+ - [License](#-license)
30
+
31
+ ## ๐Ÿงญ Why Folio
32
+
33
+ A Worker, a Linux machine in a Durable Object and a PHP interpreter all end up as one Wasm
34
+ instance on one thread. Folio spreads the work of that instance across cores without asking the
35
+ program to be rewritten. The caller passes one ordinary entry point. The compiler discovers the
36
+ regions, so there are no access annotations and no caller-created chunks.
37
+
38
+ - **Native Sharing.** Isolates map the same backing allocation, so a 256 MiB arena costs about 4 MiB
39
+ to attach to another isolate instead of a copy.
40
+ - **Serial Semantics.** Uncertain dependencies run on private overlays and commit in original
41
+ order. A conflict replays against committed state, and a trap keeps its preceding writes.
42
+ - **Original Stack.** JSPI suspends the program's own Wasm stack at joins, so branches, scalar
43
+ carry and host effects behave as they do natively.
44
+ - **Portable.** The client and the managed backend use fetch, WebSockets and Durable Objects, with
45
+ no Node imports and no request-time Wasm compilation.
46
+
47
+ Accepted input does not guarantee a speedup. A program with a true serial dependency runs serially,
48
+ and a small job loses to dispatch overhead.
49
+
50
+ ## โœจ Features
51
+
52
+ - ๐Ÿงต **Automatic region discovery** across branches, loops, switches, nested calls and reductions.
53
+ - ๐Ÿง  **Ordered validation** with byte-granular conflict detection, replay and budget fallback.
54
+ - ๐Ÿ›ก๏ธ **Native guards** that prove footprints, bounds and finite loops, then run on plain native
55
+ instructions with no tracking.
56
+ - ๐Ÿ”Œ **Arbitrary Wasm input** as bytes, `ArrayBuffer`, `WebAssembly.Module` or a prepared plan,
57
+ with imported memories, tables, globals and host functions bound as in native instantiation.
58
+ - โณ **Asynchronous host effects** through JSPI, executed once and in call order.
59
+ - ๐ŸŒ **Execution host and portable client** for workerd, with sessions, quotas and joined cleanup.
60
+ - โ˜๏ธ **Managed backend** that runs entirely in Workers and Durable Objects, with binary frames and
61
+ copied snapshots between lanes.
62
+ - ๐Ÿงฐ **Task pool** that runs named functions in private contexts on other threads, with ordered
63
+ joins and an optional differential audit.
64
+ - ๐ŸงŠ **Baked boot images** that write a booted memory into the module as data segments.
65
+ - ๐Ÿ“Š **Opt-in profiling** of worker time, validation, commit and replay cost.
66
+
67
+ ## ๐Ÿ“ฆ Install
68
+
69
+ ```sh
70
+ bun add @gmitch215/folio
71
+ # or
72
+ npm install @gmitch215/folio
73
+ ```
74
+
75
+ The Node backend needs Node 26 or later. Async host imports and the managed backend need WebAssembly
76
+ JSPI. The browser counted-loop backend works without JSPI; page-owner transports are portable.
77
+ Builds from the main branch publish to the `snapshot` tag.
78
+
79
+ ## ๐Ÿš€ Getting Started
80
+
81
+ ```ts
82
+ import { readFileSync } from 'node:fs';
83
+ import { Folio } from '@gmitch215/folio';
84
+
85
+ const folio = await Folio.open(readFileSync('./build/fixture.wasm'), { workers: 4 });
86
+ try {
87
+ new Uint32Array(folio.memory.buffer, 1024, 37).fill(1);
88
+ const report = await folio.run('program', [1024, 37, 10000]);
89
+ console.log(report.mode, report.workers, report.regions);
90
+ console.log(folio.inspect('program'));
91
+ } finally {
92
+ await folio.close();
93
+ }
94
+ ```
95
+
96
+ `Folio.open(input, options)` accepts a `Uint8Array`, an `ArrayBuffer`, a `WebAssembly.Module` or the
97
+ result of `prepare(bytes)`. A compiled module has no inspectable bytes and uses its native entry.
98
+ Imported memory is allocated from the module's limits when omitted. Pass `memory` to bind an
99
+ existing single imported memory, or bind several by their exact names in `imports`. Missing host
100
+ functions, tables, globals, tags and memory64 bindings are supplied as with native instantiation.
101
+ `prepare(bytes, { parallel: 'off' })` disables optimization and leaves the program unchanged.
102
+ Prepared plans are trusted build artifacts.
103
+
104
+ A region runs on a worker only when its estimated work pays for dispatch, joining and validation.
105
+ `prepare` estimates each candidate in instruction units, charges 3,600 units for every tracked load
106
+ or store, and keeps the region at its owner below `minimumRegionWork` (200,000 by default, about
107
+ 39 microseconds of native work on an Apple M2 Pro). A loop bounded by a constant uses that count, a
108
+ loop bounded by an untouched parameter or a countdown from one is checked against the arguments at
109
+ each call, and any other loop is assumed to run `assumedTripCount` times (1,000). A module with no
110
+ region above the threshold gets no control plan and runs as the original Wasm, so a small kernel, a
111
+ memory-bound loop or a serial recurrence stays at native speed. `minimumRegionWork: 0` admits every
112
+ pure region. `folio.diagnostics` says why a plan was refused.
113
+
114
+ ## โณ Asynchronous Host Effects
115
+
116
+ ```ts
117
+ import { Folio, suspending } from '@gmitch215/folio';
118
+
119
+ const folio = await Folio.open(module, {
120
+ imports: {
121
+ host: {
122
+ read: suspending(async (key) => (await fetch(new URL(String(key), storageUrl))).status)
123
+ }
124
+ },
125
+ promising: ['main']
126
+ });
127
+ const report = await folio.run('main', [42]);
128
+ await folio.close();
129
+ ```
130
+
131
+ This needs a runtime with WebAssembly JSPI. Listed async exports and numeric-result coordinator
132
+ entries receive a promising wrapper. Reference-returning exports keep their native ABI, because
133
+ Promise assimilation would change an externref Promise's identity. Host effects run once in call
134
+ order and exceptions keep their identity. Opaque references stay in the original isolate. Closing
135
+ joins a suspended native call; it cannot cancel an arbitrary external Promise.
136
+
137
+ ## ๐ŸŒ‰ Execution Host
138
+
139
+ `@gmitch215/folio/host` registers trusted artifacts, bindings and export allowlists through
140
+ `FolioHost`. Its authenticated fetch handler exposes ordered run, read, write and close operations
141
+ with joined disposal and bounded admission. `@gmitch215/folio/remote` is the client for it.
142
+
143
+ ```ts
144
+ import { RemoteFolio } from '@gmitch215/folio/remote';
145
+
146
+ const remote = await RemoteFolio.open(endpoint, 'fixture', {
147
+ headers: { authorization: `Bearer ${token}` },
148
+ workers: 4
149
+ });
150
+ try {
151
+ await remote.write(1024, inputBytes);
152
+ const report = await remote.run('program', [1024, wordCount, rounds]);
153
+ const output = await remote.read(1024, inputBytes.length);
154
+ } finally {
155
+ await remote.close();
156
+ }
157
+ ```
158
+
159
+ The client runs in stock workerd with no Node imports and no runtime Wasm compilation. Requests and
160
+ results cross a serialized transport, and physical sharing happens inside the host. Each session
161
+ caches its last accepted result, so `retryPending()` recovers a lost response without repeating
162
+ effects. The cache is bounded and held in memory. Memory admission checks the initial accessible
163
+ backing, and trusted artifact factories enforce growth maxima and private-memory budgets.
164
+
165
+ ## ๐Ÿ“ก Managed Workers
166
+
167
+ `@gmitch215/folio/managed` exports `ManagedFolio` and `FolioLane` for execution entirely in managed
168
+ Workers and Durable Objects. `ManagedFolio` takes precompiled artifact modules and lane transports
169
+ whose `execute(frame)` returns a binary response, and `FolioLane` runs the tracked region module.
170
+ The original JSPI coordinator keeps control flow and host effects, and copied snapshots with
171
+ ordered byte validation connect independent lanes. A transport failure falls back to native owner
172
+ execution. Snapshot, frame, fuel and tracking bounds are configurable, and the canonical memory
173
+ must fit the owner runtime. See [the managed procedure](experiments/managed/METHOD.md).
174
+
175
+ ## ๐Ÿ”— Browser Execution and Page Leases
176
+
177
+ `@gmitch215/folio/browser` exports `BrowserFolio` for Chromium and other hosts without JSPI. It
178
+ takes a precompiled original module and the `loops`, `native`, `reasons` and `memories` metadata
179
+ that `prepare` produced offline. `open()` attaches dedicated module workers to the supplied shared
180
+ memory. `run(name, args)` derives guarded partitions from one ordinary counted-loop call and joins
181
+ before it returns, with no snapshot and no runtime compiler. Other entries use the original owner.
182
+ The caller keeps exclusive ownership of the arena. A failure after native writes closes the pool,
183
+ and the application restores a checkpoint before retrying.
184
+
185
+ `@gmitch215/folio/pages` exports `PageDirectory`, `MemoryPageOwner`, `ResidentPageLease` and the
186
+ `PageOwner` transport contract. `acquire({ read, write })` obtains bounded resident pages and
187
+ `lease.view(page)` returns a private view of one. `commit()` stages immutable versions and
188
+ atomically publishes their manifest, `abort()` discards local changes, and `collect()` reclaims
189
+ retired versions with delayed-message fencing. The directory holds page metadata, not a whole heap.
190
+
191
+ Leases work on copied bytes, and the bundled owners and directory keep their state in memory. The
192
+ [technical report](TECHNICAL_REPORT.md) covers failure semantics, the native Wasm measurements and
193
+ the limits of both modules.
194
+
195
+ ## ๐Ÿงฐ Task Pool
196
+
197
+ `@gmitch215/folio/tasks` runs independent work that a program names itself. A `TaskPool` owns one
198
+ channel per worker. The caller starts each worker with `pool.link(index)` and calls `serveTasks`
199
+ there with a function that runs a named task. The owner calls `submit(name, input)` and keeps going,
200
+ then `join(handle)` blocks until the output arrives, or `joinAsync(handle)` waits without blocking
201
+ the event loop. `run(jobs)` submits a list and returns the results in submission order, and
202
+ `runSync(jobs)` does the same where the caller cannot yield, such as inside a synchronous Wasm
203
+ import. Input and output are strings or bytes, `submitJson` and `result.json()` cover structured
204
+ values, and `pool.width` limits how many workers take tasks.
205
+
206
+ ```ts
207
+ import { Worker } from 'node:worker_threads';
208
+ import { TaskPool } from '@gmitch215/folio/tasks';
209
+
210
+ const pool = new TaskPool(4);
211
+ for (let index = 0; index < pool.size; index++) {
212
+ const link = pool.link(index);
213
+ new Worker(new URL('./task-worker.js', import.meta.url), {
214
+ workerData: { link },
215
+ transferList: [link.port]
216
+ });
217
+ }
218
+
219
+ const results = await pool.run([
220
+ ['render', 'page-1'],
221
+ ['render', 'page-2']
222
+ ]);
223
+ console.log(results.map((result) => result.text()));
224
+ ```
225
+
226
+ ```ts
227
+ import { workerData } from 'node:worker_threads';
228
+ import { serveTasks } from '@gmitch215/folio/tasks';
229
+
230
+ serveTasks(workerData.link, (name, input) => {
231
+ // run the task called `name` on `input` and return its output
232
+ return String(input);
233
+ });
234
+ ```
235
+
236
+ A worker shares nothing with the owner. Each task runs against that worker's own state, so a task
237
+ that reads or writes state the serial program would have shared returns a different result than the
238
+ serial run. `audit: { run, every }` runs every nth task again in the joining thread and throws
239
+ `TaskConflictError` with the first differing byte. The audit costs one serial execution per checked
240
+ task and is meant for tests and canaries. `drain()` returns a record per joined task with its worker,
241
+ start and end time, thread CPU time and byte counts, and `peakConcurrency(records)` reports how many
242
+ tasks ran at the same time.
243
+
244
+ The pool does not discover independent work. Region discovery and ordered validation stay in the
245
+ core engine, and the task pool covers programs that can say which calls are independent.
246
+
247
+ ## ๐ŸงŠ Baked Boot Images
248
+
249
+ `@gmitch215/folio/bake` moves a booted memory into the module. `captureImage(booted, fresh)` compares
250
+ a booted memory with a fresh instance of the same module and keeps the 64 KiB pages that differ.
251
+ `bakeModule(bytes, image)` returns the module with those pages as active data segments after its own,
252
+ so instantiating it starts from the booted memory. It uses binaryen, loaded on the first bake, and
253
+ writes memory 0.
254
+
255
+ ```ts
256
+ import { bakeModule, captureImage, imagePages, moduleDigest } from '@gmitch215/folio/bake';
257
+
258
+ const fresh = new WebAssembly.Memory({ initial: 1024 });
259
+ const booted = new WebAssembly.Memory({ initial: 1024 });
260
+ // instantiate `bytes` on each memory, then run the boot sequence on `booted`
261
+
262
+ const image = captureImage(booted, fresh, { module: await moduleDigest(bytes) });
263
+ const baked = await bakeModule(bytes, image);
264
+
265
+ const memory = new WebAssembly.Memory({ initial: imagePages(image).memoryPages });
266
+ const { instance } = await WebAssembly.instantiate(baked, { env: { memory } });
267
+ ```
268
+
269
+ The caller creates an imported memory with at least `memoryPages` pages. A defined memory that
270
+ starts smaller has its initial pages raised to the image size, and its maximum, shared and memory64
271
+ flags stay as they are. A page that boot zeroed but the module's own data had set is stored as
272
+ zeros, and pages that are zero in both are left out. Pass the global values and the function table
273
+ of both instances to `captureImage` as `globals` and `table` and the image records what boot
274
+ changed. `bakeModule` writes changed i32, i64, f32 and f64 globals into their initial values and
275
+ refuses changed table slots unless `allowTableChanges` is set. It throws `ImageMismatchError`, which
276
+ has a `code`, for a wrong module digest, no memory, an image over the memory maximum and a global it
277
+ cannot rewrite. Adjacent pages become one segment of at most `maxSegmentBytes` (64 MiB).
278
+
279
+ `applyImage(memory, image)` copies the pages into a fresh instance's memory without baking. It
280
+ cannot set a module's globals or table slots, so an image that records changed ones is refused with
281
+ code `global` or `table`; `{ memoryOnly: true }` copies the memory anyway and leaves the instance
282
+ with its fresh globals, which is not a booted instance. A module whose boot changes globals (the
283
+ PHP 8.5.12 build changes its stack bounds) belongs in `bakeModule`.
284
+ `captureImage` takes a `context` string beside the module digest, a digest of whatever else shapes
285
+ the heap (settings, shims, assets), and `applyImage(memory, image, { module, context })` refuses an
286
+ image whose module or context differs, or that carries none, with `ImageMismatchError` code `digest`
287
+ or `context` and before it writes a byte. `encodeImage` and `decodeImage` store an image beside the
288
+ module and reject truncated or unknown input with `ImageFormatError`. `checkBaked(baked, image)`
289
+ reads the data segments back and compares them with the image without instantiating.
290
+ `bakeModule` throws code `memories` for a module with more than one memory.
291
+
292
+ The image is the heap as it was, so anything the booted process held is in the baked module and
293
+ becomes public with it. State kept in JavaScript, such as handles and open descriptors, is not
294
+ captured. `findInImage(image, needles)` returns every offset where a needle's bytes occur in the
295
+ image pages, so a secret and its base64 and hex forms can be searched for before the module ships.
296
+ Freed memory is not zeroed, so a secret that was ever in the heap cannot be scrubbed out of an
297
+ image afterwards: bake a site whose key and salt are throwaway values, and give the replaying site
298
+ its own.
299
+
300
+ For a Drupal heap that means three replacements after the replay. The hash salt lives in the static
301
+ `Settings` object; the private key lives in the `State` cache collector, which serves it from memory
302
+ once read; and PHP's Mersenne Twister state is in the heap, so every replayed instance would draw
303
+ the same `mt_rand()` sequence. Values the bake computed from the old key and salt, such as the
304
+ permissions hash of the anonymous user, sit in the `cache.memory` bin. This snippet makes the
305
+ replayed instance use the replaying site's values, with `$salt` set to that site's hash salt:
306
+
307
+ ```php
308
+ use Drupal\Core\Site\Settings;
309
+
310
+ (function (string $salt) {
311
+ $this->storage['hash_salt'] = $salt;
312
+ })->call(Settings::getInstance(), $salt);
313
+
314
+ (function () {
315
+ $this->reset();
316
+ $this->keysSetDuringRequest = [];
317
+ })->call(Drupal::state());
318
+
319
+ Drupal::service('cache.memory')->deleteAll();
320
+ mt_srand(unpack('V', random_bytes(4))[1]);
321
+ ```
322
+
323
+ Run it before any other PHP in the replayed instance. A host that resets `State` at the start of
324
+ each request still needs the salt and the random seed, and needs the key step for code that runs
325
+ before the first request. The measured effect for a PHP interpreter is in the Baked Boot Images
326
+ section of the technical report.
327
+
328
+ ## ๐Ÿงฑ Execution and Memory
329
+
330
+ Proved finite, nontrapping i32 kernels use runtime bounds and cross-region overlap checks, then
331
+ run native instructions against the shared allocation with no tracking or commit copy. A failed
332
+ guard falls back to tracked execution.
333
+
334
+ Tracked regions read a frozen shared base and keep private byte overlays. Once every reader stops,
335
+ Folio validates and commits in order. Conflicts replay against committed state, budgets discard
336
+ speculation, and ordered traps keep their preceding writes while later results are discarded.
337
+
338
+ The coordinator keeps admitted scalar control flow and live results. Inline numeric-memory spans
339
+ become regions when modified locals have no external live-outs and are assigned before reads on
340
+ every admitted path. Pure nonrecursive calls with unused results also qualify. Opaque functions,
341
+ recursion, host effects and state operations join preceding regions and run at their original
342
+ owner. Transactional memory covers i32, i64, f32 and f64 scalar operations plus `memory.copy` and
343
+ `memory.fill`, including unaligned access, overlap, NaN payloads, bounds and traps. Growth and
344
+ initialization stay at the coordinator. Unsupported instructions, reference and vector state,
345
+ memory64 and multiple memories keep native execution.
346
+
347
+ Shared source memory has zero-copy physical backing across the worker group. Ordinary source memory
348
+ keeps its original identity and buffer semantics, with an explicit shared snapshot per speculative
349
+ batch and ordered writeback, and the report counts the snapshot bytes. Regions travel in batches of
350
+ up to 16 per worker, and a singleton at a join runs locally.
351
+
352
+ Each isolate keeps its own stack, globals, table, JS heap and instance. Shared linear bytes do not
353
+ merge GC heaps or make arbitrary callbacks transferable. Give Folio exclusive access to its
354
+ memories and native exports until a run settles, and refresh views after shared growth. A failure
355
+ during direct native writes can leave partial memory, so the failed group closes and the
356
+ application restores a checkpoint before retrying. Instruction-defined traps keep their order and
357
+ writes. Native stack capacity and allocation failure can differ between isolates.
358
+
359
+ ## ๐Ÿ“– API Reference
360
+
361
+ | Member | Contract |
362
+ | -------------------------------------- | ---------------------------------------------------------------------------- |
363
+ | `run(name, args?, options?)` | One entry, automatic region discovery when supported |
364
+ | `runAll([{ export, args }], options?)` | Ordered sequence of calls; the lower-level speculation primitive |
365
+ | `inspect(name)` | Automatic plan and native guard availability, with analysis diagnostics |
366
+ | `diagnostics` | Module-wide optimization refusals |
367
+ | `capabilities` | Active same-process sharing, automatic extraction and validation mode |
368
+ | `memory` | The unique accessible arena, including a coordinator-exposed hidden memory |
369
+ | `memories` | Named imported and exported memory wrappers |
370
+ | `exports` | Original native exports for trusted host integration |
371
+ | `close()` and async disposal | Join worker termination and outstanding JSPI calls; repeated close shares it |
372
+
373
+ A run returns `values`, `mode`, participating `workers`, `regions`, `replayed`, `fallbacks` and an
374
+ optional routing `reason`. Generalized execution also reports `extraction`, `memoryMode` and
375
+ `snapshotBytes`. Mode is `serial`, `speculative` or `native-shared`, and a serial run reports zero
376
+ participating workers. An analysis refusal is distinct from a runtime dependency, a failed guard
377
+ and a small-workload decision.
378
+
379
+ Run options:
380
+
381
+ - `parallel: 'auto' | 'off' | 'speculate'` chooses automatic routing, original execution or tracked
382
+ regions.
383
+ - `maximumWorkers` caps participating workers without recreating the group, which limits
384
+ contention or leaves CPU for other jobs.
385
+
386
+ Pool options are `workers` (up to four by default), `memory`, `imports`, `minimumParallelWork`
387
+ (100,000 estimated iterations for proved kernels), `minimumRegionWork` and `assumedTripCount` (both
388
+ apply when `open` prepares raw bytes), `fuel` (100,000,000), `maxTransactionBytes` (262,144),
389
+ `promising` and `profile`. A one-worker pool uses its native entry and creates no idle
390
+ worker.
391
+
392
+ Profiling is opt-in. `report.profile` holds elapsed time, worker observations, validation, commit
393
+ and replay time, and tracked read and write bytes. On generalized batches `workerWallMs` and
394
+ `workerCpuMs` hold per-region observations. Measure process CPU once at the coordinator, because
395
+ summing overlapping process-wide counters double counts.
396
+
397
+ The generated API reference is published to GitHub Pages from `bun run docs:build`.
398
+
399
+ ## ๐Ÿงช Consumer Harness
400
+
401
+ `scripts/probe/consumer.ts` measures any Wasm module against a native instance of itself. A consumer
402
+ file exports the module bytes, a factory for fresh imports and a list of cases. Each case prepares
403
+ state on the raw exports and returns the calls to time. The harness opens a native arm and one pool
404
+ per worker count, alternates the arms inside every round, and compares the whole memory and every
405
+ return value before it records a sample. A mismatch stops the run.
406
+
407
+ ```sh
408
+ node scripts/probe/consumer.ts scripts/probe/consumers/tinyimg.ts results/mine/tinyimg.jsonl 20 1,2,4,8
409
+ bun scripts/analyze/paired.ts mine tinyimg.jsonl
410
+ ```
411
+
412
+ `FOLIO_OLD_BUILD=1` adds an `old-N` arm per worker count that runs the archived source from before
413
+ static admission (`results/20261020-regress/old-build-src.tar.gz`), alternating with the current
414
+ build in the same rounds. The summary then reports `versusOld`, the old build's wall time divided by
415
+ the current one.
416
+
417
+ Every row carries wall time, process CPU and what Folio dispatched: workers, regions, replays,
418
+ fallbacks, mode and the reason it stayed serial. The closing row holds `inspect` coverage for each
419
+ entry that ran. The summary reports the paired speedup (native over Folio, within each round) and
420
+ the CPU ratio, so a run that finds nothing to split says so with its numbers. The consumers in
421
+ `scripts/probe/consumers/` cover tinyimg, a Linux machine core and a process ABI probe, a serial
422
+ recurrence, the compute kernel and a kernel whose trip count is too small to pay for dispatch.
423
+ `scripts/probe/php-workloads.ts` runs the same comparison on a PHP 8.5 build that serves Drupal.
424
+
425
+ `scripts/probe/php-contexts.ts` opens N private PHP instances, one per worker thread, and runs a
426
+ snippet or the uncached Drupal render in each. Every result carries timestamps from inside the
427
+ thread and thread CPU, so a run can show that two instances executed at the same time.
428
+ `scripts/probe/php-concurrent.ts` uses it for the four-arm comparison of independent requests
429
+ (native serial, native concurrent, Folio serial, Folio concurrent). Independent requests scale
430
+ with the number of instances whether or not Folio is involved; the library adds nothing to that
431
+ result and the numbers are in the technical report.
432
+
433
+ `scripts/probe/php-regen.ts` regenerates a set of Drupal pages with private contexts pulling from
434
+ one queue and aborts if any page differs from the serial render. On ten cores it reproduced 31 pages
435
+ 7.65x faster than one context. It also runs under Bun, which the task pool supports.
436
+
437
+ ## ๐Ÿ“ˆ Measured Results
438
+
439
+ | Backend | Environment | Result |
440
+ | ---------------------------- | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
441
+ | Node, shared allocation | Ryzen 9 9900X, eight pinned workers, 256 MiB arena | 7.52x median elapsed speedup on a normally inlined C entry, 4.87% extra CPU work, every byte exact |
442
+ | Node, compute kernel | eight workers, 207 byte-exact samples | 7.62x, with total CPU 1.037x of serial |
443
+ | Node, Drupal regeneration | Ryzen 9 9900X, ten private contexts, 31 pages, n=20 | 7.65x median over one context, 1.087x process CPU, every page equal to the serial render |
444
+ | Managed Workers | deployed Durable Object lanes | 39 of 39 rows exact over RPC, fetch, streams and WebSockets; 1.62x end to end at four lanes |
445
+ | Browser Run | deployed Chromium, eight workers on one 256 MiB allocation | 3.87x with four workers on explicit partitions |
446
+ | Browser automatic extraction | FREE account, no JSPI, one ordinary counted-loop call over 256 MiB | 3.45x at eight workers, all memory and returns exact; n=3 exploratory wall time |
447
+ | Baked boot image | PHP 8.5.12 Drupal host in a Durable Object, assets, n=4 per arm | first request 72.9% less cpuTime and 52.4% less wall; serve after a drop 43.9% less cpuTime |
448
+
449
+ A streaming workload stops improving near four workers, and `maximumWorkers` caps the pool per run.
450
+ Managed Workers cannot share physical memory across isolates, so that backend copies snapshots. The
451
+ [technical report](TECHNICAL_REPORT.md) lists every figure with its instrument, the raw samples
452
+ live in [results/](results), and the Cloudflare probes are described in
453
+ [experiments/](experiments/README.md).
454
+
455
+ ## ๐Ÿ”ง Development
456
+
457
+ ```sh
458
+ bun install
459
+ bun run build:c # compile the C fixtures in tests/c with LLVM
460
+ bun run typecheck
461
+ bun run test # unit gate
462
+ bun run test:integration # local workerd probes and the managed lanes
463
+ bun run build
464
+ bun run example
465
+ ```
466
+
467
+ Fixtures need `clang` and `wasm-ld` with the `wasm32` target. Tests need Node 26 for JSPI.
468
+ `bun run test:coverage` runs the unit and integration projects with coverage, and `bun run
469
+ test:e2e` deploys the probes to a Cloudflare account when `FREE_CLOUDFLARE_ACCOUNT_ID` and
470
+ `FREE_CLOUDFLARE_API_TOKEN` are set; the experiments also accept `FOLIO_CLOUDFLARE_ACCOUNT_ID` and
471
+ `FOLIO_CLOUDFLARE_API_TOKEN`. Layout notes live in [tests/](tests/README.md),
472
+ [scripts/](scripts/README.md) and [experiments/](experiments/README.md).
473
+
474
+ ## ๐Ÿค Contributing
475
+
476
+ Open an issue before a large change. Run `bun run typecheck`, `bun run test` and
477
+ `bun run prettier:check` before sending a pull request. Changes to the compiler need a differential
478
+ test against native execution, and a performance claim needs a paired measurement with its raw
479
+ samples.
480
+
481
+ ## ๐Ÿ“„ License
482
+
483
+ MIT. See [LICENSE](LICENSE).