@gmitch215/folio 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,11 +14,13 @@ the same engine.
14
14
  - [Features](#-features)
15
15
  - [Install](#-install)
16
16
  - [Getting Started](#-getting-started)
17
+ - [Examples](#-examples)
17
18
  - [Asynchronous Host Effects](#-asynchronous-host-effects)
18
19
  - [Execution Host](#-execution-host)
19
20
  - [Managed Workers](#-managed-workers)
20
21
  - [Browser Execution and Page Leases](#-browser-execution-and-page-leases)
21
22
  - [Task Pool](#-task-pool)
23
+ - [Context Checkpoints](#-context-checkpoints)
22
24
  - [Baked Boot Images](#-baked-boot-images)
23
25
  - [Execution and Memory](#-execution-and-memory)
24
26
  - [API Reference](#-api-reference)
@@ -107,9 +109,21 @@ or store, and keeps the region at its owner below `minimumRegionWork` (200,000 b
107
109
  39 microseconds of native work on an Apple M2 Pro). A loop bounded by a constant uses that count, a
108
110
  loop bounded by an untouched parameter or a countdown from one is checked against the arguments at
109
111
  each call, and any other loop is assumed to run `assumedTripCount` times (1,000). A module with no
110
- region above the threshold gets no control plan and runs as the original Wasm, so a small kernel, a
111
- memory-bound loop or a serial recurrence stays at native speed. `minimumRegionWork: 0` admits every
112
- pure region. `folio.diagnostics` says why a plan was refused.
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.
123
+
124
+ ## 🧩 Examples
125
+
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.
113
127
 
114
128
  ## ⏳ Asynchronous Host Effects
115
129
 
@@ -170,7 +184,11 @@ whose `execute(frame)` returns a binary response, and `FolioLane` runs the track
170
184
  The original JSPI coordinator keeps control flow and host effects, and copied snapshots with
171
185
  ordered byte validation connect independent lanes. A transport failure falls back to native owner
172
186
  execution. Snapshot, frame, fuel and tracking bounds are configurable, and the canonical memory
173
- must fit the owner runtime. See [the managed procedure](experiments/managed/METHOD.md).
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).
174
192
 
175
193
  ## 🔗 Browser Execution and Page Leases
176
194
 
@@ -244,6 +262,39 @@ tasks ran at the same time.
244
262
  The pool does not discover independent work. Region discovery and ordered validation stay in the
245
263
  core engine, and the task pool covers programs that can say which calls are independent.
246
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
+
247
298
  ## 🧊 Baked Boot Images
248
299
 
249
300
  `@gmitch215/folio/bake` moves a booted memory into the module. `captureImage(booted, fresh)` compares
@@ -269,11 +320,11 @@ const { instance } = await WebAssembly.instantiate(baked, { env: { memory } });
269
320
  The caller creates an imported memory with at least `memoryPages` pages. A defined memory that
270
321
  starts smaller has its initial pages raised to the image size, and its maximum, shared and memory64
271
322
  flags stay as they are. A page that boot zeroed but the module's own data had set is stored as
272
- zeros, and pages that are zero in both are left out. Pass the global values and the function table
273
- of both instances to `captureImage` as `globals` and `table` and the image records what boot
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
274
325
  changed. `bakeModule` writes changed i32, i64, f32 and f64 globals into their initial values and
275
326
  refuses changed table slots unless `allowTableChanges` is set. It throws `ImageMismatchError`, which
276
- has a `code`, for a wrong module digest, no memory, an image over the memory maximum and a global it
327
+ has a `code`, for a wrong module digest, a start function, no memory, an image over the memory maximum and a global it
277
328
  cannot rewrite. Adjacent pages become one segment of at most `maxSegmentBytes` (64 MiB).
278
329
 
279
330
  `applyImage(memory, image)` copies the pages into a fresh instance's memory without baking. It
@@ -320,7 +371,9 @@ Drupal::service('cache.memory')->deleteAll();
320
371
  mt_srand(unpack('V', random_bytes(4))[1]);
321
372
  ```
322
373
 
323
- Run it before any other PHP in the replayed instance. A host that resets `State` at the start of
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
324
377
  each request still needs the salt and the random seed, and needs the key step for code that runs
325
378
  before the first request. The measured effect for a PHP interpreter is in the Baked Boot Images
326
379
  section of the technical report.
@@ -386,7 +439,9 @@ Run options:
386
439
  Pool options are `workers` (up to four by default), `memory`, `imports`, `minimumParallelWork`
387
440
  (100,000 estimated iterations for proved kernels), `minimumRegionWork` and `assumedTripCount` (both
388
441
  apply when `open` prepares raw bytes), `fuel` (100,000,000), `maxTransactionBytes` (262,144),
389
- `promising` and `profile`. A one-worker pool uses its native entry and creates no idle
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
390
445
  worker.
391
446
 
392
447
  Profiling is opt-in. `report.profile` holds elapsed time, worker observations, validation, commit
@@ -410,7 +465,7 @@ bun scripts/analyze/paired.ts mine tinyimg.jsonl
410
465
  ```
411
466
 
412
467
  `FOLIO_OLD_BUILD=1` adds an `old-N` arm per worker count that runs the archived source from before
413
- static admission (`results/20261020-regress/old-build-src.tar.gz`), alternating with the current
468
+ static admission (`results/execution/admission/old-build-src.tar.gz`), alternating with the current
414
469
  build in the same rounds. The summary then reports `versusOld`, the old build's wall time divided by
415
470
  the current one.
416
471
 
@@ -436,15 +491,19 @@ one queue and aborts if any page differs from the serial render. On ten cores it
436
491
 
437
492
  ## 📈 Measured Results
438
493
 
439
- | Backend | Environment | Result |
440
- | ---------------------------- | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |
441
- | Node, shared allocation | Ryzen 9 9900X, eight pinned workers, 256 MiB arena | 7.52x median elapsed speedup on a normally inlined C entry, 4.87% extra CPU work, every byte exact |
442
- | Node, compute kernel | eight workers, 207 byte-exact samples | 7.62x, with total CPU 1.037x of serial |
443
- | Node, Drupal regeneration | Ryzen 9 9900X, ten private contexts, 31 pages, n=20 | 7.65x median over one context, 1.087x process CPU, every page equal to the serial render |
444
- | Managed Workers | deployed Durable Object lanes | 39 of 39 rows exact over RPC, fetch, streams and WebSockets; 1.62x end to end at four lanes |
445
- | Browser Run | deployed Chromium, eight workers on one 256 MiB allocation | 3.87x with four workers on explicit partitions |
446
- | Browser automatic extraction | FREE account, no JSPI, one ordinary counted-loop call over 256 MiB | 3.45x at eight workers, all memory and returns exact; n=3 exploratory wall time |
447
- | Baked boot image | PHP 8.5.12 Drupal host in a Durable Object, assets, n=4 per arm | first request 72.9% less cpuTime and 52.4% less wall; serve after a drop 43.9% less cpuTime |
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 |
448
507
 
449
508
  A streaming workload stops improving near four workers, and `maximumWorkers` caps the pool per run.
450
509
  Managed Workers cannot share physical memory across isolates, so that backend copies snapshots. The
package/dist/bake.d.ts CHANGED
@@ -40,7 +40,11 @@ export interface CaptureOptions {
40
40
  context?: string;
41
41
  /** Global values read from the booted and the fresh instance, by wasm global index. */
42
42
  globals?: BootedAndFresh<Record<number, GlobalValue>>;
43
- /** The `__indirect_function_table` of the booted and the fresh instance. */
43
+ /**
44
+ * Table after boot and a table holding the pre-boot function references. Copy the references
45
+ * before boot; functions from separately instantiated modules have distinct identities and are
46
+ * conservatively reported as changed. Function names cannot establish identity.
47
+ */
44
48
  table?: BootedAndFresh<WebAssembly.Table>;
45
49
  }
46
50
  /** The result of `imagePages`. */
@@ -86,7 +90,7 @@ export interface BakedCheck {
86
90
  * several `memories`, an image over the memory `maximum`, or a `global` or `table` change the
87
91
  * operation cannot write.
88
92
  */
89
- export type ImageMismatchCode = 'digest' | 'context' | 'no-memory' | 'memories' | 'maximum' | 'global' | 'table';
93
+ export type ImageMismatchCode = 'digest' | 'context' | 'no-memory' | 'memories' | 'maximum' | 'global' | 'table' | 'start';
90
94
  /** The image cannot be baked into this module. */
91
95
  export declare class ImageMismatchError extends Error {
92
96
  /** The reason, for a caller that handles one mismatch differently from another. */
@@ -169,6 +173,7 @@ export declare function findInImage(image: MemoryImage, needles: Uint8Array[]):
169
173
  *
170
174
  * Throws `ImageMismatchError` for a wrong module digest (taken over `bytes` as passed), a module
171
175
  * with no memory or with more than one, an image over the memory maximum, a global that cannot be rewritten and changed
172
- * table slots (unless `allowTableChanges`).
176
+ * table slots (unless `allowTableChanges`). A start function is refused because it would run
177
+ * again over the captured state.
173
178
  */
174
179
  export declare function bakeModule(bytes: Uint8Array, image: MemoryImage, options?: BakeOptions): Promise<Uint8Array>;
package/dist/bake.js CHANGED
@@ -135,7 +135,7 @@ export function captureImage(booted, fresh, options = {}) {
135
135
  for (let slot = 0; slot < Math.max(now.length, then.length); slot++) {
136
136
  const a = slot < now.length ? now.get(slot) : null;
137
137
  const b = slot < then.length ? then.get(slot) : null;
138
- if ((a?.name ?? null) !== (b?.name ?? null))
138
+ if (a !== b)
139
139
  slots.push(slot);
140
140
  }
141
141
  if (slots.length)
@@ -647,7 +647,8 @@ function setGlobal(binaryen, mod, index, value) {
647
647
  *
648
648
  * Throws `ImageMismatchError` for a wrong module digest (taken over `bytes` as passed), a module
649
649
  * with no memory or with more than one, an image over the memory maximum, a global that cannot be rewritten and changed
650
- * table slots (unless `allowTableChanges`).
650
+ * table slots (unless `allowTableChanges`). A start function is refused because it would run
651
+ * again over the captured state.
651
652
  */
652
653
  export async function bakeModule(bytes, image, options = {}) {
653
654
  assertImage(image);
@@ -674,6 +675,8 @@ export async function bakeModule(bytes, image, options = {}) {
674
675
  const binaryen = (await import('binaryen')).default;
675
676
  const mod = binaryen.readBinary(located.raise(pages));
676
677
  try {
678
+ if (mod.getStart())
679
+ throw new ImageMismatchError('start', 'module start would run again after image restoration');
677
680
  for (const [key, value] of Object.entries(image.globals ?? {}))
678
681
  setGlobal(binaryen, mod, Number(key), value);
679
682
  const memory = memoryName(bytes, zero.imported);
@@ -1,5 +1,28 @@
1
- import type { AdmissionOptions, ControlPlan } from './extract.ts';
1
+ import type { AdmissionOptions, ControlPlan, IterationRoute, StackRoute } from './extract.ts';
2
2
  import type { NativePlan } from './guards.ts';
3
+ /** Offline exports used to checkpoint a private instance; function bodies remain unchanged. */
4
+ export interface PreparedContext {
5
+ /** The module as passed in. */
6
+ original: Uint8Array;
7
+ /** The module to instantiate: the original plus the added exports, or the original on refusal. */
8
+ bytes: Uint8Array;
9
+ /** Export names of every memory. */
10
+ memories: string[];
11
+ /** Export names of every mutable numeric global. */
12
+ globals: string[];
13
+ /** Export names of every table. */
14
+ tables: string[];
15
+ /** A refusal retains original bytes so the caller can recreate a context instead. */
16
+ reasons: string[];
17
+ }
18
+ /**
19
+ * Exposes Wasm memories, mutable globals and tables for private-context reset. This adds exports
20
+ * only; start functions and code run normally. Unsupported metadata retains the original module.
21
+ * Host effects, passive segment drop state and objects behind references require recreation or
22
+ * a caller-owned reset. Modules using segment drop are refused for checkpoint reuse.
23
+ * @since 1.0.1
24
+ */
25
+ export declare function prepareContext(input: Uint8Array): PreparedContext;
3
26
  /** A counted loop the splitter can divide: the count parameter and the affine pointer steps. */
4
27
  export interface LoopPlan {
5
28
  /** Index of the parameter holding the iteration count. */
@@ -30,6 +53,19 @@ export interface PreparedProgram {
30
53
  control?: ControlPlan;
31
54
  /** Why control-flow extraction produced no plan; the counted-loop plans above are unaffected. */
32
55
  controlReasons?: string[];
56
+ /**
57
+ * The stack-pointer route: the worker-side function set when one mutable i32 global is private
58
+ * and recursion is allowed. It ignores `reasons` and nothing consumes it yet.
59
+ *
60
+ * @internal
61
+ */
62
+ stackRoute?: StackRoute;
63
+ /**
64
+ * One loop of independent calls into the stack route's worker set; inert like `stackRoute`.
65
+ *
66
+ * @internal
67
+ */
68
+ iterationRoute?: IterationRoute;
33
69
  }
34
70
  /** Plan options: whether to optimize, and when a region is worth dispatching. */
35
71
  export interface PrepareOptions extends AdmissionOptions {
package/dist/compiler.js CHANGED
@@ -1,6 +1,119 @@
1
1
  import binaryen from 'binaryen';
2
- import { admission, extract } from "./extract.js";
2
+ import { admission, extract, iterationRoute, stackRoute } from "./extract.js";
3
3
  import { nativePlan } from "./guards.js";
4
+ /**
5
+ * Exposes Wasm memories, mutable globals and tables for private-context reset. This adds exports
6
+ * only; start functions and code run normally. Unsupported metadata retains the original module.
7
+ * Host effects, passive segment drop state and objects behind references require recreation or
8
+ * a caller-owned reset. Modules using segment drop are refused for checkpoint reuse.
9
+ * @since 1.0.1
10
+ */
11
+ export function prepareContext(input) {
12
+ const original = Uint8Array.from(input), native = new WebAssembly.Module(original);
13
+ const result = {
14
+ original,
15
+ bytes: original,
16
+ memories: [],
17
+ globals: [],
18
+ tables: [],
19
+ reasons: []
20
+ };
21
+ let mod;
22
+ try {
23
+ mod = binaryen.readBinary(original);
24
+ mod.setFeatures(binaryen.Features.All);
25
+ // passive segment and gc state cannot be restored through exported bindings
26
+ const text = mod.emitText();
27
+ if (/\((?:data|elem)\.drop(?:\s|\))/.test(text))
28
+ throw new TypeError('passive segment drop state requires recreation');
29
+ if (/\((?:struct|array)\./.test(text))
30
+ throw new TypeError('Wasm GC object state requires recreation');
31
+ const exports = new Set(WebAssembly.Module.exports(native).map((item) => item.name));
32
+ let prefix = '__folio_context_';
33
+ while ([...exports].some((name) => name.startsWith(prefix)))
34
+ prefix += '_';
35
+ const additions = [];
36
+ const leb = (value) => {
37
+ const out = [];
38
+ do {
39
+ const byte = value & 127;
40
+ value = Math.floor(value / 128);
41
+ out.push(byte | (value ? 128 : 0));
42
+ } while (value);
43
+ return out;
44
+ };
45
+ const add = (kind, index, names, label) => {
46
+ const name = `${prefix}${label}${index}`, encoded = new TextEncoder().encode(name);
47
+ additions.push(...leb(encoded.length), ...encoded, kind, ...leb(index));
48
+ names.push(name);
49
+ };
50
+ let cursor = 8, definedMemories = 0;
51
+ const unsigned = () => {
52
+ let value = 0, shift = 0, byte;
53
+ do {
54
+ byte = original[cursor++];
55
+ value += (byte & 127) * 2 ** shift;
56
+ shift += 7;
57
+ } while (byte & 128);
58
+ return value;
59
+ };
60
+ const sections = [];
61
+ while (cursor < original.length) {
62
+ const start = cursor, kind = original[cursor++], length = unsigned(), payload = cursor, end = cursor + length;
63
+ if (kind === 5)
64
+ definedMemories = unsigned();
65
+ sections.push({ kind, start, payload, end });
66
+ cursor = end;
67
+ }
68
+ const memoryCount = definedMemories +
69
+ WebAssembly.Module.imports(native).filter((item) => item.kind === 'memory').length;
70
+ for (let index = 0; index < memoryCount; index++)
71
+ add(2, index, result.memories, 'memory');
72
+ for (let index = 0; index < mod.getNumGlobals(); index++) {
73
+ const global = binaryen.getGlobalInfo(mod.getGlobalByIndex(index));
74
+ if (![binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64, binaryen.v128].includes(global.type))
75
+ throw new TypeError('reference global state requires recreation');
76
+ if (!global.mutable)
77
+ continue;
78
+ if (global.type === binaryen.v128)
79
+ throw new TypeError('v128 globals require recreation');
80
+ add(3, index, result.globals, 'global');
81
+ }
82
+ for (let index = 0; index < mod.getNumTables(); index++)
83
+ add(1, index, result.tables, 'table');
84
+ const prior = sections.find((section) => section.kind === 7);
85
+ let count = 0, records = new Uint8Array();
86
+ if (prior) {
87
+ cursor = prior.payload;
88
+ count = unsigned();
89
+ records = original.subarray(cursor, prior.end);
90
+ }
91
+ const addedCount = result.memories.length + result.globals.length + result.tables.length;
92
+ const payload = Uint8Array.from([...leb(count + addedCount), ...records, ...additions]);
93
+ const header = Uint8Array.from([7, ...leb(payload.length)]);
94
+ const position = prior?.start ??
95
+ sections.find((section) => [8, 9, 12, 10, 11].includes(section.kind))?.start ??
96
+ original.length;
97
+ const rest = prior?.end ?? position;
98
+ const bytes = new Uint8Array(position + header.length + payload.length + original.length - rest);
99
+ bytes.set(original.subarray(0, position));
100
+ bytes.set(header, position);
101
+ bytes.set(payload, position + header.length);
102
+ bytes.set(original.subarray(rest), position + header.length + payload.length);
103
+ new WebAssembly.Module(bytes);
104
+ result.bytes = bytes;
105
+ }
106
+ catch (error) {
107
+ result.memories = [];
108
+ result.globals = [];
109
+ result.tables = [];
110
+ result.reasons.push(error instanceof Error ? error.message : String(error));
111
+ }
112
+ finally {
113
+ mod?.dispose();
114
+ }
115
+ return result;
116
+ }
4
117
  const info = (expression) => {
5
118
  const id = binaryen.getExpressionId(expression);
6
119
  if (id === binaryen.UnreachableId || id === binaryen.NopId) {
@@ -500,6 +613,8 @@ export function prepare(bytes, options = {}) {
500
613
  catch (error) {
501
614
  prepared.reasons.push(`control-flow extraction unavailable: ${error instanceof Error ? error.message : String(error)}`);
502
615
  }
616
+ prepared.stackRoute = stackRoute(prepared.original, options);
617
+ prepared.iterationRoute = iterationRoute(prepared.original, prepared.stackRoute);
503
618
  }
504
619
  return prepared;
505
620
  }
@@ -0,0 +1,33 @@
1
+ import type { PreparedContext } from './compiler.ts';
2
+ /** A changed memory or table size requires a newly instantiated context. */
3
+ export declare class ContextResetError extends Error {
4
+ /** Which binding changed size. */
5
+ readonly kind: 'memory-size' | 'table-size';
6
+ constructor(kind: 'memory-size' | 'table-size');
7
+ }
8
+ /** Memory traffic and state restored by a checkpoint operation. */
9
+ export interface ContextResetReport {
10
+ /** Bytes compared; zero for a full restore. */
11
+ checkedBytes: number;
12
+ /** Bytes written back to memory. */
13
+ copiedBytes: number;
14
+ /** 64 KiB pages written back. */
15
+ changedPages: number;
16
+ /** Globals whose value was restored. */
17
+ globals: number;
18
+ /** Table slots whose reference was restored. */
19
+ tableSlots: number;
20
+ }
21
+ /**
22
+ * Captures private Wasm state after initialization. `prepareContext` exposes hidden bindings.
23
+ * Each restore checks current bytes, so different inputs may dirty different pages. Callers own
24
+ * exclusive access and reset host resources and objects behind externref values separately.
25
+ * Memory/table growth requires recreation because Wasm cannot shrink those bindings.
26
+ * @since 1.0.1
27
+ */
28
+ export declare class InstanceCheckpoint {
29
+ #private;
30
+ constructor(instance: WebAssembly.Instance, plan: PreparedContext);
31
+ /** Restores all mutable bindings. `full` skips page comparison and copies every memory byte. */
32
+ restore(strategy?: 'changed' | 'full'): ContextResetReport;
33
+ }
@@ -0,0 +1,93 @@
1
+ import { Buffer } from 'node:buffer';
2
+ /** A changed memory or table size requires a newly instantiated context. */
3
+ export class ContextResetError extends Error {
4
+ /** Which binding changed size. */
5
+ kind;
6
+ constructor(kind) {
7
+ super(`context ${kind} changed; instantiate and initialize a new context`);
8
+ this.name = 'ContextResetError';
9
+ this.kind = kind;
10
+ }
11
+ }
12
+ /**
13
+ * Captures private Wasm state after initialization. `prepareContext` exposes hidden bindings.
14
+ * Each restore checks current bytes, so different inputs may dirty different pages. Callers own
15
+ * exclusive access and reset host resources and objects behind externref values separately.
16
+ * Memory/table growth requires recreation because Wasm cannot shrink those bindings.
17
+ * @since 1.0.1
18
+ */
19
+ export class InstanceCheckpoint {
20
+ #memories;
21
+ #globals;
22
+ #tables;
23
+ constructor(instance, plan) {
24
+ if (plan.reasons.length)
25
+ throw new TypeError(`context requires recreation: ${plan.reasons.join('; ')}`);
26
+ this.#memories = plan.memories.map((name) => {
27
+ const memory = instance.exports[name];
28
+ if (!(memory instanceof WebAssembly.Memory))
29
+ throw new TypeError(`missing context memory ${name}`);
30
+ return { memory, bytes: Uint8Array.from(new Uint8Array(memory.buffer)) };
31
+ });
32
+ this.#globals = plan.globals.map((name) => {
33
+ const global = instance.exports[name];
34
+ if (!(global instanceof WebAssembly.Global))
35
+ throw new TypeError(`missing context global ${name}`);
36
+ return { global, value: global.value };
37
+ });
38
+ this.#tables = plan.tables.map((name) => {
39
+ const table = instance.exports[name];
40
+ if (!(table instanceof WebAssembly.Table))
41
+ throw new TypeError(`missing context table ${name}`);
42
+ return {
43
+ table,
44
+ slots: Array.from({ length: table.length }, (_, index) => table.get(index))
45
+ };
46
+ });
47
+ }
48
+ /** Restores all mutable bindings. `full` skips page comparison and copies every memory byte. */
49
+ restore(strategy = 'changed') {
50
+ if (strategy !== 'changed' && strategy !== 'full')
51
+ throw new TypeError('invalid context reset strategy');
52
+ for (const { memory, bytes } of this.#memories)
53
+ if (memory.buffer.byteLength !== bytes.length)
54
+ throw new ContextResetError('memory-size');
55
+ for (const { table, slots } of this.#tables)
56
+ if (table.length !== slots.length)
57
+ throw new ContextResetError('table-size');
58
+ const report = {
59
+ checkedBytes: 0,
60
+ copiedBytes: 0,
61
+ changedPages: 0,
62
+ globals: 0,
63
+ tableSlots: 0
64
+ };
65
+ for (const { memory, bytes } of this.#memories) {
66
+ const target = new Uint8Array(memory.buffer);
67
+ for (let offset = 0; offset < bytes.length; offset += 65536) {
68
+ const source = bytes.subarray(offset, offset + 65536), current = target.subarray(offset, offset + 65536);
69
+ if (strategy === 'changed')
70
+ report.checkedBytes += current.length;
71
+ if (strategy === 'full' ||
72
+ !Buffer.from(current.buffer, current.byteOffset, current.length).equals(Buffer.from(source.buffer, source.byteOffset, source.length))) {
73
+ current.set(source);
74
+ report.copiedBytes += current.length;
75
+ report.changedPages++;
76
+ }
77
+ }
78
+ }
79
+ for (const { global, value } of this.#globals) {
80
+ if (!Object.is(global.value, value)) {
81
+ global.value = value;
82
+ report.globals++;
83
+ }
84
+ }
85
+ for (const { table, slots } of this.#tables)
86
+ for (let index = 0; index < slots.length; index++)
87
+ if (!Object.is(table.get(index), slots[index])) {
88
+ table.set(index, slots[index]);
89
+ report.tableSlots++;
90
+ }
91
+ return report;
92
+ }
93
+ }
@@ -17,7 +17,7 @@ export declare class Coordinator {
17
17
  pending?: {
18
18
  value: unknown;
19
19
  };
20
- dispatch: (worker: number, calls: RegionCall[]) => Promise<TransactionResult[]>;
20
+ dispatch: (worker: number, calls: RegionCall[], generation: number) => Promise<TransactionResult[]>;
21
21
  native: (call: RegionCall) => void;
22
22
  });
23
23
  enqueue(call: RegionCall): Promise<void> | undefined;
@@ -20,6 +20,7 @@ export class Coordinator {
20
20
  #pending;
21
21
  #armed = false;
22
22
  #polls = 0;
23
+ #generation = 0;
23
24
  #flushing;
24
25
  constructor(options) {
25
26
  this.#pending = options.pending;
@@ -127,7 +128,8 @@ export class Coordinator {
127
128
  const width = Math.min(this.#width, batch.length);
128
129
  this.report.workers = Math.max(this.report.workers, width);
129
130
  const lanes = Array.from({ length: width }, (_, lane) => batch.filter((_, index) => index % width === lane));
130
- const outcomes = await Promise.allSettled(lanes.map((calls, i) => this.#dispatch(i, calls)));
131
+ const generation = ++this.#generation;
132
+ const outcomes = await Promise.allSettled(lanes.map((calls, i) => this.#dispatch(i, calls, generation)));
131
133
  const failure = outcomes.find((outcome) => outcome.status === 'rejected');
132
134
  if (failure?.status === 'rejected')
133
135
  throw failure.reason;
@@ -170,7 +172,7 @@ export class Coordinator {
170
172
  }
171
173
  if (!result.exhausted) {
172
174
  const replayStart = this.#profile ? performance.now() : 0;
173
- result = (await this.#dispatch(0, [batch[i]]))[0];
175
+ result = (await this.#dispatch(0, [batch[i]], ++this.#generation))[0];
174
176
  observe(result);
175
177
  if (this.#profile)
176
178
  this.#profile.replayMs += performance.now() - replayStart;