@gmitch215/folio 1.0.1 → 1.2.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.
Files changed (130) hide show
  1. package/README.md +98 -460
  2. package/dist/boot.d.ts +1 -0
  3. package/dist/boot.js +1 -0
  4. package/dist/browser/index.d.ts +73 -0
  5. package/dist/browser/index.js +277 -0
  6. package/dist/browser.d.ts +1 -68
  7. package/dist/browser.js +1 -274
  8. package/dist/continuation.d.ts +1 -0
  9. package/dist/continuation.js +1 -0
  10. package/dist/{compiler.d.ts → execution/compiler.d.ts} +1 -1
  11. package/dist/{compiler.js → execution/compiler.js} +5 -12
  12. package/dist/{coordinator.d.ts → execution/coordinator.d.ts} +1 -1
  13. package/dist/{coordinator.js → execution/coordinator.js} +55 -8
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +22 -13
  15. package/dist/{extract.js → execution/extract.js} +137 -10
  16. package/dist/execution/fold.d.ts +44 -0
  17. package/dist/execution/fold.js +105 -0
  18. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  19. package/dist/execution/runs.d.ts +44 -0
  20. package/dist/execution/runs.js +182 -0
  21. package/dist/{transaction.d.ts → execution/transaction.d.ts} +10 -0
  22. package/dist/execution/types.d.ts +221 -0
  23. package/dist/folds/affine-state.d.ts +142 -0
  24. package/dist/folds/affine-state.js +737 -0
  25. package/dist/folds/affine.d.ts +148 -0
  26. package/dist/folds/affine.js +562 -0
  27. package/dist/folds/boundaries.d.ts +48 -0
  28. package/dist/folds/boundaries.js +119 -0
  29. package/dist/folds/certified.d.ts +55 -0
  30. package/dist/folds/certified.js +178 -0
  31. package/dist/folds/certify.d.ts +87 -0
  32. package/dist/folds/certify.js +2611 -0
  33. package/dist/footprints/memo.d.ts +74 -0
  34. package/dist/footprints/memo.js +256 -0
  35. package/dist/footprints/ranges.d.ts +78 -0
  36. package/dist/footprints/ranges.js +263 -0
  37. package/dist/footprints/read-scan.d.ts +18 -0
  38. package/dist/footprints/read-scan.js +94 -0
  39. package/dist/footprints/read-windows.d.ts +77 -0
  40. package/dist/footprints/read-windows.js +245 -0
  41. package/dist/index.d.ts +16 -4
  42. package/dist/index.js +14 -2
  43. package/dist/iteration/admission.d.ts +149 -0
  44. package/dist/iteration/admission.js +201 -0
  45. package/dist/iteration/index.d.ts +239 -0
  46. package/dist/iteration/index.js +1210 -0
  47. package/dist/iteration/inline.d.ts +182 -0
  48. package/dist/{inline.js → iteration/inline.js} +277 -21
  49. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +16 -3
  50. package/dist/{iteration-owner.js → iteration/owner.js} +6 -5
  51. package/dist/iteration/worker.js +216 -0
  52. package/dist/{managed.d.ts → managed/index.d.ts} +75 -3
  53. package/dist/managed/index.js +817 -0
  54. package/dist/managed/outbox.d.ts +128 -0
  55. package/dist/managed/outbox.js +156 -0
  56. package/dist/managed/pool.d.ts +221 -0
  57. package/dist/managed/pool.js +310 -0
  58. package/dist/managed/tasks.d.ts +154 -0
  59. package/dist/managed/tasks.js +183 -0
  60. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  61. package/dist/{bake.js → memory/bake.js} +9 -7
  62. package/dist/memory/continuation.d.ts +141 -0
  63. package/dist/memory/continuation.js +495 -0
  64. package/dist/memory/elastic-peer.d.ts +20 -0
  65. package/dist/memory/elastic-peer.js +39 -0
  66. package/dist/memory/elastic-sql.d.ts +11 -0
  67. package/dist/memory/elastic-sql.js +35 -0
  68. package/dist/memory/elastic.d.ts +130 -0
  69. package/dist/memory/elastic.js +475 -0
  70. package/dist/memory/growth-governor.d.ts +16 -0
  71. package/dist/memory/growth-governor.js +42 -0
  72. package/dist/memory/imports.d.ts +10 -0
  73. package/dist/memory/imports.js +89 -0
  74. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +61 -1
  75. package/dist/{iteration-layout.js → memory/iteration-layout.js} +54 -3
  76. package/dist/memory/lease.d.ts +45 -0
  77. package/dist/memory/lease.js +274 -0
  78. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  79. package/dist/memory.d.ts +5 -10
  80. package/dist/memory.js +5 -89
  81. package/dist/{context.d.ts → node/context.d.ts} +17 -3
  82. package/dist/{context.js → node/context.js} +60 -14
  83. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  84. package/dist/{host.js → node/host.js} +2 -2
  85. package/dist/{node.d.ts → node/index.d.ts} +46 -49
  86. package/dist/{node.js → node/index.js} +101 -26
  87. package/dist/{tasks.d.ts → node/tasks.d.ts} +16 -17
  88. package/dist/{tasks.js → node/tasks.js} +12 -11
  89. package/dist/node/worker.d.ts +1 -0
  90. package/dist/{worker.js → node/worker.js} +2 -2
  91. package/dist/ownership/index.d.ts +161 -0
  92. package/dist/ownership/index.js +6565 -0
  93. package/dist/ownership/redirect.d.ts +30 -0
  94. package/dist/ownership/redirect.js +179 -0
  95. package/dist/ownership/slices.d.ts +44 -0
  96. package/dist/ownership/slices.js +72 -0
  97. package/dist/{frames.d.ts → remote/frames.d.ts} +6 -2
  98. package/dist/remote/frames.js +306 -0
  99. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  100. package/dist/{remote.js → remote/index.js} +7 -2
  101. package/dist/routing/index.d.ts +203 -0
  102. package/dist/routing/index.js +671 -0
  103. package/dist/routing/worker.d.ts +1 -0
  104. package/dist/routing/worker.js +4 -0
  105. package/dist/slices/index.d.ts +126 -0
  106. package/dist/slices/index.js +441 -0
  107. package/dist/slices/worker.d.ts +1 -0
  108. package/dist/slices/worker.js +38 -0
  109. package/dist/workers.d.ts +5 -0
  110. package/dist/workers.js +5 -0
  111. package/package.json +32 -46
  112. package/dist/frames.js +0 -159
  113. package/dist/inline.d.ts +0 -68
  114. package/dist/iteration-admission.d.ts +0 -76
  115. package/dist/iteration-admission.js +0 -72
  116. package/dist/iteration-worker.js +0 -150
  117. package/dist/iteration.d.ts +0 -163
  118. package/dist/iteration.js +0 -435
  119. package/dist/managed.js +0 -421
  120. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  121. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  122. /package/dist/{guards.js → execution/guards.js} +0 -0
  123. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  124. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  125. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  126. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  127. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  128. /package/dist/{pages.js → memory/pages.js} +0 -0
  129. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  130. /package/dist/{values.js → remote/values.js} +0 -0
package/README.md CHANGED
@@ -1,12 +1,13 @@
1
1
  # 🚋 Folio
2
2
 
3
- > ⚡ Shared WebAssembly memory and ordered speculative execution across isolates
3
+ > ⚡ WebAssembly tooling for Node, Workers and browsers
4
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.
5
+ Folio is a toolkit for running, resetting and bounding WebAssembly modules in JavaScript runtimes.
6
+ Its core runs native WebAssembly across several V8 isolates that share one physical memory
7
+ allocation. It finds inline memory regions and pure calls in ordinary programs, validates the ones
8
+ it cannot prove independent, and keeps the serial result. Around the core sit task and slice pools,
9
+ exact stream folds, instance checkpoints, baked boot images, a growth governor and a portable client
10
+ for workerd and managed Cloudflare Workers.
10
11
 
11
12
  ## Table of Contents
12
13
 
@@ -15,34 +16,31 @@ the same engine.
15
16
  - [Install](#-install)
16
17
  - [Getting Started](#-getting-started)
17
18
  - [Examples](#-examples)
18
- - [Asynchronous Host Effects](#-asynchronous-host-effects)
19
- - [Execution Host](#-execution-host)
20
- - [Managed Workers](#-managed-workers)
21
- - [Browser Execution and Page Leases](#-browser-execution-and-page-leases)
22
- - [Task Pool](#-task-pool)
23
- - [Context Checkpoints](#-context-checkpoints)
24
- - [Baked Boot Images](#-baked-boot-images)
25
- - [Execution and Memory](#-execution-and-memory)
26
- - [API Reference](#-api-reference)
27
- - [Consumer Harness](#-consumer-harness)
28
- - [Measured Results](#-measured-results)
19
+ - [Modules](#-modules)
20
+ - [Limits](#-limits)
29
21
  - [Development](#-development)
30
22
  - [Contributing](#-contributing)
31
23
  - [License](#-license)
32
24
 
33
25
  ## 🧭 Why Folio
34
26
 
35
- A Worker, a Linux machine in a Durable Object and a PHP interpreter all end up as one Wasm
36
- instance on one thread. Folio spreads the work of that instance across cores without asking the
37
- program to be rewritten. The caller passes one ordinary entry point. The compiler discovers the
38
- regions, so there are no access annotations and no caller-created chunks.
39
-
40
- - **Native Sharing.** Isolates map the same backing allocation, so a 256 MiB arena costs about 4 MiB
41
- to attach to another isolate instead of a copy.
42
- - **Serial Semantics.** Uncertain dependencies run on private overlays and commit in original
43
- order. A conflict replays against committed state, and a trap keeps its preceding writes.
44
- - **Original Stack.** JSPI suspends the program's own Wasm stack at joins, so branches, scalar
45
- carry and host effects behave as they do natively.
27
+ A Worker, a Linux machine in a Durable Object and a PHP interpreter all end up as one Wasm instance
28
+ on one thread. Folio spreads the work of that instance across cores without asking the program to be
29
+ rewritten. The caller passes one ordinary entry point, and the compiler discovers the regions. The
30
+ task pool, slice pool and chunked recurrences take a caller declaration instead, and the report says
31
+ which checks each route runs. The same package manages the instance itself: it resets a private
32
+ instance between jobs, starts a module from a booted heap and refuses memory growth past a cap.
33
+
34
+ - **Native Sharing.** Isolates map the same backing allocation. Four isolates attach to a touched 64
35
+ MiB backing for 3.871 MiB of additional resident memory, against 259.930 MiB for copied buffers.
36
+ - **Serial Semantics.** On the automatic routes, uncertain dependencies run on private overlays and
37
+ commit in original order. A conflict replays against committed state, and a trap keeps its
38
+ preceding writes.
39
+ - **Original Stack.** JSPI suspends the program's own Wasm stack at joins, so branches, scalar carry
40
+ and host effects behave as they do natively.
41
+ - **Instance Control.** Checkpoints restore a private instance between jobs, boot images start a
42
+ module from a booted memory, and the growth governor turns an oversized allocation into a failure
43
+ the guest can report.
46
44
  - **Portable.** The client and the managed backend use fetch, WebSockets and Durable Objects, with
47
45
  no Node imports and no request-time Wasm compilation.
48
46
 
@@ -51,20 +49,19 @@ and a small job loses to dispatch overhead.
51
49
 
52
50
  ## ✨ Features
53
51
 
54
- - 🧵 **Automatic region discovery** across branches, loops, switches, nested calls and reductions.
55
- - 🧠 **Ordered validation** with byte-granular conflict detection, replay and budget fallback.
56
- - 🛡️ **Native guards** that prove footprints, bounds and finite loops, then run on plain native
57
- instructions with no tracking.
58
- - 🔌 **Arbitrary Wasm input** as bytes, `ArrayBuffer`, `WebAssembly.Module` or a prepared plan,
59
- with imported memories, tables, globals and host functions bound as in native instantiation.
60
- - ⏳ **Asynchronous host effects** through JSPI, executed once and in call order.
61
- - 🌐 **Execution host and portable client** for workerd, with sessions, quotas and joined cleanup.
62
- - ☁️ **Managed backend** that runs entirely in Workers and Durable Objects, with binary frames and
63
- copied snapshots between lanes.
64
- - 🧰 **Task pool** that runs named functions in private contexts on other threads, with ordered
65
- joins and an optional differential audit.
66
- - 🧊 **Baked boot images** that write a booted memory into the module as data segments.
67
- - 📊 **Opt-in profiling** of worker time, validation, commit and replay cost.
52
+ | Feature | What it does | Module |
53
+ | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
54
+ | Region discovery, ordered validation, native guards and asynchronous host effects | Runs one ordinary entry on several cores and keeps the serial result | [Core](docs/modules/core.md) |
55
+ | Task pool and slice pool | Run named tasks in private contexts, or slices of a call range in place on one shared memory | [Pools](docs/modules/pools.md) |
56
+ | Exact chunked recurrences and certified stream folds | Split one CRC-32, Adler-32 or AES-CTR stream across workers and join the chunk states | [Folds and Certificates](docs/modules/folds-and-certificates.md) |
57
+ | Ownership certificates and the router | Prove that a record loop keeps its scratch private, and pick a route per call with a stated reason | [Folds and Certificates](docs/modules/folds-and-certificates.md) |
58
+ | Execution host and instance checkpoints | Serve a program over an authenticated fetch handler, and restore a private instance between jobs | [Core](docs/modules/core.md) |
59
+ | Managed Workers and portable client | Run entirely in Workers and Durable Objects, with binary frames and learned byte ranges between lanes | [Workers](docs/modules/workers.md) |
60
+ | Browser backend | Attach Web Workers to one shared memory, with page leases for transports that copy bytes | [Browser](docs/modules/browser.md) |
61
+ | Growth governor, page directory and leases | Refuse `memory.grow` past a byte cap, and hold bounded resident pages | [Memory](docs/modules/memory.md) |
62
+ | Baked boot images | Write a booted memory into the module as data segments | [Boot](docs/modules/boot.md) |
63
+ | Continuations | Run a Wasm guest across Durable Object alarm events with page-hash checkpoints in SQLite | [Continuation](docs/modules/continuation.md) |
64
+ | Profiling and the consumer harness | Time worker, validation, commit and replay cost, and time any Wasm module against a native instance of it | [Core](docs/modules/core.md) |
68
65
 
69
66
  ## 📦 Install
70
67
 
@@ -75,7 +72,7 @@ npm install @gmitch215/folio
75
72
  ```
76
73
 
77
74
  The Node backend needs Node 26 or later. Async host imports and the managed backend need WebAssembly
78
- JSPI. The browser counted-loop backend works without JSPI; page-owner transports are portable.
75
+ JSPI. The browser counted-loop backend works without JSPI, and page-owner transports are portable.
79
76
  Builds from the main branch publish to the `snapshot` tag.
80
77
 
81
78
  ## 🚀 Getting Started
@@ -96,420 +93,58 @@ try {
96
93
  ```
97
94
 
98
95
  `Folio.open(input, options)` accepts a `Uint8Array`, an `ArrayBuffer`, a `WebAssembly.Module` or the
99
- result of `prepare(bytes)`. A compiled module has no inspectable bytes and uses its native entry.
100
- Imported memory is allocated from the module's limits when omitted. Pass `memory` to bind an
101
- existing single imported memory, or bind several by their exact names in `imports`. Missing host
102
- functions, tables, globals, tags and memory64 bindings are supplied as with native instantiation.
103
- `prepare(bytes, { parallel: 'off' })` disables optimization and leaves the program unchanged.
104
- Prepared plans are trusted build artifacts.
105
-
106
- A region runs on a worker only when its estimated work pays for dispatch, joining and validation.
107
- `prepare` estimates each candidate in instruction units, charges 3,600 units for every tracked load
108
- or store, and keeps the region at its owner below `minimumRegionWork` (200,000 by default, about
109
- 39 microseconds of native work on an Apple M2 Pro). A loop bounded by a constant uses that count, a
110
- loop bounded by an untouched parameter or a countdown from one is checked against the arguments at
111
- each call, and any other loop is assumed to run `assumedTripCount` times (1,000). A module with no
112
- region above the threshold and no eligible loop gets no control plan and runs as the original Wasm, so
113
- a small kernel, a memory-bound loop or a serial recurrence stays at native speed.
114
- `minimumRegionWork: 0` admits every pure region. `folio.diagnostics` says why a plan was refused.
115
-
116
- A function with one countdown loop whose iterations are calls, such as a program that hashes several
117
- files, runs its iterations on workers when `memory` is a shared `WebAssembly.Memory`. Iterations write
118
- in place on private stack slots, validate in order and replay serially on a conflict. The first iteration
119
- runs on the owner, and its measured time and the time of each batch decide whether dispatch continues. A
120
- loop that writes more per iteration than the undo log holds, or whose batches lose to the serial time,
121
- finishes serially. With an unshared memory, or one the library cannot grow by the arena it needs, the run
122
- stays serial and the report names the reason.
96
+ result of `prepare(bytes)`. `folio.run` returns a report that names the mode (`serial`,
97
+ `speculative` or `native-shared`), the workers that took part and the reason a call stayed serial. A
98
+ region runs on a worker only when its estimated work pays for dispatch, joining and validation, so a
99
+ small kernel, a memory-bound loop or a serial recurrence stays at native speed.
100
+ [Getting Started](docs/getting-started.md) walks through the report and the choice between routes.
123
101
 
124
102
  ## 🧩 Examples
125
103
 
126
- The [examples](examples) run against the built package with `node examples/<name>.ts` after `bun run build:c` and `bun run build`: `basic` runs one entry, `routing` reads the report and shows capped and adaptive routing, `iteration` runs a loop of per-record calls on workers over a shared memory and compares the digests with the serial run, `context-reset` resets a private instance between jobs, `task-pool` joins independent jobs in order, and `boot-image` bakes captured memory into a module.
127
-
128
- ## ⏳ Asynchronous Host Effects
129
-
130
- ```ts
131
- import { Folio, suspending } from '@gmitch215/folio';
132
-
133
- const folio = await Folio.open(module, {
134
- imports: {
135
- host: {
136
- read: suspending(async (key) => (await fetch(new URL(String(key), storageUrl))).status)
137
- }
138
- },
139
- promising: ['main']
140
- });
141
- const report = await folio.run('main', [42]);
142
- await folio.close();
143
- ```
144
-
145
- This needs a runtime with WebAssembly JSPI. Listed async exports and numeric-result coordinator
146
- entries receive a promising wrapper. Reference-returning exports keep their native ABI, because
147
- Promise assimilation would change an externref Promise's identity. Host effects run once in call
148
- order and exceptions keep their identity. Opaque references stay in the original isolate. Closing
149
- joins a suspended native call; it cannot cancel an arbitrary external Promise.
150
-
151
- ## 🌉 Execution Host
152
-
153
- `@gmitch215/folio/host` registers trusted artifacts, bindings and export allowlists through
154
- `FolioHost`. Its authenticated fetch handler exposes ordered run, read, write and close operations
155
- with joined disposal and bounded admission. `@gmitch215/folio/remote` is the client for it.
156
-
157
- ```ts
158
- import { RemoteFolio } from '@gmitch215/folio/remote';
159
-
160
- const remote = await RemoteFolio.open(endpoint, 'fixture', {
161
- headers: { authorization: `Bearer ${token}` },
162
- workers: 4
163
- });
164
- try {
165
- await remote.write(1024, inputBytes);
166
- const report = await remote.run('program', [1024, wordCount, rounds]);
167
- const output = await remote.read(1024, inputBytes.length);
168
- } finally {
169
- await remote.close();
170
- }
171
- ```
172
-
173
- The client runs in stock workerd with no Node imports and no runtime Wasm compilation. Requests and
174
- results cross a serialized transport, and physical sharing happens inside the host. Each session
175
- caches its last accepted result, so `retryPending()` recovers a lost response without repeating
176
- effects. The cache is bounded and held in memory. Memory admission checks the initial accessible
177
- backing, and trusted artifact factories enforce growth maxima and private-memory budgets.
178
-
179
- ## 📡 Managed Workers
180
-
181
- `@gmitch215/folio/managed` exports `ManagedFolio` and `FolioLane` for execution entirely in managed
182
- Workers and Durable Objects. `ManagedFolio` takes precompiled artifact modules and lane transports
183
- whose `execute(frame)` returns a binary response, and `FolioLane` runs the tracked region module.
184
- The original JSPI coordinator keeps control flow and host effects, and copied snapshots with
185
- ordered byte validation connect independent lanes. A transport failure falls back to native owner
186
- execution. Snapshot, frame, fuel and tracking bounds are configurable, and the canonical memory
187
- must fit the owner runtime. Frames carry the whole snapshot by default. `snapshotEncoding: 'auto'` omits pages
188
- that are all zero, which saves traffic for sparse arenas, and lanes older than 1.0.1 reject its
189
- frames. The snapshot limit is 31 MiB by default. A frame over `maximumFrameBytes` (the snapshot limit
190
- plus 1 MiB, capped below the 32 MiB Workers RPC argument limit) is not sent: that call runs at the
191
- owner and `diagnostics` names the frame size and the limit. See [the managed procedure](experiments/managed/METHOD.md).
192
-
193
- ## 🔗 Browser Execution and Page Leases
194
-
195
- `@gmitch215/folio/browser` exports `BrowserFolio` for Chromium and other hosts without JSPI. It
196
- takes a precompiled original module and the `loops`, `native`, `reasons` and `memories` metadata
197
- that `prepare` produced offline. `open()` attaches dedicated module workers to the supplied shared
198
- memory. `run(name, args)` derives guarded partitions from one ordinary counted-loop call and joins
199
- before it returns, with no snapshot and no runtime compiler. Other entries use the original owner.
200
- The caller keeps exclusive ownership of the arena. A failure after native writes closes the pool,
201
- and the application restores a checkpoint before retrying.
202
-
203
- `@gmitch215/folio/pages` exports `PageDirectory`, `MemoryPageOwner`, `ResidentPageLease` and the
204
- `PageOwner` transport contract. `acquire({ read, write })` obtains bounded resident pages and
205
- `lease.view(page)` returns a private view of one. `commit()` stages immutable versions and
206
- atomically publishes their manifest, `abort()` discards local changes, and `collect()` reclaims
207
- retired versions with delayed-message fencing. The directory holds page metadata, not a whole heap.
208
-
209
- Leases work on copied bytes, and the bundled owners and directory keep their state in memory. The
210
- [technical report](TECHNICAL_REPORT.md) covers failure semantics, the native Wasm measurements and
211
- the limits of both modules.
212
-
213
- ## 🧰 Task Pool
214
-
215
- `@gmitch215/folio/tasks` runs independent work that a program names itself. A `TaskPool` owns one
216
- channel per worker. The caller starts each worker with `pool.link(index)` and calls `serveTasks`
217
- there with a function that runs a named task. The owner calls `submit(name, input)` and keeps going,
218
- then `join(handle)` blocks until the output arrives, or `joinAsync(handle)` waits without blocking
219
- the event loop. `run(jobs)` submits a list and returns the results in submission order, and
220
- `runSync(jobs)` does the same where the caller cannot yield, such as inside a synchronous Wasm
221
- import. Input and output are strings or bytes, `submitJson` and `result.json()` cover structured
222
- values, and `pool.width` limits how many workers take tasks.
223
-
224
- ```ts
225
- import { Worker } from 'node:worker_threads';
226
- import { TaskPool } from '@gmitch215/folio/tasks';
227
-
228
- const pool = new TaskPool(4);
229
- for (let index = 0; index < pool.size; index++) {
230
- const link = pool.link(index);
231
- new Worker(new URL('./task-worker.js', import.meta.url), {
232
- workerData: { link },
233
- transferList: [link.port]
234
- });
235
- }
236
-
237
- const results = await pool.run([
238
- ['render', 'page-1'],
239
- ['render', 'page-2']
240
- ]);
241
- console.log(results.map((result) => result.text()));
242
- ```
243
-
244
- ```ts
245
- import { workerData } from 'node:worker_threads';
246
- import { serveTasks } from '@gmitch215/folio/tasks';
247
-
248
- serveTasks(workerData.link, (name, input) => {
249
- // run the task called `name` on `input` and return its output
250
- return String(input);
251
- });
252
- ```
253
-
254
- A worker shares nothing with the owner. Each task runs against that worker's own state, so a task
255
- that reads or writes state the serial program would have shared returns a different result than the
256
- serial run. `audit: { run, every }` runs every nth task again in the joining thread and throws
257
- `TaskConflictError` with the first differing byte. The audit costs one serial execution per checked
258
- task and is meant for tests and canaries. `drain()` returns a record per joined task with its worker,
259
- start and end time, thread CPU time and byte counts, and `peakConcurrency(records)` reports how many
260
- tasks ran at the same time.
261
-
262
- The pool does not discover independent work. Region discovery and ordered validation stay in the
263
- core engine, and the task pool covers programs that can say which calls are independent.
264
-
265
- ## 🔄 Context Checkpoints
266
-
267
- `@gmitch215/folio/context` resets a private Wasm instance between independent jobs.
268
- `prepareContext(bytes)` from `@gmitch215/folio/compiler` adds exports for every memory, mutable
269
- numeric global and table, and leaves function bodies and start sections as they are. An
270
- `InstanceCheckpoint` copies that state once after initialization. `restore()` compares each 64 KiB
271
- page with the copy, rewrites the pages that differ, and puts back globals and table references.
272
- `restore('full')` copies every byte instead. Different inputs may dirty different pages, so the
273
- checkpoint learns no page set from an earlier run.
274
-
275
- ```ts
276
- import { prepareContext } from '@gmitch215/folio/compiler';
277
- import { InstanceCheckpoint } from '@gmitch215/folio/context';
278
-
279
- const plan = prepareContext(bytes);
280
- const instance = new WebAssembly.Instance(new WebAssembly.Module(plan.bytes), imports);
281
- initialize(instance);
282
- const checkpoint = new InstanceCheckpoint(instance, plan);
283
-
284
- for (const job of jobs) {
285
- run(instance, job);
286
- checkpoint.restore();
287
- }
288
- ```
289
-
290
- A module that drops a passive data or element segment, uses Wasm GC objects, or holds a reference or
291
- `v128` global cannot be restored through exports. `prepareContext` then keeps the original bytes and
292
- lists the causes in `plan.reasons`, and `InstanceCheckpoint` throws so the caller creates a fresh
293
- instance for each job. Memory or table growth throws `ContextResetError` before anything is
294
- written, and the caller instantiates a new context. Host resources and the objects behind
295
- `externref` values stay with the caller. `restore()` reads every page, so its cost follows the memory
296
- size and not the number of changed pages.
297
-
298
- ## 🧊 Baked Boot Images
299
-
300
- `@gmitch215/folio/bake` moves a booted memory into the module. `captureImage(booted, fresh)` compares
301
- a booted memory with a fresh instance of the same module and keeps the 64 KiB pages that differ.
302
- `bakeModule(bytes, image)` returns the module with those pages as active data segments after its own,
303
- so instantiating it starts from the booted memory. It uses binaryen, loaded on the first bake, and
304
- writes memory 0.
305
-
306
- ```ts
307
- import { bakeModule, captureImage, imagePages, moduleDigest } from '@gmitch215/folio/bake';
308
-
309
- const fresh = new WebAssembly.Memory({ initial: 1024 });
310
- const booted = new WebAssembly.Memory({ initial: 1024 });
311
- // instantiate `bytes` on each memory, then run the boot sequence on `booted`
312
-
313
- const image = captureImage(booted, fresh, { module: await moduleDigest(bytes) });
314
- const baked = await bakeModule(bytes, image);
315
-
316
- const memory = new WebAssembly.Memory({ initial: imagePages(image).memoryPages });
317
- const { instance } = await WebAssembly.instantiate(baked, { env: { memory } });
318
- ```
319
-
320
- The caller creates an imported memory with at least `memoryPages` pages. A defined memory that
321
- starts smaller has its initial pages raised to the image size, and its maximum, shared and memory64
322
- flags stay as they are. A page that boot zeroed but the module's own data had set is stored as
323
- zeros, and pages that are zero in both are left out. Pass the global values and a pre-boot copy of
324
- the same instance's table references to `captureImage` as `globals` and `table`; it records what boot
325
- changed. `bakeModule` writes changed i32, i64, f32 and f64 globals into their initial values and
326
- refuses changed table slots unless `allowTableChanges` is set. It throws `ImageMismatchError`, which
327
- has a `code`, for a wrong module digest, a start function, no memory, an image over the memory maximum and a global it
328
- cannot rewrite. Adjacent pages become one segment of at most `maxSegmentBytes` (64 MiB).
329
-
330
- `applyImage(memory, image)` copies the pages into a fresh instance's memory without baking. It
331
- cannot set a module's globals or table slots, so an image that records changed ones is refused with
332
- code `global` or `table`; `{ memoryOnly: true }` copies the memory anyway and leaves the instance
333
- with its fresh globals, which is not a booted instance. A module whose boot changes globals (the
334
- PHP 8.5.12 build changes its stack bounds) belongs in `bakeModule`.
335
- `captureImage` takes a `context` string beside the module digest, a digest of whatever else shapes
336
- the heap (settings, shims, assets), and `applyImage(memory, image, { module, context })` refuses an
337
- image whose module or context differs, or that carries none, with `ImageMismatchError` code `digest`
338
- or `context` and before it writes a byte. `encodeImage` and `decodeImage` store an image beside the
339
- module and reject truncated or unknown input with `ImageFormatError`. `checkBaked(baked, image)`
340
- reads the data segments back and compares them with the image without instantiating.
341
- `bakeModule` throws code `memories` for a module with more than one memory.
342
-
343
- The image is the heap as it was, so anything the booted process held is in the baked module and
344
- becomes public with it. State kept in JavaScript, such as handles and open descriptors, is not
345
- captured. `findInImage(image, needles)` returns every offset where a needle's bytes occur in the
346
- image pages, so a secret and its base64 and hex forms can be searched for before the module ships.
347
- Freed memory is not zeroed, so a secret that was ever in the heap cannot be scrubbed out of an
348
- image afterwards: bake a site whose key and salt are throwaway values, and give the replaying site
349
- its own.
350
-
351
- For a Drupal heap that means three replacements after the replay. The hash salt lives in the static
352
- `Settings` object; the private key lives in the `State` cache collector, which serves it from memory
353
- once read; and PHP's Mersenne Twister state is in the heap, so every replayed instance would draw
354
- the same `mt_rand()` sequence. Values the bake computed from the old key and salt, such as the
355
- permissions hash of the anonymous user, sit in the `cache.memory` bin. This snippet makes the
356
- replayed instance use the replaying site's values, with `$salt` set to that site's hash salt:
357
-
358
- ```php
359
- use Drupal\Core\Site\Settings;
360
-
361
- (function (string $salt) {
362
- $this->storage['hash_salt'] = $salt;
363
- })->call(Settings::getInstance(), $salt);
364
-
365
- (function () {
366
- $this->reset();
367
- $this->keysSetDuringRequest = [];
368
- })->call(Drupal::state());
369
-
370
- Drupal::service('cache.memory')->deleteAll();
371
- mt_srand(unpack('V', random_bytes(4))[1]);
372
- ```
373
-
374
- Run it before any other PHP in the replayed instance. The bake request's PHP session identifier also
375
- stays in the heap and the library cannot renew it, so the host sets each request's own identifier
376
- before it serves the request. A host that resets `State` at the start of
377
- each request still needs the salt and the random seed, and needs the key step for code that runs
378
- before the first request. The measured effect for a PHP interpreter is in the Baked Boot Images
379
- section of the technical report.
380
-
381
- ## 🧱 Execution and Memory
382
-
383
- Proved finite, nontrapping i32 kernels use runtime bounds and cross-region overlap checks, then
384
- run native instructions against the shared allocation with no tracking or commit copy. A failed
385
- guard falls back to tracked execution.
386
-
387
- Tracked regions read a frozen shared base and keep private byte overlays. Once every reader stops,
388
- Folio validates and commits in order. Conflicts replay against committed state, budgets discard
389
- speculation, and ordered traps keep their preceding writes while later results are discarded.
390
-
391
- The coordinator keeps admitted scalar control flow and live results. Inline numeric-memory spans
392
- become regions when modified locals have no external live-outs and are assigned before reads on
393
- every admitted path. Pure nonrecursive calls with unused results also qualify. Opaque functions,
394
- recursion, host effects and state operations join preceding regions and run at their original
395
- owner. Transactional memory covers i32, i64, f32 and f64 scalar operations plus `memory.copy` and
396
- `memory.fill`, including unaligned access, overlap, NaN payloads, bounds and traps. Growth and
397
- initialization stay at the coordinator. Unsupported instructions, reference and vector state,
398
- memory64 and multiple memories keep native execution.
399
-
400
- Shared source memory has zero-copy physical backing across the worker group. Ordinary source memory
401
- keeps its original identity and buffer semantics, with an explicit shared snapshot per speculative
402
- batch and ordered writeback, and the report counts the snapshot bytes. Regions travel in batches of
403
- up to 16 per worker, and a singleton at a join runs locally.
404
-
405
- Each isolate keeps its own stack, globals, table, JS heap and instance. Shared linear bytes do not
406
- merge GC heaps or make arbitrary callbacks transferable. Give Folio exclusive access to its
407
- memories and native exports until a run settles, and refresh views after shared growth. A failure
408
- during direct native writes can leave partial memory, so the failed group closes and the
409
- application restores a checkpoint before retrying. Instruction-defined traps keep their order and
410
- writes. Native stack capacity and allocation failure can differ between isolates.
411
-
412
- ## 📖 API Reference
413
-
414
- | Member | Contract |
415
- | -------------------------------------- | ---------------------------------------------------------------------------- |
416
- | `run(name, args?, options?)` | One entry, automatic region discovery when supported |
417
- | `runAll([{ export, args }], options?)` | Ordered sequence of calls; the lower-level speculation primitive |
418
- | `inspect(name)` | Automatic plan and native guard availability, with analysis diagnostics |
419
- | `diagnostics` | Module-wide optimization refusals |
420
- | `capabilities` | Active same-process sharing, automatic extraction and validation mode |
421
- | `memory` | The unique accessible arena, including a coordinator-exposed hidden memory |
422
- | `memories` | Named imported and exported memory wrappers |
423
- | `exports` | Original native exports for trusted host integration |
424
- | `close()` and async disposal | Join worker termination and outstanding JSPI calls; repeated close shares it |
425
-
426
- A run returns `values`, `mode`, participating `workers`, `regions`, `replayed`, `fallbacks` and an
427
- optional routing `reason`. Generalized execution also reports `extraction`, `memoryMode` and
428
- `snapshotBytes`. Mode is `serial`, `speculative` or `native-shared`, and a serial run reports zero
429
- participating workers. An analysis refusal is distinct from a runtime dependency, a failed guard
430
- and a small-workload decision.
431
-
432
- Run options:
433
-
434
- - `parallel: 'auto' | 'off' | 'speculate'` chooses automatic routing, original execution or tracked
435
- regions.
436
- - `maximumWorkers` caps participating workers without recreating the group, which limits
437
- contention or leaves CPU for other jobs.
438
-
439
- Pool options are `workers` (up to four by default), `memory`, `imports`, `minimumParallelWork`
440
- (100,000 estimated iterations for proved kernels), `minimumRegionWork` and `assumedTripCount` (both
441
- apply when `open` prepares raw bytes), `fuel` (100,000,000), `maxTransactionBytes` (262,144),
442
- `promising`, `profile` and `adaptiveRouting`. With `adaptiveRouting`, a call shape (entry, width,
443
- memory size and numeric arguments) whose last two runs mostly replayed or fell back runs natively
444
- for the next 16 calls and is then probed again. It is off by default. A one-worker pool uses its native entry and creates no idle
445
- worker.
446
-
447
- Profiling is opt-in. `report.profile` holds elapsed time, worker observations, validation, commit
448
- and replay time, and tracked read and write bytes. On generalized batches `workerWallMs` and
449
- `workerCpuMs` hold per-region observations. Measure process CPU once at the coordinator, because
450
- summing overlapping process-wide counters double counts.
451
-
452
- The generated API reference is published to GitHub Pages from `bun run docs:build`.
453
-
454
- ## 🧪 Consumer Harness
455
-
456
- `scripts/probe/consumer.ts` measures any Wasm module against a native instance of itself. A consumer
457
- file exports the module bytes, a factory for fresh imports and a list of cases. Each case prepares
458
- state on the raw exports and returns the calls to time. The harness opens a native arm and one pool
459
- per worker count, alternates the arms inside every round, and compares the whole memory and every
460
- return value before it records a sample. A mismatch stops the run.
461
-
462
- ```sh
463
- node scripts/probe/consumer.ts scripts/probe/consumers/tinyimg.ts results/mine/tinyimg.jsonl 20 1,2,4,8
464
- bun scripts/analyze/paired.ts mine tinyimg.jsonl
465
- ```
466
-
467
- `FOLIO_OLD_BUILD=1` adds an `old-N` arm per worker count that runs the archived source from before
468
- static admission (`results/execution/admission/old-build-src.tar.gz`), alternating with the current
469
- build in the same rounds. The summary then reports `versusOld`, the old build's wall time divided by
470
- the current one.
471
-
472
- Every row carries wall time, process CPU and what Folio dispatched: workers, regions, replays,
473
- fallbacks, mode and the reason it stayed serial. The closing row holds `inspect` coverage for each
474
- entry that ran. The summary reports the paired speedup (native over Folio, within each round) and
475
- the CPU ratio, so a run that finds nothing to split says so with its numbers. The consumers in
476
- `scripts/probe/consumers/` cover tinyimg, a Linux machine core and a process ABI probe, a serial
477
- recurrence, the compute kernel and a kernel whose trip count is too small to pay for dispatch.
478
- `scripts/probe/php-workloads.ts` runs the same comparison on a PHP 8.5 build that serves Drupal.
479
-
480
- `scripts/probe/php-contexts.ts` opens N private PHP instances, one per worker thread, and runs a
481
- snippet or the uncached Drupal render in each. Every result carries timestamps from inside the
482
- thread and thread CPU, so a run can show that two instances executed at the same time.
483
- `scripts/probe/php-concurrent.ts` uses it for the four-arm comparison of independent requests
484
- (native serial, native concurrent, Folio serial, Folio concurrent). Independent requests scale
485
- with the number of instances whether or not Folio is involved; the library adds nothing to that
486
- result and the numbers are in the technical report.
487
-
488
- `scripts/probe/php-regen.ts` regenerates a set of Drupal pages with private contexts pulling from
489
- one queue and aborts if any page differs from the serial render. On ten cores it reproduced 31 pages
490
- 7.65x faster than one context. It also runs under Bun, which the task pool supports.
491
-
492
- ## 📈 Measured Results
493
-
494
- | Backend | Environment | Result |
495
- | ---------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
496
- | 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 |
497
- | Node, compute kernel | eight workers, 207 byte-exact samples | 7.62x, with total CPU 1.037x of serial |
498
- | 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 |
499
- | 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 |
500
- | Browser Run | deployed Chromium, eight workers on one 256 MiB allocation | 3.87x with four workers on explicit partitions |
501
- | 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 |
502
- | 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 |
503
- | Independent corpus | 21 kernels from nine upstream projects, Ryzen 9 9900X and Apple M2 Pro | default admission finds no plan and dispatches no worker for any kernel; forcing admission makes all 11 kernels that receive regions slower than native |
504
- | Explicit tasks on private contexts | the same 21 kernels, eight batched `TaskPool` workers | 18 of 21 reach 2x or more with a learned-page reset and 8 of 21 with the input-independent checkpoint reset; the eight-worker arm varies by up to 1.5x between runs |
505
- | Iteration route, outside program | BLAKE3 1.8.7 unmodified, 32 x 4 MiB and 128 x 256 KiB, Ryzen 9 9900X and M2 Pro | default admission through `Folio.run`: 2.4x to 3.1x and 2.0x on the Ryzen machine, 3.2x to 3.5x and 2.8x to 2.9x on the M2 Pro (warm calls, equal digests); 1.00x before. SHA-256 with a helper per input 1.7x to 2.1x, LZ4 no gain |
506
- | Baked Drupal lifecycle | Apple M2 Pro, 15 paired rounds, compile through first render | 830.5 ms to 444.7 ms elapsed (1.90x), process CPU 0.56 of native, 12 of 13 selected configurations reuse the image |
507
-
508
- A streaming workload stops improving near four workers, and `maximumWorkers` caps the pool per run.
509
- Managed Workers cannot share physical memory across isolates, so that backend copies snapshots. The
510
- [technical report](TECHNICAL_REPORT.md) lists every figure with its instrument, the raw samples
511
- live in [results/](results), and the Cloudflare probes are described in
512
- [experiments/](experiments/README.md).
104
+ The [examples](https://github.com/gmitch215/folio/tree/master/examples) run against the built
105
+ package with `node examples/<name>.ts` after `bun run build:c` and `bun run build`:
106
+
107
+ - `basic` runs one entry.
108
+ - `routing` reads the report and shows capped and adaptive routing.
109
+ - `iteration` runs a loop of per-record calls on workers over a shared memory and compares the
110
+ digests with the serial run.
111
+ - `context-reset` resets a private instance between jobs.
112
+ - `task-pool` joins independent jobs in order.
113
+ - `slice-pool` fills one shared memory from several threads and audits the run against the serial
114
+ one.
115
+ - `boot-image` bakes captured memory into a module.
116
+ - `growth-governor` caps `memory.grow` on a guest's memory and shows the guest's failed allocation.
117
+ - `continuation` runs a guest across alarm events with checkpoints in storage.
118
+
119
+ [Advanced Usage](ADVANCED_USAGE.md) combines these for specialised cases.
120
+
121
+ ## 🗂️ Modules
122
+
123
+ Folio has six subpaths. Each one names a runtime boundary or a feature.
124
+
125
+ | Import | Runs on | Purpose | Page |
126
+ | ------------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------- |
127
+ | `@gmitch215/folio` | Node | `Folio`, the compiler, folds, certificates, the router, task and slice pools, the execution host | [Core](docs/modules/core.md) |
128
+ | `@gmitch215/folio/workers` | Workers and Durable Objects | `ManagedFolio`, `FolioLane`, the remote client `RemoteFolio` and the frame and value codecs | [Workers](docs/modules/workers.md) |
129
+ | `@gmitch215/folio/browser` | Browsers without JSPI | `BrowserFolio`, which runs one counted-loop call on shared memory | [Browser](docs/modules/browser.md) |
130
+ | `@gmitch215/folio/memory` | Portable | Page directories and leases, the growth governor and elastic regions | [Memory](docs/modules/memory.md) |
131
+ | `@gmitch215/folio/boot` | Portable | Boot images: `bakeModule`, `captureImage`, `applyImage`, `checkBaked` and the image errors | [Boot](docs/modules/boot.md) |
132
+ | `@gmitch215/folio/continuation` | Portable | Wasm guests across Durable Object alarm events, with page-hash checkpoints in Durable Object SQLite | [Continuation](docs/modules/continuation.md) |
133
+
134
+ [Modules](docs/modules/README.md) helps choose between them, and
135
+ [Configuration](docs/configuration.md) lists every option. Subpaths from 1.1 that are not in this
136
+ table are no longer exported, and the
137
+ [CHANGELOG](https://github.com/gmitch215/folio/blob/master/CHANGELOG.md) lists where each of their
138
+ names moved. The generated API reference is published to GitHub Pages from `bun run docs:build`.
139
+
140
+ ## ⚠️ Limits
141
+
142
+ Folio keeps the serial result and does not promise a speedup. The automatic routes found no gain on
143
+ independent library kernels and on three unmodified outside programs, and the explicit routes win
144
+ where the caller names the independent work. [Limits](docs/limits.md) lists what does not
145
+ parallelize, the gates that were not met and the platform limits, and the
146
+ [technical report](TECHNICAL_REPORT.md) holds the figures, the instruments and the raw samples under
147
+ [results](https://github.com/gmitch215/folio/tree/master/results).
513
148
 
514
149
  ## 🔧 Development
515
150
 
@@ -524,11 +159,13 @@ bun run example
524
159
  ```
525
160
 
526
161
  Fixtures need `clang` and `wasm-ld` with the `wasm32` target. Tests need Node 26 for JSPI.
527
- `bun run test:coverage` runs the unit and integration projects with coverage, and `bun run
528
- test:e2e` deploys the probes to a Cloudflare account when `FREE_CLOUDFLARE_ACCOUNT_ID` and
529
- `FREE_CLOUDFLARE_API_TOKEN` are set; the experiments also accept `FOLIO_CLOUDFLARE_ACCOUNT_ID` and
530
- `FOLIO_CLOUDFLARE_API_TOKEN`. Layout notes live in [tests/](tests/README.md),
531
- [scripts/](scripts/README.md) and [experiments/](experiments/README.md).
162
+ `bun run test:coverage` runs the unit and integration projects with coverage, and `bun run test:e2e`
163
+ deploys the probes to a Cloudflare account when `FREE_CLOUDFLARE_ACCOUNT_ID` and
164
+ `FREE_CLOUDFLARE_API_TOKEN` are set. The experiments also accept `FOLIO_CLOUDFLARE_ACCOUNT_ID` and
165
+ `FOLIO_CLOUDFLARE_API_TOKEN`. Layout notes live in
166
+ [tests/](https://github.com/gmitch215/folio/blob/master/tests/README.md),
167
+ [scripts/](https://github.com/gmitch215/folio/blob/master/scripts/README.md) and
168
+ [experiments/](https://github.com/gmitch215/folio/blob/master/experiments/README.md).
532
169
 
533
170
  ## 🤝 Contributing
534
171
 
@@ -539,4 +176,5 @@ samples.
539
176
 
540
177
  ## 📄 License
541
178
 
542
- MIT. See [LICENSE](LICENSE).
179
+ MIT. See [LICENSE](https://github.com/gmitch215/folio/blob/master/LICENSE). The documentation
180
+ favicons in `docs/` are the Fluent UI Emoji tram car from Microsoft, licensed under MIT.