@gmitch215/folio 1.0.1 โ†’ 1.1.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 (65) hide show
  1. package/README.md +398 -28
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/boundaries.d.ts +59 -0
  7. package/dist/boundaries.js +127 -0
  8. package/dist/certified.d.ts +66 -0
  9. package/dist/certified.js +192 -0
  10. package/dist/certify.d.ts +98 -0
  11. package/dist/certify.js +2628 -0
  12. package/dist/context.d.ts +16 -2
  13. package/dist/context.js +60 -14
  14. package/dist/coordinator.js +50 -3
  15. package/dist/extract.d.ts +19 -0
  16. package/dist/extract.js +133 -5
  17. package/dist/fold.d.ts +32 -0
  18. package/dist/fold.js +105 -0
  19. package/dist/frames.d.ts +5 -1
  20. package/dist/frames.js +156 -9
  21. package/dist/inline.d.ts +114 -0
  22. package/dist/inline.js +276 -13
  23. package/dist/iteration-admission.d.ts +116 -7
  24. package/dist/iteration-admission.js +137 -8
  25. package/dist/iteration-layout.d.ts +60 -0
  26. package/dist/iteration-layout.js +54 -3
  27. package/dist/iteration-owner.d.ts +14 -1
  28. package/dist/iteration-owner.js +2 -2
  29. package/dist/iteration-worker.js +124 -58
  30. package/dist/iteration.d.ts +179 -13
  31. package/dist/iteration.js +845 -70
  32. package/dist/lease.d.ts +45 -0
  33. package/dist/lease.js +274 -0
  34. package/dist/managed.d.ts +72 -0
  35. package/dist/managed.js +425 -27
  36. package/dist/memo.d.ts +99 -0
  37. package/dist/memo.js +250 -0
  38. package/dist/node.d.ts +43 -1
  39. package/dist/node.js +87 -11
  40. package/dist/ownership-redirect.d.ts +30 -0
  41. package/dist/ownership-redirect.js +179 -0
  42. package/dist/ownership-slices.d.ts +44 -0
  43. package/dist/ownership-slices.js +72 -0
  44. package/dist/ownership.d.ts +161 -0
  45. package/dist/ownership.js +6568 -0
  46. package/dist/ranges.d.ts +78 -0
  47. package/dist/ranges.js +263 -0
  48. package/dist/read-scan.d.ts +18 -0
  49. package/dist/read-scan.js +94 -0
  50. package/dist/read-windows.d.ts +103 -0
  51. package/dist/read-windows.js +244 -0
  52. package/dist/router-worker.d.ts +1 -0
  53. package/dist/router-worker.js +4 -0
  54. package/dist/router.d.ts +203 -0
  55. package/dist/router.js +667 -0
  56. package/dist/runs.d.ts +44 -0
  57. package/dist/runs.js +182 -0
  58. package/dist/slices-worker.d.ts +1 -0
  59. package/dist/slices-worker.js +38 -0
  60. package/dist/slices.d.ts +126 -0
  61. package/dist/slices.js +441 -0
  62. package/dist/tasks.d.ts +14 -4
  63. package/dist/tasks.js +12 -11
  64. package/dist/transaction.d.ts +10 -0
  65. package/package.json +40 -4
package/README.md CHANGED
@@ -20,6 +20,10 @@ the same engine.
20
20
  - [Managed Workers](#-managed-workers)
21
21
  - [Browser Execution and Page Leases](#-browser-execution-and-page-leases)
22
22
  - [Task Pool](#-task-pool)
23
+ - [Slice Pool](#-slice-pool)
24
+ - [Certified Stream Folds](#-certified-stream-folds)
25
+ - [Ownership Certificates](#-ownership-certificates)
26
+ - [Router](#-router)
23
27
  - [Context Checkpoints](#-context-checkpoints)
24
28
  - [Baked Boot Images](#-baked-boot-images)
25
29
  - [Execution and Memory](#-execution-and-memory)
@@ -35,12 +39,16 @@ the same engine.
35
39
  A Worker, a Linux machine in a Durable Object and a PHP interpreter all end up as one Wasm
36
40
  instance on one thread. Folio spreads the work of that instance across cores without asking the
37
41
  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.
42
+ regions, so on the automatic route there are no access annotations and no caller-created chunks.
43
+ The task pool, slice pool and chunked recurrences take a caller declaration instead, and the report
44
+ says which checks each route runs.
39
45
 
40
46
  - **Native Sharing.** Isolates map the same backing allocation, so a 256 MiB arena costs about 4 MiB
41
47
  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.
48
+ - **Serial Semantics.** On the automatic routes, uncertain dependencies run on private overlays and
49
+ commit in original order. A conflict replays against committed state, and a trap keeps its
50
+ preceding writes. Routes where the caller declares independence keep that contract and offer an
51
+ audit.
44
52
  - **Original Stack.** JSPI suspends the program's own Wasm stack at joins, so branches, scalar
45
53
  carry and host effects behave as they do natively.
46
54
  - **Portable.** The client and the managed backend use fetch, WebSockets and Durable Objects, with
@@ -60,9 +68,21 @@ and a small job loses to dispatch overhead.
60
68
  - โณ **Asynchronous host effects** through JSPI, executed once and in call order.
61
69
  - ๐ŸŒ **Execution host and portable client** for workerd, with sessions, quotas and joined cleanup.
62
70
  - โ˜๏ธ **Managed backend** that runs entirely in Workers and Durable Objects, with binary frames and
63
- copied snapshots between lanes.
71
+ copied snapshots or learned byte ranges between lanes.
64
72
  - ๐Ÿงฐ **Task pool** that runs named functions in private contexts on other threads, with ordered
65
73
  joins and an optional differential audit.
74
+ - ๐Ÿฐ **Slice pool** that runs slices of a call range in place on one shared memory, with a private
75
+ stack per worker and an optional serial audit, for calls the caller declares independent.
76
+ - ๐Ÿงฎ **Exact chunked recurrences** that split one CRC-32, Adler-32 or AES-CTR stream across the
77
+ task pool and join the chunk states into the serial result.
78
+ - ๐Ÿ” **Ownership certificates** that check whether the fixed-address scratch of a record function is
79
+ private to each record, so a certified loop of records runs in place on the slice pool. Each
80
+ certificate lists the premises it relies on.
81
+ - ๐Ÿšฆ **Router** that picks the certified summary, the certified window, tracked speculation or
82
+ serial for each call, caches certificates and refusals, and names the reason for every refusal.
83
+ - ๐Ÿ›‘ **Stall guard** (`iterationStall`, off by default) that stops an iteration batch that does not
84
+ return and finishes the loop serially, for programs whose iterations can loop on state another
85
+ iteration is changing.
66
86
  - ๐ŸงŠ **Baked boot images** that write a booted memory into the module as data segments.
67
87
  - ๐Ÿ“Š **Opt-in profiling** of worker time, validation, commit and replay cost.
68
88
 
@@ -121,9 +141,33 @@ loop that writes more per iteration than the undo log holds, or whose batches lo
121
141
  finishes serially. With an unshared memory, or one the library cannot grow by the arena it needs, the run
122
142
  stays serial and the report names the reason.
123
143
 
144
+ Five `Folio.open` options adjust the iteration route. All five are off by default.
145
+
146
+ | Option | Effect |
147
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
148
+ | `iterationReadWindows` | Learns read windows from the first batch that finishes without a conflict, so loads of the input the iterations stream through set no per-access mark. A window can cost a false conflict, never a different result. |
149
+ | `iterationReadSummary` | Keeps a summary of the 64-word blocks of each read bitmap that a read touched, so workers scan those blocks and not the whole bitmap. The conflicts found do not change. It adds a few instructions to every tracked read. |
150
+ | `iterationSecondChance` | Judges a loop a little under the dispatch floor on one timed batch, and lets the batches a running loop has shown decide whether the rest pays. A probe that loses ends the dispatch and the loop runs serially for the next 16 calls. The result is the same either way. |
151
+ | `iterationLogCeiling` | A number of undo entries per iteration. When a batch exhausts the default log, the logs grow to this size and the batch retries once. Unset, that batch finishes serially. On padded LZ4 the retry cost more than the dispatch gained, because ordered validation is quadratic in the logged entries. |
152
+ | `iterationStall` | `true` or `{ factor, floorMs }`. Workers poll a stop word at every loop start. A batch that runs past `factor` times the serial time of its iterations (50 by default), and at least `floorMs` (2000 ms), traps and rolls back from the undo logs, and the loop finishes serially with `iteration.stopped` set to `stalled`. The poll cost 0.9% to 11.2% of worker time on the four programs measured. |
153
+
154
+ A program whose iterations can read state another iteration is changing and then loop on it, such as
155
+ a linked structure two iterations rewrite, needs `iterationStall`.
156
+
124
157
  ## ๐Ÿงฉ Examples
125
158
 
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.
159
+ The [examples](examples) run against the built package with `node examples/<name>.ts` after
160
+ `bun run build:c` and `bun run build`:
161
+
162
+ - `basic` runs one entry.
163
+ - `routing` reads the report and shows capped and adaptive routing.
164
+ - `iteration` runs a loop of per-record calls on workers over a shared memory and compares the
165
+ digests with the serial run.
166
+ - `context-reset` resets a private instance between jobs.
167
+ - `task-pool` joins independent jobs in order.
168
+ - `slice-pool` fills one shared memory from several threads and audits the run against the serial
169
+ one.
170
+ - `boot-image` bakes captured memory into a module.
127
171
 
128
172
  ## โณ Asynchronous Host Effects
129
173
 
@@ -184,11 +228,29 @@ whose `execute(frame)` returns a binary response, and `FolioLane` runs the track
184
228
  The original JSPI coordinator keeps control flow and host effects, and copied snapshots with
185
229
  ordered byte validation connect independent lanes. A transport failure falls back to native owner
186
230
  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).
231
+ must fit the owner runtime. Frames carry the whole snapshot by default. `snapshotEncoding: 'auto'`
232
+ omits pages that are all zero, which saves traffic for sparse arenas, and lanes older than 1.0.1
233
+ reject its frames. The snapshot limit is 31 MiB by default. A frame over `maximumFrameBytes` (the
234
+ snapshot limit plus 1 MiB, capped below the 32 MiB Workers RPC argument limit) is not sent: that
235
+ call runs at the owner and `diagnostics` names the frame size and the limit. See
236
+ [the managed procedure](experiments/managed/METHOD.md).
237
+
238
+ Four options change what a call costs. `ranges` ships the byte ranges a region reads and writes,
239
+ learned from earlier calls, instead of a snapshot: an 8 MiB arena sends about 0.2% of the bytes.
240
+ `inline` on a `FolioLane` runs a module that tracks accesses in its own code, so a lane no longer
241
+ calls back into JavaScript on every load and store. `runs: true` makes lanes answer in sorted byte
242
+ runs that the owner validates and commits as intervals. `memo` reuses a recorded result when the
243
+ bytes a region read are unchanged, through the same ordered validation. `fuel` bounds the
244
+ speculative back-edges of one call (100,000,000 by default); a call that runs out finishes serially
245
+ at the owner, so a long kernel needs a larger `fuel`.
246
+
247
+ Lane placement decides whether lanes overlap. Service-bound Worker lanes share a thread with their
248
+ caller, so four of them take as long as one lane run four times. Durable Object lanes run on their
249
+ own isolates and overlap. A decomposition that fits a managed lane is a few large explicit units
250
+ with a merge the caller declares, such as SQLite shards that each scan a row-id range; a loop of
251
+ small records does not pay for a lane call. The
252
+ [sharded SQLite probe](experiments/sqlite-lanes/README.md) runs 1,000,000-row queries 2.0x to 9.7x
253
+ faster than one object at four and eight shards, with every result equal to the serial one.
192
254
 
193
255
  ## ๐Ÿ”— Browser Execution and Page Leases
194
256
 
@@ -219,7 +281,10 @@ then `join(handle)` blocks until the output arrives, or `joinAsync(handle)` wait
219
281
  the event loop. `run(jobs)` submits a list and returns the results in submission order, and
220
282
  `runSync(jobs)` does the same where the caller cannot yield, such as inside a synchronous Wasm
221
283
  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.
284
+ values, and `pool.width` limits how many workers take tasks. Input on a `SharedArrayBuffer` is copied
285
+ at submit so a later write cannot reach the task. `submit`, `run` and `runSync` take `{ share: true }`
286
+ to post such an input as it is, which removes the copy when the caller promises not to write those
287
+ bytes until the task is joined.
223
288
 
224
289
  ```ts
225
290
  import { Worker } from 'node:worker_threads';
@@ -262,6 +327,284 @@ tasks ran at the same time.
262
327
  The pool does not discover independent work. Region discovery and ordered validation stay in the
263
328
  core engine, and the task pool covers programs that can say which calls are independent.
264
329
 
330
+ `@gmitch215/folio/fold` covers one case where a single call is not independent but still splits
331
+ exactly. A CRC-32, an Adler-32 or an AES-CTR stream over one input is a recurrence with an exact
332
+ combine, so chunks run on separate tasks and join into the serial result. `chunkRanges(length,
333
+ count, align)` cuts the input, `foldChunks(pool, input, { task, initial, combine })` runs one task
334
+ per chunk and combines the results in order, and `crc32Combine`, `adler32Combine` and `ctrAdvance`
335
+ supply the algebra. AES chunks must be multiples of 16 bytes except the last. Chunks are copied into
336
+ their tasks, and 64 MiB of CRC-32 on eight workers ran 3.52x faster than serial with the result equal
337
+ to `zlib.crc32`. A recurrence with no known combine, such as one SHA-256 message, stays serial.
338
+
339
+ ## ๐Ÿฐ Slice Pool
340
+
341
+ `@gmitch215/folio/slices` runs an exported function over a range of calls on several threads, on one
342
+ shared memory, with no copy and no tracking. The caller declares that the calls are independent. A
343
+ `SlicePool` compiles the module once, marks its imported memory shared, grows the memory by one
344
+ private stack per worker when the module keeps a stack pointer global, and starts the workers.
345
+ `run(entry, count, args)` splits `[0, count)` into slices, and `args(from, to)` returns the arguments
346
+ of the call for a slice. The records go into `pool.memory` after `open`, because opening applies the
347
+ module's data segments, and the results are read from it afterwards.
348
+
349
+ ```ts
350
+ import { SlicePool } from '@gmitch215/folio/slices';
351
+
352
+ const memory = new WebAssembly.Memory({ initial: 256, maximum: 4096, shared: true });
353
+ const pool = await SlicePool.open(bytes, { memory, workers: 8 });
354
+ write(pool.memory, records); // table, input bytes and an output area
355
+
356
+ const report = await pool.run('bulk', records.length, (from, to) => [
357
+ table + 16 * from,
358
+ to - from,
359
+ out + from * slot
360
+ ]);
361
+ read(pool.memory, out, records.length * slot);
362
+ await pool.close();
363
+ ```
364
+
365
+ The module must import its memory with a declared maximum that leaves room for the stacks, and keep
366
+ at most one mutable global, which is taken to be the stack pointer. A start function, a dropped
367
+ data segment or a second mutable global refuses the module. Arguments and results are i32 or i64
368
+ (`bigint`). Imports other than the memory come from `imports`, a module specifier whose default export
369
+ returns them, because functions do not cross threads.
370
+
371
+ Nothing here checks independence. A program that writes state the serial program would share
372
+ returns a different result. `run(..., { audit: true })` copies the memory before the run, runs the
373
+ same slices serially on the copy and compares every returned value and every byte below the
374
+ stacks, and throws `SliceConflictError` with the first difference. The audit costs a serial run and a
375
+ memory copy and is meant for tests and canaries. A route that copies each task's records into a
376
+ private context cannot win on a kernel whose speed is the copy's bandwidth; the slice pool has no
377
+ copy, and on the quiet rig xxHash, Adler-32 and LZ4 decompress over thousands of records ran 1.7x
378
+ to 4.9x faster than serial on eight workers (see the technical report).
379
+
380
+ ## ๐Ÿงฎ Certified Stream Folds
381
+
382
+ `@gmitch215/folio/certify` decides whether an exported function `entry(state, ptr, len)` over a byte
383
+ stream is the left fold of one affine byte step, for every length of at least one byte, and
384
+ `@gmitch215/folio/certified` runs such a function on workers. `certifyStream(bytes, entry)` returns a
385
+ certificate or the reason it refused. The proof executes the function symbolically, so it covers the
386
+ unrolled main loop and tail that clang emits, tables the module carries or builds on its first call,
387
+ 64-bit states and internal calls. The step is affine in the state over GF(2) (bit operations), over
388
+ Z/2^w (add and multiply) or over two 16-bit residues of one modulus (Adler-32 keeps its two sums this
389
+ way), and it may apply any pure function to the input bytes.
390
+
391
+ A certificate names the module digest. `verifyCertificate(bytes, certificate)` re-derives it from the
392
+ module, and `guardInput` checks that an input range stays inside memory and clear of the bytes the proof
393
+ read. With a certificate, `foldCertified` runs every chunk once from state zero on its own worker, reads
394
+ the input in place from shared memory and combines the end states with the recovered model. It does not
395
+ run a second pass, because the certificate replaces the validation that `foldAffine` needs when it only
396
+ has a sampled model.
397
+
398
+ ```ts
399
+ import { Worker } from 'node:worker_threads';
400
+ import { certifyStream } from '@gmitch215/folio/certify';
401
+ import { foldCertified, installPrefill, shareCertified } from '@gmitch215/folio/certified';
402
+ import { TaskPool } from '@gmitch215/folio/tasks';
403
+
404
+ const certificate = certifyStream(bytes, 'crc32c');
405
+ if (certificate.kind === 'refusal') throw new Error(certificate.reason);
406
+
407
+ const pages = 256;
408
+ const subject = shareCertified(bytes, certificate, pages);
409
+ const memory = new WebAssembly.Memory({ initial: pages, maximum: pages, shared: true });
410
+ installPrefill(subject, memory);
411
+ const module = new WebAssembly.Module(subject.bytes);
412
+
413
+ const pool = new TaskPool(8);
414
+ for (let index = 0; index < 8; index++) {
415
+ const link = pool.link(index);
416
+ // worker.ts calls serveCertified(link, { module, memory, layout }) from workerData
417
+ new Worker(new URL('./worker.ts', import.meta.url), {
418
+ workerData: { link, module, memory, layout: certificate.layout },
419
+ transferList: [link.port]
420
+ });
421
+ }
422
+
423
+ const input = new Uint8Array(memory.buffer, 1 << 20, 64 * 1024 * 1024);
424
+ // fill the input here
425
+ const { state } = foldCertified(pool, input, memory, certificate);
426
+ ```
427
+
428
+ A function that also rewrites its input in place, such as a stream cipher that xors a keystream into
429
+ the buffer, gets an `output` field when the proof shows that byte i becomes a fixed function of the
430
+ original byte and the fold state before it, and that nothing else is written. When the state does not
431
+ read the input bytes, `reconstructCertified` starts every chunk at its own state, which the model gives
432
+ without running the kernel, and each worker rewrites its own bytes once. A chunk that ends in a state
433
+ the model did not predict makes it throw, because the input is already rewritten. `foldCertified`
434
+ throws for a certificate with `output`: chunks that start from state zero would write the wrong bytes.
435
+
436
+ A refusal describes the checker and not the function: a function it cannot prove runs serially or through
437
+ `foldAffine` in exact mode. The checker refuses a branch on input data or on the state, a pointer or
438
+ length used as data, state kept in memory or globals, stores other than the in-place byte rewrite,
439
+ imports, a start function and passive data segments. A function that depends on the alignment of
440
+ its pointer or reads past its input is refused. `zeroLength` in the certificate says what a call over no bytes returns, and
441
+ `foldCertified` runs an empty input as the serial call.
442
+
443
+ ## ๐Ÿ” Ownership Certificates
444
+
445
+ `@gmitch215/folio/ownership` checks whether a function that loops over records keeps its scratch
446
+ memory private to each record. Compiled drivers often write a fixed address (a scratch buffer, a
447
+ static table, a cursor) before they read it back, and records that run on several threads over one
448
+ memory collide there. `certifyOwnership(bytes, options)` takes an entry that is `bulk(table, count,
449
+ out, ...)` by default (`entry` and `convention` name another function and record layout), finds the
450
+ fixed-address windows the records write, and returns a certificate or a refusal. A certificate
451
+ covers six obligations: state isolation, read before write, aliasing through indirect pointers and
452
+ bulk operations, the final state the owner must rebuild, escaping addresses, and failure (a trap or
453
+ aborted iteration publishes nothing). The `prefix`, `config`, `recursion` and `allocator` options
454
+ widen the domain the checker handles, and each adds premises that the certificate lists.
455
+
456
+ A refusal carries a `reason` from the closed list `OWNERSHIP_REASONS`, the `obligation` it belongs
457
+ to, a `detail` and, where there is one, an `address`. The reasons are one per obligation
458
+ (`isolation`, `read-before-write`, `aliasing`, `final-state`, `escape`, `failure`), the pointer
459
+ rules of the allocator mode (`ptr-store`, `ptr-return`, `ptr-import`, `ptr-compare`, `ptr-control`,
460
+ `ptr-deref`, `allocator`), `prefix-store`, `prefix-cover`, `config-store`, and four about scope:
461
+ `no-window`, `unsupported`, `budget` and `invalid`. `budget` means the analysis hit its step limit
462
+ (4,000,000 by default) and says nothing about the program. Any refusal says what the checker could
463
+ not establish, and the function runs serially or on another route. On the 10 development drivers
464
+ that fail the plain slice pool, 6 certify.
465
+
466
+ `verifyOwnership(bytes, certificate)` re-derives the certificate from the module and compares
467
+ everything except the work counters. A certificate names the module digest and the checker version
468
+ (`OWNERSHIP_CHECKER`).
469
+
470
+ Two routes run a certified driver. `ownershipSlices` from `@gmitch215/folio/ownership-slices`
471
+ redirects every window access to a private copy per worker and runs the records in place on the
472
+ slice pool. A trap in any slice puts `writes` back and runs the calls serially in place, so the
473
+ serial run decides the memory and the trap. `ownershipSlices` throws `OwnershipSlicesError` with
474
+ code `wild-store` for a certificate that records stores no record owns. `run` throws it with code
475
+ `layout` when a record region overlaps a window, and with `config` when the memory differs from a
476
+ configuration the certificate assumed. `redirectOwnership` and `ownershipRoute` from
477
+ `@gmitch215/folio/ownership-redirect` make the same rewrite and hand it to the iteration pool,
478
+ which tracks every access and paid less on the module measured.
479
+
480
+ ```ts
481
+ import { certifyOwnership, verifyOwnership } from '@gmitch215/folio/ownership';
482
+ import { ownershipSlices } from '@gmitch215/folio/ownership-slices';
483
+
484
+ const certificate = certifyOwnership(bytes, { entry: 'bulk' });
485
+ if (certificate.kind === 'refusal') {
486
+ throw new Error(`${certificate.reason} (${certificate.obligation}): ${certificate.detail}`);
487
+ }
488
+ if (!verifyOwnership(bytes, certificate)) throw new Error('the certificate does not re-derive');
489
+
490
+ const memory = new WebAssembly.Memory({ initial: 8, maximum: 40, shared: true });
491
+ const pool = await ownershipSlices(bytes, certificate, { memory, workers: 4 });
492
+ try {
493
+ // write the record table, the inputs and the output area into pool.memory here
494
+ const report = await pool.run(
495
+ count,
496
+ (from, to) => [table + 16 * from, to - from, out + 64 * from],
497
+ {
498
+ regions: [
499
+ [table, table + 16 * count],
500
+ [input, input + inputBytes],
501
+ [out, out + 64 * count]
502
+ ],
503
+ writes: [[out, out + 64 * count]]
504
+ }
505
+ );
506
+ console.log(report.ownership?.replayed);
507
+ } finally {
508
+ await pool.close();
509
+ }
510
+ ```
511
+
512
+ A certificate rests on premises that the checker does not prove, and a run that breaks one can
513
+ return a different result than the serial program:
514
+
515
+ - The record regions (table, output slots, inputs, auxiliary data, arena slices and stack slots)
516
+ do not overlap a window. `OwnershipSlices.run` checks the `regions` and `writes` the caller
517
+ passes, so they must be complete.
518
+ - Record-derived pointers stay inside their regions. The library does not check this one.
519
+ - The entry branches on its loop counters and the record count only to end or repeat its loop.
520
+ - A trap discards the private copies and the serial path decides what happens next.
521
+ - The start function and the host leave the window bytes the private copies start from.
522
+ - The stack pointer discipline and the stack residue are not proved.
523
+
524
+ The `allocator`, `prefix` and `config` modes add their own premises, which the certificate lists in
525
+ `allocator.assumptions`, `prefix.rules` and `config.rules`. The checker has produced false
526
+ certificates. A red team round found three classes of them that earlier mutation testing had not
527
+ found, and the fixes are part of this release. Red team round 3 found four more classes before the
528
+ checker was frozen, and those are closed too. On the frozen checker, the adversary families and two
529
+ generators of 20,000 modules each found no module whose certificate was wrong. The adversary
530
+ families accept the same number of modules as before the fixes, so they do not exercise the new
531
+ refusals, and the generators have blind spots. The premises above still apply.
532
+
533
+ ## ๐Ÿšฆ Router
534
+
535
+ `@gmitch215/folio/router` picks one route for a call from the module bytes and a description of
536
+ the call, runs it and says why. A call is `{ kind: 'stream', entry, ptr, len }` for one function
537
+ `entry(state, ptr, len)` over a byte stream, or `{ kind: 'records', entry, count, args, regions,
538
+ writes }` for a loop of independent calls, where `args(from, to)` returns the arguments of a slice.
539
+ `Router.open(bytes, call, options)` decides and builds the memory and pools its route needs, and
540
+ `router.run()` executes the call. `decide(bytes, call, options)` returns the decision without
541
+ running anything. A parallel route over a records call needs a module that imports its memory,
542
+ which the router allocates shared.
543
+
544
+ The order is fixed. A stream takes the certified summary when `certifyStream` returns a
545
+ certificate. A loop of records takes the certified window when the ownership certificate exists,
546
+ records no wild stores and the regions clear its windows, then the explicit runner in
547
+ `options.explicit` if the caller supplied one, then tracked speculation, then serial. Tracked
548
+ speculation runs only after an ownership refusal for allocator state or a missing window, and only
549
+ when `assume` states that imports are deterministic (or absent) and that nothing reads the stack
550
+ zone afterwards. `mode` limits the routes: `router` is the whole chain, `serial` never leaves the
551
+ owner, `w1` is the summary only and `w2` the window only, and `independent` and `shared` try the
552
+ summary and then the window, with the module analyses made independently or shared. The last
553
+ four are the arms of the development ablation.
554
+
555
+ Certificates and refusals go into a `CertificateCache`, keyed by the module's SHA-256 and by the
556
+ backend, the checker versions, `ROUTER_VERSION` (`folio-router-2`) and the options that change a
557
+ certificate. A refused module costs a map lookup after the first call, and `serialize()` and
558
+ `load()` move the cache between processes. A route has a floor: the window route stays serial below
559
+ 0.8 ms of remaining serial work and the summary route below 1 MiB, both in `routerConstants`, and
560
+ the tracked and explicit routes use the admission floor of the iteration route. The router runs the
561
+ first records of a call serially to estimate that time, and it stops dispatching after two losing
562
+ dispatches in a row. The constants were fitted on development data, so a result on the development
563
+ drivers describes the fit, and the figure on the frozen final corpus is in Measured Results.
564
+
565
+ ```ts
566
+ import { Router } from '@gmitch215/folio/router';
567
+
568
+ const router = await Router.open(
569
+ bytes,
570
+ {
571
+ kind: 'records',
572
+ entry: 'bulk',
573
+ count,
574
+ args: (from, to) => [table + 16 * from, to - from, out + 64 * from],
575
+ regions: [
576
+ [table, table + 16 * count],
577
+ [input, input + inputBytes],
578
+ [out, out + 64 * count]
579
+ ],
580
+ writes: [[out, out + 64 * count]]
581
+ },
582
+ { mode: 'router', pages: 8, maxPages: 40, workers: 4 }
583
+ );
584
+ try {
585
+ console.log(router.decision.route, router.decision.reason, router.decision.detail);
586
+ for (const step of router.decision.considered) {
587
+ console.log(step.route, step.verdict, step.reason);
588
+ }
589
+ // write the record table, the inputs and the output area into router.memory here
590
+ const run = await router.run();
591
+ console.log(run.route, run.reason, run.wallMs);
592
+ } finally {
593
+ await router.close();
594
+ }
595
+ ```
596
+
597
+ A refusal is a decision with `route: 'serial'` and a `reason` from the closed list
598
+ `ROUTER_REASONS`. The first four reasons are routes taken (`certified-summary`,
599
+ `certified-window`, `explicit-runner`, `tracked-eligible`) and the rest are refusals, such as
600
+ `allocator-state`, `shared-state`, `wild-store`, `layout-overlap`, `assumption-unasserted`,
601
+ `memory-not-imported` and `below-floor`. `decision.considered` lists each route in the order the
602
+ router looked at it, with a `verdict` of `taken`, `refused` or `skipped`, its reason and a `detail`
603
+ that quotes the certifier's refusal. `decision.cacheHit` and `certifyMs` say whether the analysis
604
+ was paid for on this call. The `route` that `run()` returns is the route that executed, which
605
+ differs from the decision when a floor sends the call to the owner (`below-floor`) or the loss rule
606
+ stops a dispatch (`dispatch-lost`).
607
+
265
608
  ## ๐Ÿ”„ Context Checkpoints
266
609
 
267
610
  `@gmitch215/folio/context` resets a private Wasm instance between independent jobs.
@@ -295,6 +638,13 @@ written, and the caller instantiates a new context. Host resources and the objec
295
638
  `externref` values stay with the caller. `restore()` reads every page, so its cost follows the memory
296
639
  size and not the number of changed pages.
297
640
 
641
+ A job that writes its whole input region before it runs can skip that region.
642
+ `restore('changed', ranges)` takes `{ offset, length }` ranges (and a `memory` index when the plan has
643
+ more than one) that it neither compares nor copies back, and `skippedBytes` in the report counts them.
644
+ The caller must write every byte of a range before the program reads it, because those bytes keep the
645
+ previous job's contents. Everything outside the ranges is restored as before, and an invalid range
646
+ throws a `RangeError` before anything changes.
647
+
298
648
  ## ๐ŸงŠ Baked Boot Images
299
649
 
300
650
  `@gmitch215/folio/bake` moves a booted memory into the module. `captureImage(booted, fresh)` compares
@@ -324,8 +674,8 @@ zeros, and pages that are zero in both are left out. Pass the global values and
324
674
  the same instance's table references to `captureImage` as `globals` and `table`; it records what boot
325
675
  changed. `bakeModule` writes changed i32, i64, f32 and f64 globals into their initial values and
326
676
  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).
677
+ has a `code`, for a wrong module digest, a start function, no memory, an image over the memory
678
+ maximum and a global it cannot rewrite. Adjacent pages become one segment of at most `maxSegmentBytes` (64 MiB).
329
679
 
330
680
  `applyImage(memory, image)` copies the pages into a fresh instance's memory without baking. It
331
681
  cannot set a module's globals or table slots, so an image that records changed ones is refused with
@@ -441,14 +791,25 @@ Pool options are `workers` (up to four by default), `memory`, `imports`, `minimu
441
791
  apply when `open` prepares raw bytes), `fuel` (100,000,000), `maxTransactionBytes` (262,144),
442
792
  `promising`, `profile` and `adaptiveRouting`. With `adaptiveRouting`, a call shape (entry, width,
443
793
  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.
794
+ for the next 16 calls and is then probed again. It is off by default. A one-worker pool uses its
795
+ native entry and creates no idle worker.
446
796
 
447
797
  Profiling is opt-in. `report.profile` holds elapsed time, worker observations, validation, commit
448
798
  and replay time, and tracked read and write bytes. On generalized batches `workerWallMs` and
449
799
  `workerCpuMs` hold per-region observations. Measure process CPU once at the coordinator, because
450
800
  summing overlapping process-wide counters double counts.
451
801
 
802
+ Subpaths added in 1.1 for certified and routed execution, with their runtime exports and the types
803
+ that go with them:
804
+
805
+ | Subpath | Exports | Contract |
806
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
807
+ | `affine` | `probeAffine`, `foldAffine`, `foldExact`, `serveAffine`, `affineSerial`, `advance`, `predictEnd`, `AFFINE_TASK`, `gfApply`, `gfMul`, `mask`, `mulberry` | Sampled affine model of a stream function and its chunked fold, with the GF(2) helpers the model uses; `exact` mode validates every boundary |
808
+ | `ownership` | `certifyOwnership`, `verifyOwnership`, `guardRecords`, `checkConfig`, `memoryAccesses`, `OWNERSHIP_REASONS`, `OWNERSHIP_CHECKER` | Window certificate or typed refusal, its re-derivation, and the layout and configuration checks a router runs |
809
+ | `ownership-redirect` | `redirectOwnership`, `ownershipRoute`, `OwnershipRedirectError` | Rewrites a certified module so each window access adds a per-worker delta |
810
+ | `ownership-slices` | `OwnershipSlices`, `ownershipSlices`, `OwnershipSlicesError` | The slice pool over a certified module, with serial replay after a trap |
811
+ | `router` | `Router`, `openRouter`, `decide`, `analyzeModule`, `CertificateCache`, `defaultBackend`, `routerConstants`, `ROUTER_VERSION`, `ROUTER_REASONS` | Route choice per call, certificate cache and the decision record |
812
+
452
813
  The generated API reference is published to GitHub Pages from `bun run docs:build`.
453
814
 
454
815
  ## ๐Ÿงช Consumer Harness
@@ -491,19 +852,28 @@ one queue and aborts if any page differs from the serial render. On ten cores it
491
852
 
492
853
  ## ๐Ÿ“ˆ Measured Results
493
854
 
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 |
855
+ | Backend | Environment | Result |
856
+ | ---------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
857
+ | 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 |
858
+ | Node, compute kernel | eight workers, 207 byte-exact samples | 7.62x, with total CPU 1.037x of serial |
859
+ | 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 |
860
+ | 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 |
861
+ | Browser Run | deployed Chromium, eight workers on one 256 MiB allocation | 3.87x with four workers on explicit partitions |
862
+ | 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 |
863
+ | 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 |
864
+ | 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 |
865
+ | 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 |
866
+ | 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 |
867
+ | 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 |
868
+ | Managed range lanes | deployed Durable Object lanes, 8 MiB arena, 65,536 rounds | 1.98x to 2.00x over serial with `fuel` raised to 1e9 and 0.2% of the snapshot bytes on the wire; 0.84x to 0.90x at the default fuel, where the owner finishes serially |
869
+ | Managed SQLite shards | deployed Durable Object lanes, 1,000,000 rows, 4 and 8 shards, declared merges | 2.0x to 9.7x over one object across five queries, 178 samples equal to the serial result |
870
+ | Record-level corpus | 30 bulk drivers, Ryzen 9 9900X, three sessions of five rounds | default admission wins on 7 drivers (SHA-256 2.01x, MD5 1.46x, SHA-1 1.55x, miniz CRC-32 1.52x, AES-CTR 1.21x, LZ4 compress 1.06x); explicit private contexts win on 26 (1.48x to 3.64x on 25); every output equal to the serial one |
871
+ | Exact chunked recurrences | one 64 MiB stream, eight task workers, Apple M2 Pro | CRC-32 4.25x, Adler-32 5.00x, AES-128-CTR 3.69x with shared input; CRC-32 3.52x with copied chunks; outputs equal to `zlib` and `node:crypto` |
872
+ | Certified stream folds | ten stream subjects, eight task workers, three sessions, Ryzen 9 9900X | 3.4x to 4.1x at 8 MiB and 4.7x to 6.8x at 64 MiB over the serial call (serial median over steady median, median of sessions), process CPU 1.02 to 1.10 of serial at 64 MiB, every result equal to the serial call |
873
+ | Ownership certificate, slice route | frozen final corpus, 47 drivers from 10 projects | window certificate on 1 of 47 drivers (`minimp3-mp3dec_init`), run on the window in 21 of 30 arm64 rounds and 0 of 30 x86_64 rounds; router geomean stays 0.90, gate missed (`router-ablation-final.ts`, rig and Mac) |
874
+ | Router | frozen final corpus, 47 drivers from 10 projects | geomean 0.899 (0.861 to 0.935) on the Ryzen 9 9900X rig and 0.900 (0.858 to 0.941) on the Apple M2 Pro, three sessions each, against 1.20; slowest of the five slowest 0.594 and 0.561 against 0.90; 17,484 rows, 0 wrong; not met |
875
+ | Unmodified external programs | aobench, 6pack with FastLZ and llama2.c at `-O2`, Ryzen 9 9900X, seven rounds | the automatic route stays serial on all three: 1.002 (0.999 to 1.007), 1.002 (0.996 to 1.004) and 1.001 (0.998 to 1.003) over serial Wasm; the 1.20 pass line is not met; 0 wrong outputs in 126 timed samples |
876
+ | Software translation for paging | PHP stock front page render, Ryzen 9 9900X, ten pairs per cell | tau 1.581 (1.537 to 1.617), translated render over native minus one, against a gate of at most 1: not met at default V8 tiering; the objective stays open |
507
877
 
508
878
  A streaming workload stops improving near four workers, and `maximumWorkers` caps the pool per run.
509
879
  Managed Workers cannot share physical memory across isolates, so that backend copies snapshots. The