@gmitch215/folio 0.0.0-stage → 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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +541 -2
  3. package/dist/bake.d.ts +179 -0
  4. package/dist/bake.js +704 -0
  5. package/dist/browser-worker.d.ts +9 -0
  6. package/dist/browser-worker.js +37 -0
  7. package/dist/browser.d.ts +68 -0
  8. package/dist/browser.js +274 -0
  9. package/dist/compiler.d.ts +79 -0
  10. package/dist/compiler.js +620 -0
  11. package/dist/context.d.ts +33 -0
  12. package/dist/context.js +93 -0
  13. package/dist/coordinator.d.ts +27 -0
  14. package/dist/coordinator.js +191 -0
  15. package/dist/extract.d.ts +165 -0
  16. package/dist/extract.js +1817 -0
  17. package/dist/frames.d.ts +33 -0
  18. package/dist/frames.js +159 -0
  19. package/dist/guards.d.ts +12 -0
  20. package/dist/guards.js +202 -0
  21. package/dist/host.d.ts +60 -0
  22. package/dist/host.js +374 -0
  23. package/dist/import-order.d.ts +2 -0
  24. package/dist/import-order.js +114 -0
  25. package/dist/index.d.ts +4 -0
  26. package/dist/index.js +2 -0
  27. package/dist/inline.d.ts +68 -0
  28. package/dist/inline.js +503 -0
  29. package/dist/iteration-admission.d.ts +76 -0
  30. package/dist/iteration-admission.js +72 -0
  31. package/dist/iteration-layout.d.ts +75 -0
  32. package/dist/iteration-layout.js +118 -0
  33. package/dist/iteration-owner.d.ts +32 -0
  34. package/dist/iteration-owner.js +223 -0
  35. package/dist/iteration-worker.d.ts +1 -0
  36. package/dist/iteration-worker.js +150 -0
  37. package/dist/iteration.d.ts +163 -0
  38. package/dist/iteration.js +435 -0
  39. package/dist/managed.d.ts +92 -0
  40. package/dist/managed.js +421 -0
  41. package/dist/memory.d.ts +10 -0
  42. package/dist/memory.js +89 -0
  43. package/dist/node.d.ts +138 -0
  44. package/dist/node.js +1153 -0
  45. package/dist/pages.d.ts +109 -0
  46. package/dist/pages.js +339 -0
  47. package/dist/remote.d.ts +86 -0
  48. package/dist/remote.js +255 -0
  49. package/dist/tasks.d.ts +107 -0
  50. package/dist/tasks.js +330 -0
  51. package/dist/transaction.d.ts +23 -0
  52. package/dist/transaction.js +93 -0
  53. package/dist/values.d.ts +3 -0
  54. package/dist/values.js +25 -0
  55. package/dist/worker.d.ts +1 -0
  56. package/dist/worker.js +86 -0
  57. package/package.json +130 -5
@@ -0,0 +1,75 @@
1
+ import type { IterationLocal } from './extract.ts';
2
+ /** Granule sizes of the inline lowering the iteration executor runs. */
3
+ export declare const iterationGranules: {
4
+ readonly read: 64;
5
+ readonly write: 32;
6
+ };
7
+ /** Bytes of one undo entry: granule address, stamp, then the prior bytes of the granule. */
8
+ export declare const iterationEntryBytes: number;
9
+ /** Sizes of the per-batch arena. Every field has a default. */
10
+ export interface IterationArenaOptions {
11
+ /** Iterations in flight at once, one slot, bitmap pair and undo log each. Default 32. */
12
+ batch?: number;
13
+ /** Undo entries one iteration may log, the budget in write granules. Default 2048. */
14
+ logCapacity?: number;
15
+ /** Bytes of one private stack slot, a multiple of 64. Default 32768. */
16
+ slotBytes?: number;
17
+ /** Size of the owner frame whose reads the executor tracks, for the per-slot shadow. Default 0. */
18
+ frameBytes?: number;
19
+ }
20
+ /** Absolute addresses of the arena parts. Slot 0 sits above one unused guard slot. */
21
+ export interface IterationArena {
22
+ base: number;
23
+ bytes: number;
24
+ memoryBytes: number;
25
+ batch: number;
26
+ logCapacity: number;
27
+ slotBytes: number;
28
+ slots: number;
29
+ stamp: number;
30
+ logs: number;
31
+ logBytes: number;
32
+ rmaps: number;
33
+ rsize: number;
34
+ wmaps: number;
35
+ wsize: number;
36
+ /** Start of the frame shadows, one per slot, after the write bitmaps. */
37
+ frameShadow: number;
38
+ /** Bytes of one slot's frame shadow; 0 without a tracked frame. */
39
+ frameSlotBytes: number;
40
+ /** The tracked frame size. */
41
+ frameBytes: number;
42
+ }
43
+ /**
44
+ * Shadow of one tracked frame: `4 * ceil(size / 32)` bytes of written bits, one per frame byte
45
+ * (the bits of frame granule `g`, 32 bytes, are the i32 at `4 * g`), 4 pad bytes, the exposed bits
46
+ * in the same layout, and 4 pad bytes.
47
+ */
48
+ export declare function iterationFrameShadow(frameBytes: number): {
49
+ exposed: number;
50
+ bytes: number;
51
+ };
52
+ /**
53
+ * Lays out slots, the stamp word, undo logs and bitmaps from `base`. The bitmaps cover the whole
54
+ * memory, arena included, so `bytes` depends on `memoryBytes` and not on `base`.
55
+ */
56
+ export declare function iterationArena(base: number, memoryBytes: number, options?: IterationArenaOptions): IterationArena;
57
+ /** Bytes the caller must keep free for a pool over a memory of `memoryBytes`. */
58
+ export declare const iterationArenaBytes: (memoryBytes: number, options?: IterationArenaOptions) => number;
59
+ /**
60
+ * Smallest memory of whole pages that holds the arena above `startBytes`. The bitmaps cover the
61
+ * whole memory, so the size is a fixed point: it grows until the arena it needs fits. Undefined
62
+ * when the result would pass 65,536 pages.
63
+ */
64
+ export declare function iterationFit(startBytes: number, options?: IterationArenaOptions): {
65
+ base: number;
66
+ pages: number;
67
+ bytes: number;
68
+ memoryBytes: number;
69
+ } | undefined;
70
+ /**
71
+ * Arguments of `iterate` for iteration `k`. A strided local is `entry + k * stride` modulo 2^32, or
72
+ * `entry + k * stride * entry[strideLocal]` when its step is held in a local, an invariant local
73
+ * keeps its entry value, and the frame local takes `frame`.
74
+ */
75
+ export declare function iterationArguments(locals: readonly Pick<IterationLocal, 'local' | 'kind' | 'argument' | 'stride' | 'strideLocal'>[], entry: Readonly<Record<number, number | bigint>>, k: number, frame: number): (number | bigint)[];
@@ -0,0 +1,118 @@
1
+ /** Granule sizes of the inline lowering the iteration executor runs. */
2
+ export const iterationGranules = { read: 64, write: 32 };
3
+ /** Bytes of one undo entry: granule address, stamp, then the prior bytes of the granule. */
4
+ export const iterationEntryBytes = 8 + iterationGranules.write;
5
+ const align = (value, to) => Math.ceil(value / to) * to;
6
+ /**
7
+ * Shadow of one tracked frame: `4 * ceil(size / 32)` bytes of written bits, one per frame byte
8
+ * (the bits of frame granule `g`, 32 bytes, are the i32 at `4 * g`), 4 pad bytes, the exposed bits
9
+ * in the same layout, and 4 pad bytes.
10
+ */
11
+ export function iterationFrameShadow(frameBytes) {
12
+ if (!frameBytes)
13
+ return { exposed: 0, bytes: 0 };
14
+ const granules = Math.ceil(frameBytes / 32);
15
+ const exposed = 4 * granules + 4;
16
+ return { exposed, bytes: align(exposed + 4 * granules + 4, 64) };
17
+ }
18
+ /**
19
+ * Lays out slots, the stamp word, undo logs and bitmaps from `base`. The bitmaps cover the whole
20
+ * memory, arena included, so `bytes` depends on `memoryBytes` and not on `base`.
21
+ */
22
+ export function iterationArena(base, memoryBytes, options = {}) {
23
+ const batch = options.batch ?? 32;
24
+ const logCapacity = options.logCapacity ?? 2048;
25
+ const slotBytes = options.slotBytes ?? 32768;
26
+ const frameBytes = options.frameBytes ?? 0;
27
+ if (!Number.isSafeInteger(frameBytes) || frameBytes < 0)
28
+ throw new RangeError('invalid frame');
29
+ if (!Number.isSafeInteger(base) || base < 0 || base % 64)
30
+ throw new RangeError('invalid base');
31
+ if (!Number.isSafeInteger(memoryBytes) || memoryBytes <= 0)
32
+ throw new RangeError('invalid memory size');
33
+ if (!Number.isSafeInteger(batch) || batch < 1 || batch > 1024)
34
+ throw new RangeError('invalid batch');
35
+ if (!Number.isSafeInteger(logCapacity) || logCapacity < 1)
36
+ throw new RangeError('invalid log capacity');
37
+ if (!Number.isSafeInteger(slotBytes) || slotBytes < 64 || slotBytes % 64)
38
+ throw new RangeError('invalid slot size');
39
+ const slots = base + slotBytes;
40
+ const stamp = slots + batch * slotBytes;
41
+ const logs = stamp + 64;
42
+ const logBytes = align(logCapacity * iterationEntryBytes, 64);
43
+ const rmaps = logs + batch * logBytes;
44
+ const rsize = align(Math.ceil(memoryBytes / (iterationGranules.read * 8)), 64);
45
+ const wmaps = rmaps + batch * rsize;
46
+ const wsize = align(Math.ceil(memoryBytes / (iterationGranules.write * 8)), 64);
47
+ const frameShadow = wmaps + batch * wsize;
48
+ const frameSlotBytes = iterationFrameShadow(frameBytes).bytes;
49
+ const end = frameShadow + batch * frameSlotBytes;
50
+ return {
51
+ base,
52
+ bytes: end - base,
53
+ memoryBytes,
54
+ batch,
55
+ logCapacity,
56
+ slotBytes,
57
+ slots,
58
+ stamp,
59
+ logs,
60
+ logBytes,
61
+ rmaps,
62
+ rsize,
63
+ wmaps,
64
+ wsize,
65
+ frameShadow,
66
+ frameSlotBytes,
67
+ frameBytes
68
+ };
69
+ }
70
+ /** Bytes the caller must keep free for a pool over a memory of `memoryBytes`. */
71
+ export const iterationArenaBytes = (memoryBytes, options = {}) => iterationArena(0, memoryBytes, options).bytes;
72
+ const PAGE = 65536;
73
+ /**
74
+ * Smallest memory of whole pages that holds the arena above `startBytes`. The bitmaps cover the
75
+ * whole memory, so the size is a fixed point: it grows until the arena it needs fits. Undefined
76
+ * when the result would pass 65,536 pages.
77
+ */
78
+ export function iterationFit(startBytes, options = {}) {
79
+ const base = align(startBytes, 64);
80
+ let pages = Math.ceil((base + PAGE) / PAGE);
81
+ for (;;) {
82
+ if (pages > PAGE)
83
+ return;
84
+ const bytes = iterationArenaBytes(pages * PAGE, options);
85
+ if (base + bytes <= pages * PAGE)
86
+ return { base, pages, bytes, memoryBytes: pages * PAGE };
87
+ pages = Math.ceil((base + bytes) / PAGE);
88
+ }
89
+ }
90
+ /**
91
+ * Arguments of `iterate` for iteration `k`. A strided local is `entry + k * stride` modulo 2^32, or
92
+ * `entry + k * stride * entry[strideLocal]` when its step is held in a local, an invariant local
93
+ * keeps its entry value, and the frame local takes `frame`.
94
+ */
95
+ export function iterationArguments(locals, entry, k, frame) {
96
+ const values = [];
97
+ for (const item of locals) {
98
+ if (item.argument === undefined)
99
+ continue;
100
+ if (item.kind === 'frame') {
101
+ values[item.argument] = frame;
102
+ continue;
103
+ }
104
+ const from = entry[item.local];
105
+ if (from === undefined)
106
+ throw new RangeError(`no loop-entry value for local ${item.local}`);
107
+ if (item.strideLocal !== undefined) {
108
+ const step = entry[item.strideLocal];
109
+ if (step === undefined)
110
+ throw new RangeError(`no loop-entry value for local ${item.strideLocal}`);
111
+ const advance = Math.imul(k, Number(step));
112
+ values[item.argument] = (Number(from) + (item.stride < 0 ? -advance : advance)) | 0;
113
+ }
114
+ else
115
+ values[item.argument] = item.stride ? (Number(from) + k * item.stride) | 0 : from;
116
+ }
117
+ return values;
118
+ }
@@ -0,0 +1,32 @@
1
+ import type { IterationRoute } from './extract.ts';
2
+ /** Why the iteration route is not used, in `ExecutionReport.reason`. */
3
+ export type IterationReason = 'no-arena' | 'memory-size-observed' | 'import-order' | 'workers-unavailable' | 'trip-zero' | 'no-admission' | 'log-exhausted' | 'frame-carried dependence';
4
+ /** The owner module with its loop handed to `iterate`, and what the host needs to bind it. */
5
+ export interface IterationOwner {
6
+ module: Uint8Array;
7
+ /** import module of the host function; the function is `iterate` */
8
+ namespace: string;
9
+ /** the owner local passed as each argument of `iterate`, in order */
10
+ locals: number[];
11
+ /** export of the owner's stack global, when the module has one */
12
+ stackExport?: string;
13
+ /** the memory import, as declared by the original module */
14
+ memory: {
15
+ module: string;
16
+ name: string;
17
+ initial: number;
18
+ maximum?: number;
19
+ };
20
+ }
21
+ /**
22
+ * Builds the owner module of an iteration route: the memory import is shared, and the one loop
23
+ * of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.
24
+ * The host function returns 1 after it ran every iteration and 0 to leave the original loop to
25
+ * run in the owner. A refusal names its reason and never throws.
26
+ */
27
+ export declare function iterationOwner(original: Uint8Array, route: IterationRoute, stack?: string): {
28
+ owner: IterationOwner;
29
+ } | {
30
+ reason: IterationReason;
31
+ detail: string;
32
+ };
@@ -0,0 +1,223 @@
1
+ import binaryen from 'binaryen';
2
+ import { restoreImportOrder } from "./import-order.js";
3
+ const PAGE_LIMIT = 65536;
4
+ function uleb(value) {
5
+ const out = [];
6
+ do {
7
+ let byte = value % 128;
8
+ value = Math.floor(value / 128);
9
+ if (value)
10
+ byte |= 128;
11
+ out.push(byte);
12
+ } while (value);
13
+ return out;
14
+ }
15
+ /** Reads the one imported memory's limits from the import section. */
16
+ function importedMemory(bytes) {
17
+ let at = 8;
18
+ const uint = () => {
19
+ let value = 0, shift = 0, byte;
20
+ do {
21
+ byte = bytes[at++];
22
+ value += (byte & 127) * 2 ** shift;
23
+ shift += 7;
24
+ } while (byte & 128);
25
+ return value;
26
+ };
27
+ const name = () => {
28
+ const length = uint();
29
+ const text = new TextDecoder().decode(bytes.subarray(at, at + length));
30
+ at += length;
31
+ return text;
32
+ };
33
+ const reference = () => {
34
+ const type = bytes[at++];
35
+ if (type === 0x63 || type === 0x64)
36
+ uint();
37
+ };
38
+ while (at < bytes.length) {
39
+ const header = at;
40
+ const id = bytes[at++];
41
+ const length = uint();
42
+ const sectionEnd = at + length;
43
+ const sectionStart = at;
44
+ if (id !== 2) {
45
+ at = sectionEnd;
46
+ continue;
47
+ }
48
+ const count = uint();
49
+ const found = [];
50
+ for (let i = 0; i < count; i++) {
51
+ const module = name();
52
+ const base = name();
53
+ const kind = bytes[at++];
54
+ if (kind === 0)
55
+ uint();
56
+ else if (kind === 1) {
57
+ reference();
58
+ const flags = uint();
59
+ uint();
60
+ if (flags & 1)
61
+ uint();
62
+ }
63
+ else if (kind === 2) {
64
+ const from = at;
65
+ const flags = uint();
66
+ const initial = uint();
67
+ const maximum = flags & 1 ? uint() : undefined;
68
+ found.push({
69
+ module,
70
+ name: base,
71
+ flags,
72
+ initial,
73
+ maximum,
74
+ limits: [from, at],
75
+ header,
76
+ body: [sectionStart, sectionEnd]
77
+ });
78
+ }
79
+ else if (kind === 3) {
80
+ reference();
81
+ at++;
82
+ }
83
+ else if (kind === 4) {
84
+ at++;
85
+ uint();
86
+ }
87
+ else
88
+ throw new TypeError('unsupported import descriptor');
89
+ }
90
+ return found;
91
+ }
92
+ return [];
93
+ }
94
+ /** Rewrites the memory import limits to shared with the largest maximum. */
95
+ function shareMemory(bytes, memory) {
96
+ const { limits, header, body } = memory;
97
+ const content = [
98
+ ...bytes.subarray(body[0], limits[0]),
99
+ 3,
100
+ ...uleb(memory.initial),
101
+ ...uleb(PAGE_LIMIT),
102
+ ...bytes.subarray(limits[1], body[1])
103
+ ];
104
+ return Uint8Array.from([
105
+ ...bytes.subarray(0, header),
106
+ 2,
107
+ ...uleb(content.length),
108
+ ...content,
109
+ ...bytes.subarray(body[1])
110
+ ]);
111
+ }
112
+ const refusal = (reason, detail) => ({ reason, detail });
113
+ /**
114
+ * Builds the owner module of an iteration route: the memory import is shared, and the one loop
115
+ * of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.
116
+ * The host function returns 1 after it ran every iteration and 0 to leave the original loop to
117
+ * run in the owner. A refusal names its reason and never throws.
118
+ */
119
+ export function iterationOwner(original, route, stack) {
120
+ let module;
121
+ try {
122
+ if (!route.eligible || !route.owner || !route.trip)
123
+ return refusal('no-arena', 'route is not eligible');
124
+ const memories = importedMemory(original);
125
+ if (memories.length !== 1)
126
+ return refusal('no-arena', 'iteration needs exactly one imported memory');
127
+ const declared = memories[0];
128
+ if (declared.flags & ~3)
129
+ return refusal('no-arena', 'wasm64 or unsupported memory limits');
130
+ const shared = shareMemory(original, declared);
131
+ module = binaryen.readBinary(shared);
132
+ const compactImports = binaryen.Features
133
+ .CompactImports;
134
+ module.setFeatures(binaryen.Features.All & ~compactImports);
135
+ const m = module;
136
+ if (m.getMemoryInfo().is64)
137
+ return refusal('no-arena', 'wasm64 memory');
138
+ if (/\bmemory\.(size|grow)\b/.test(m.emitText()))
139
+ return refusal('memory-size-observed', 'the module executes memory.size or memory.grow, which would observe the arena');
140
+ const owner = m.getFunction(route.owner);
141
+ if (!owner)
142
+ return refusal('no-arena', `owner ${route.owner} not found`);
143
+ const f = binaryen.getFunctionInfo(owner);
144
+ const types = [...binaryen.expandType(f.params), ...f.vars];
145
+ const id = (e) => binaryen.getExpressionId(e);
146
+ const locate = (e) => {
147
+ if (id(e) === binaryen.LoopId)
148
+ return { index: -1, loop: e };
149
+ if (id(e) !== binaryen.BlockId)
150
+ return;
151
+ const kids = binaryen.getExpressionInfo(e).children;
152
+ for (let i = 0; i < kids.length; i++) {
153
+ if (id(kids[i]) === binaryen.LoopId)
154
+ return { parent: e, index: i, loop: kids[i] };
155
+ const inner = locate(kids[i]);
156
+ if (inner)
157
+ return inner;
158
+ }
159
+ };
160
+ const place = locate(f.body);
161
+ if (!place)
162
+ return refusal('no-arena', 'loop not found in the owner');
163
+ const imports = WebAssembly.Module.imports(new WebAssembly.Module(Uint8Array.from(original)));
164
+ let namespace = '__folio_iteration';
165
+ while (imports.some((item) => item.module === namespace))
166
+ namespace += '_';
167
+ let call = '__folio_iterate';
168
+ while (m.getFunction(call))
169
+ call += '_';
170
+ const locals = route.locals.map((item) => item.local);
171
+ m.addFunctionImport(call, namespace, 'iterate', binaryen.createType(locals.map((local) => types[local])), binaryen.i32);
172
+ const get = (local) => m.local.get(local, types[local]);
173
+ const counter = route.trip.local;
174
+ const done = [];
175
+ for (const item of route.locals)
176
+ if (item.kind === 'stride')
177
+ done.push(m.local.set(item.local, m.i32.add(get(item.local), m.i32.mul(get(counter), m.i32.const(item.stride | 0)))));
178
+ done.push(m.local.set(counter, m.i32.const(0)));
179
+ const replacement = m.if(m.call(call, locals.map((local) => get(local)), binaryen.i32), m.block(null, done), place.loop);
180
+ const raw = binaryen;
181
+ if (place.parent)
182
+ raw._BinaryenBlockSetChildAt(place.parent, place.index, replacement);
183
+ else
184
+ raw._BinaryenFunctionSetBody(owner, replacement);
185
+ let stackExport;
186
+ if (stack !== undefined && m.getGlobal(stack)) {
187
+ stackExport = '__folio_owner_stack';
188
+ while (m.getExport(stackExport))
189
+ stackExport += '_';
190
+ m.addGlobalExport(stack, stackExport);
191
+ }
192
+ if (!m.validate())
193
+ throw new Error('invalid iteration owner');
194
+ let bytes;
195
+ try {
196
+ bytes = restoreImportOrder(m.emitBinary(), imports);
197
+ }
198
+ catch (error) {
199
+ return refusal('import-order', `import order cannot be kept: ${error instanceof Error ? error.message : String(error)}`);
200
+ }
201
+ new WebAssembly.Module(Uint8Array.from(bytes));
202
+ return {
203
+ owner: {
204
+ module: bytes,
205
+ namespace,
206
+ locals,
207
+ stackExport,
208
+ memory: {
209
+ module: declared.module,
210
+ name: declared.name,
211
+ initial: declared.initial,
212
+ maximum: declared.maximum
213
+ }
214
+ }
215
+ };
216
+ }
217
+ catch (error) {
218
+ return refusal('no-arena', `iteration owner unavailable: ${error instanceof Error ? error.message : String(error)}`);
219
+ }
220
+ finally {
221
+ module?.dispose();
222
+ }
223
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,150 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { iterationArguments, iterationEntryBytes } from "./iteration-layout.js";
3
+ const { module, memory, arena, globals, iterate, locals, frameSize, port, signal, control } = workerData;
4
+ const L = arena;
5
+ const ENTRY = iterationEntryBytes;
6
+ const exportsOf = new WebAssembly.Instance(module, { env: { memory } }).exports;
7
+ const u8 = new Uint8Array(memory.buffer);
8
+ const u32 = new Uint32Array(memory.buffer);
9
+ const counter = new Int32Array(control);
10
+ const done = new Int32Array(signal);
11
+ const now = () => performance.now();
12
+ const stats = { run: 0, scan: 0 };
13
+ // reads a bitmap into [start, length] runs of granules and zeroes it as it goes
14
+ function scan(base, size) {
15
+ const words = new Uint32Array(memory.buffer, base, size / 4);
16
+ const runs = [];
17
+ let start = -1;
18
+ for (let k = 0; k < words.length; k++) {
19
+ const w = words[k];
20
+ if (w === 0) {
21
+ if (start >= 0) {
22
+ runs.push(start, k * 32 - start);
23
+ start = -1;
24
+ }
25
+ continue;
26
+ }
27
+ words[k] = 0;
28
+ if (w === 0xffffffff) {
29
+ if (start < 0)
30
+ start = k * 32;
31
+ continue;
32
+ }
33
+ for (let b = 0; b < 32; b++) {
34
+ if ((w >>> b) & 1) {
35
+ if (start < 0)
36
+ start = k * 32 + b;
37
+ }
38
+ else if (start >= 0) {
39
+ runs.push(start, k * 32 + b - start);
40
+ start = -1;
41
+ }
42
+ }
43
+ }
44
+ if (start >= 0)
45
+ runs.push(start, words.length * 32 - start);
46
+ return Int32Array.from(runs);
47
+ }
48
+ // status 0 ran, 1 trapped, 2 undo log exhausted
49
+ function runOne(job, s) {
50
+ const index = job.first + s;
51
+ const top = L.slots + (s + 1) * L.slotBytes;
52
+ const frame = top - frameSize;
53
+ if (frameSize)
54
+ u8.copyWithin(frame, job.frameBase, job.frameBase + frameSize);
55
+ const shadow = L.frameShadow + s * L.frameSlotBytes;
56
+ if (frameSize) {
57
+ u8.fill(0, shadow, shadow + L.frameSlotBytes);
58
+ exportsOf[globals.frameLow].value = frame;
59
+ exportsOf[globals.frameSize].value = frameSize;
60
+ exportsOf[globals.frameShadow].value = shadow;
61
+ }
62
+ const rbase = L.rmaps + s * L.rsize;
63
+ const wbase = L.wmaps + s * L.wsize;
64
+ const lbase = L.logs + s * L.logBytes;
65
+ const limit = lbase + L.logCapacity * ENTRY;
66
+ exportsOf[globals.readBitmap].value = rbase;
67
+ exportsOf[globals.writeBitmap].value = wbase;
68
+ exportsOf[globals.logPointer].value = lbase;
69
+ exportsOf[globals.logLimit].value = limit;
70
+ exportsOf[globals.stampAddress].value = L.stamp;
71
+ const stack = exportsOf[globals.stackPointer];
72
+ if (stack)
73
+ stack.value = frameSize ? frame : top;
74
+ const args = iterationArguments(locals, job.entry, index, frame);
75
+ const t1 = now();
76
+ let status = 0;
77
+ try {
78
+ exportsOf[iterate](...args);
79
+ }
80
+ catch (error) {
81
+ const left = limit - (exportsOf[globals.logPointer].value >>> 0);
82
+ status =
83
+ error instanceof WebAssembly.RuntimeError &&
84
+ /unreachable/.test(error.message) &&
85
+ left < ENTRY
86
+ ? 2
87
+ : 1;
88
+ }
89
+ const t2 = now();
90
+ stats.run += t2 - t1;
91
+ const entries = ((exportsOf[globals.logPointer].value >>> 0) - lbase) / ENTRY;
92
+ const written = new Int32Array(entries);
93
+ for (let e = 0; e < entries; e++)
94
+ written[e] = u32[(lbase + e * ENTRY) / 4] >>> 5;
95
+ written.sort();
96
+ const reads = scan(rbase, L.rsize);
97
+ let frameWritten = new Uint32Array(0);
98
+ let frameExposed = new Uint32Array(0);
99
+ if (frameSize) {
100
+ const granules = Math.ceil(frameSize / 32);
101
+ const words = (at) => u32.slice(at / 4, at / 4 + granules);
102
+ const copy = (at) => {
103
+ const found = words(at);
104
+ return found.some(Boolean) ? found : new Uint32Array(0);
105
+ };
106
+ frameWritten = copy(shadow);
107
+ frameExposed = copy(shadow + 4 * granules + 4);
108
+ }
109
+ if (status)
110
+ u8.fill(0, wbase, wbase + L.wsize);
111
+ else
112
+ for (let e = 0; e < entries; e++)
113
+ u8[wbase + (written[e] >>> 3)] = 0;
114
+ stats.scan += now() - t2;
115
+ return {
116
+ index,
117
+ status,
118
+ entries,
119
+ written,
120
+ reads,
121
+ frameWritten,
122
+ frameExposed
123
+ };
124
+ }
125
+ port.on('message', (job) => {
126
+ stats.run = 0;
127
+ stats.scan = 0;
128
+ let reply;
129
+ try {
130
+ const results = [];
131
+ for (;;) {
132
+ const k = Atomics.add(counter, 0, 1);
133
+ if (k >= job.count)
134
+ break;
135
+ const outcome = runOne(job, job.reverse ? job.count - 1 - k : k);
136
+ results.push(outcome);
137
+ // every later iteration is rolled back and replayed anyway, so leave them unstarted
138
+ if (outcome.status && !job.reverse)
139
+ Atomics.store(counter, 0, 1 << 30);
140
+ }
141
+ reply = { done: results, runMs: stats.run, scanMs: stats.scan };
142
+ }
143
+ catch (error) {
144
+ reply = { error: String(error?.stack ?? error) };
145
+ }
146
+ port.postMessage(reply);
147
+ Atomics.add(done, 0, 1);
148
+ Atomics.notify(done, 0);
149
+ });
150
+ parentPort.postMessage({ ready: true });