@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.
- package/LICENSE +21 -0
- package/README.md +541 -2
- package/dist/bake.d.ts +179 -0
- package/dist/bake.js +704 -0
- package/dist/browser-worker.d.ts +9 -0
- package/dist/browser-worker.js +37 -0
- package/dist/browser.d.ts +68 -0
- package/dist/browser.js +274 -0
- package/dist/compiler.d.ts +79 -0
- package/dist/compiler.js +620 -0
- package/dist/context.d.ts +33 -0
- package/dist/context.js +93 -0
- package/dist/coordinator.d.ts +27 -0
- package/dist/coordinator.js +191 -0
- package/dist/extract.d.ts +165 -0
- package/dist/extract.js +1817 -0
- package/dist/frames.d.ts +33 -0
- package/dist/frames.js +159 -0
- package/dist/guards.d.ts +12 -0
- package/dist/guards.js +202 -0
- package/dist/host.d.ts +60 -0
- package/dist/host.js +374 -0
- package/dist/import-order.d.ts +2 -0
- package/dist/import-order.js +114 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/inline.d.ts +68 -0
- package/dist/inline.js +503 -0
- package/dist/iteration-admission.d.ts +76 -0
- package/dist/iteration-admission.js +72 -0
- package/dist/iteration-layout.d.ts +75 -0
- package/dist/iteration-layout.js +118 -0
- package/dist/iteration-owner.d.ts +32 -0
- package/dist/iteration-owner.js +223 -0
- package/dist/iteration-worker.d.ts +1 -0
- package/dist/iteration-worker.js +150 -0
- package/dist/iteration.d.ts +163 -0
- package/dist/iteration.js +435 -0
- package/dist/managed.d.ts +92 -0
- package/dist/managed.js +421 -0
- package/dist/memory.d.ts +10 -0
- package/dist/memory.js +89 -0
- package/dist/node.d.ts +138 -0
- package/dist/node.js +1153 -0
- package/dist/pages.d.ts +109 -0
- package/dist/pages.js +339 -0
- package/dist/remote.d.ts +86 -0
- package/dist/remote.js +255 -0
- package/dist/tasks.d.ts +107 -0
- package/dist/tasks.js +330 -0
- package/dist/transaction.d.ts +23 -0
- package/dist/transaction.js +93 -0
- package/dist/values.d.ts +3 -0
- package/dist/values.js +25 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +86 -0
- package/package.json +130 -5
package/dist/node.js
ADDED
|
@@ -0,0 +1,1153 @@
|
|
|
1
|
+
import { availableParallelism } from 'node:os';
|
|
2
|
+
import { isArrayBuffer, isSharedArrayBuffer, isUint8Array } from 'node:util/types';
|
|
3
|
+
import { Worker } from 'node:worker_threads';
|
|
4
|
+
import { Coordinator } from "./coordinator.js";
|
|
5
|
+
import { decideAdmission, decideBatch, decideCollapse } from "./iteration-admission.js";
|
|
6
|
+
import { iterationArguments, iterationFit } from "./iteration-layout.js";
|
|
7
|
+
import { memoryImports } from "./memory.js";
|
|
8
|
+
import { numberBits, restoreNumbers } from "./values.js";
|
|
9
|
+
/** Wraps an asynchronous host import for Wasm stack suspension. */
|
|
10
|
+
export function suspending(fn) {
|
|
11
|
+
const runtime = WebAssembly;
|
|
12
|
+
if (!runtime.Suspending)
|
|
13
|
+
throw new Error('this runtime does not support JSPI');
|
|
14
|
+
return new runtime.Suspending(fn);
|
|
15
|
+
}
|
|
16
|
+
function isModule(value) {
|
|
17
|
+
try {
|
|
18
|
+
WebAssembly.Module.exports(value);
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function isMemory(value) {
|
|
26
|
+
try {
|
|
27
|
+
Object.getOwnPropertyDescriptor(WebAssembly.Memory.prototype, 'buffer').get.call(value);
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const PAGE = 65536;
|
|
35
|
+
function addCounts(total, part) {
|
|
36
|
+
if (!total)
|
|
37
|
+
return structuredClone(part);
|
|
38
|
+
for (const key of Object.keys(part)) {
|
|
39
|
+
if (key === 'stopped')
|
|
40
|
+
total.stopped ??= part.stopped;
|
|
41
|
+
else if (key === 'admission')
|
|
42
|
+
total.admission = part.admission ?? total.admission;
|
|
43
|
+
else if (key === 'workers')
|
|
44
|
+
total.workers = Math.max(total.workers, part.workers);
|
|
45
|
+
else if (key === 'conflicts') {
|
|
46
|
+
total.conflicts.raw += part.conflicts.raw;
|
|
47
|
+
total.conflicts.war += part.conflicts.war;
|
|
48
|
+
total.conflicts.waw += part.conflicts.waw;
|
|
49
|
+
total.conflicts.frame += part.conflicts.frame;
|
|
50
|
+
}
|
|
51
|
+
else
|
|
52
|
+
total[key] += part[key];
|
|
53
|
+
}
|
|
54
|
+
return total;
|
|
55
|
+
}
|
|
56
|
+
// true when the host supplies the memory import through `imports`, or it cannot be told safely
|
|
57
|
+
function suppliesMemory(imports, module, name) {
|
|
58
|
+
if (!imports || !(module in imports))
|
|
59
|
+
return false;
|
|
60
|
+
const descriptor = Object.getOwnPropertyDescriptor(imports, module);
|
|
61
|
+
if (!descriptor || !('value' in descriptor))
|
|
62
|
+
return true;
|
|
63
|
+
const value = descriptor.value;
|
|
64
|
+
return value !== null && ['object', 'function'].includes(typeof value) && name in value;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Chooses the iteration route for a program no older route covers, and builds its owner module and
|
|
68
|
+
* shared memory. A refusal names its reason; a program that is not a candidate returns nothing.
|
|
69
|
+
*/
|
|
70
|
+
async function selectIteration(program, options, size) {
|
|
71
|
+
const route = program.iterationRoute;
|
|
72
|
+
if (!route?.eligible ||
|
|
73
|
+
size < 2 ||
|
|
74
|
+
program.control ||
|
|
75
|
+
program.compiled ||
|
|
76
|
+
Object.keys(program.loops).length ||
|
|
77
|
+
Object.keys(program.native ?? {}).length)
|
|
78
|
+
return;
|
|
79
|
+
const refuse = (reason, detail) => ({ reason, detail });
|
|
80
|
+
const { iterationOwner } = await import("./iteration-owner.js");
|
|
81
|
+
const built = iterationOwner(program.original, route, program.stackRoute?.stack?.name);
|
|
82
|
+
if (!('owner' in built))
|
|
83
|
+
return built;
|
|
84
|
+
const owner = built.owner;
|
|
85
|
+
if (suppliesMemory(options.imports, owner.memory.module, owner.memory.name))
|
|
86
|
+
return refuse('no-arena', 'the memory import is supplied through imports');
|
|
87
|
+
if (options.memory && !isMemory(options.memory))
|
|
88
|
+
return;
|
|
89
|
+
if (options.memory && !isSharedArrayBuffer(options.memory.buffer))
|
|
90
|
+
return refuse('no-arena', 'the host memory is not shared');
|
|
91
|
+
const start = options.memory ? options.memory.buffer.byteLength : owner.memory.initial * PAGE;
|
|
92
|
+
const fit = iterationFit(start, { frameBytes: route.frame?.size });
|
|
93
|
+
if (!fit)
|
|
94
|
+
return refuse('no-arena', 'the arena does not fit in 65536 pages');
|
|
95
|
+
if (owner.memory.maximum !== undefined && fit.pages > owner.memory.maximum)
|
|
96
|
+
return refuse('no-arena', `the declared maximum of ${owner.memory.maximum} pages is below the ${fit.pages} the arena needs`);
|
|
97
|
+
let memory = options.memory;
|
|
98
|
+
try {
|
|
99
|
+
if (memory)
|
|
100
|
+
memory.grow(fit.pages - start / PAGE);
|
|
101
|
+
else
|
|
102
|
+
memory = new WebAssembly.Memory({
|
|
103
|
+
initial: fit.pages,
|
|
104
|
+
maximum: Math.max(owner.memory.maximum ?? fit.pages, fit.pages),
|
|
105
|
+
shared: true
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (!(error instanceof RangeError))
|
|
110
|
+
throw error;
|
|
111
|
+
return refuse('no-arena', `memory cannot hold an arena of ${fit.bytes} bytes`);
|
|
112
|
+
}
|
|
113
|
+
return { route, owner, memory, arenaBase: fit.base, size };
|
|
114
|
+
}
|
|
115
|
+
function throwTrap(result) {
|
|
116
|
+
if (!result.trap)
|
|
117
|
+
return;
|
|
118
|
+
if (result.errorKind === 'TypeError')
|
|
119
|
+
throw new TypeError(result.trap);
|
|
120
|
+
if (result.errorKind === 'RangeError')
|
|
121
|
+
throw new RangeError(result.trap);
|
|
122
|
+
throw new WebAssembly.RuntimeError(result.trap);
|
|
123
|
+
}
|
|
124
|
+
/** A same-process isolate group; callers give it exclusive memory access during each run. */
|
|
125
|
+
export class Folio {
|
|
126
|
+
/** Active sharing, extraction and validation mode; a one-worker pool reports none and serial. */
|
|
127
|
+
get capabilities() {
|
|
128
|
+
return Object.freeze({
|
|
129
|
+
physicalSharing: this.#workers.length || this.#iteration
|
|
130
|
+
? 'same-process'
|
|
131
|
+
: 'none',
|
|
132
|
+
automaticRegions: this.#iteration
|
|
133
|
+
? 'iteration'
|
|
134
|
+
: this.#workers.length
|
|
135
|
+
? this.#control
|
|
136
|
+
? 'control-flow'
|
|
137
|
+
: 'counted-loops'
|
|
138
|
+
: 'none',
|
|
139
|
+
dependence: this.#workers.length || this.#iteration
|
|
140
|
+
? 'ordered-validation'
|
|
141
|
+
: 'serial'
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/** The original native exports, for trusted host integration. Raw calls bypass tracking. */
|
|
145
|
+
get exports() {
|
|
146
|
+
return this.#exports;
|
|
147
|
+
}
|
|
148
|
+
/** The unique accessible arena, including a coordinator-exposed hidden memory. Throws otherwise. */
|
|
149
|
+
get memory() {
|
|
150
|
+
if (!this.#memory)
|
|
151
|
+
throw new Error('program has no single bound or exported memory; use memories');
|
|
152
|
+
return this.#memory;
|
|
153
|
+
}
|
|
154
|
+
/** Named imported and exported memory wrappers. */
|
|
155
|
+
get memories() {
|
|
156
|
+
return this.#memories;
|
|
157
|
+
}
|
|
158
|
+
/** Module-wide reasons the optimizer refused or fell back. A refusal is not a proved dependency. */
|
|
159
|
+
get diagnostics() {
|
|
160
|
+
return [
|
|
161
|
+
...this.#program.reasons,
|
|
162
|
+
...(this.#program.controlReasons ?? []),
|
|
163
|
+
...(this.#control?.diagnostics ?? []),
|
|
164
|
+
...this.#runtimeDiagnostics
|
|
165
|
+
];
|
|
166
|
+
}
|
|
167
|
+
/** Whether `entry` has an automatic plan or a native guard, by which mechanism, and why not. */
|
|
168
|
+
inspect(entry) {
|
|
169
|
+
const reason = this.#program.loopReasons && Object.hasOwn(this.#program.loopReasons, entry)
|
|
170
|
+
? this.#program.loopReasons[entry]
|
|
171
|
+
: undefined;
|
|
172
|
+
return Object.freeze({
|
|
173
|
+
automatic: Object.hasOwn(this.#program.loops, entry) ||
|
|
174
|
+
Boolean(this.#control?.entries.includes(entry)),
|
|
175
|
+
nativeGuard: Boolean(this.#program.native && Object.hasOwn(this.#program.native, entry)),
|
|
176
|
+
mechanism: this.#control?.entries.includes(entry)
|
|
177
|
+
? 'control-flow'
|
|
178
|
+
: Object.hasOwn(this.#program.loops, entry)
|
|
179
|
+
? 'counted-loop'
|
|
180
|
+
: 'native',
|
|
181
|
+
diagnostics: Object.freeze([...this.diagnostics, ...(reason ? [reason] : [])])
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
#memory;
|
|
185
|
+
#iteration;
|
|
186
|
+
#ownerStack;
|
|
187
|
+
#refusal;
|
|
188
|
+
#workerMemory;
|
|
189
|
+
#control;
|
|
190
|
+
#serial;
|
|
191
|
+
#queued;
|
|
192
|
+
#coordinator;
|
|
193
|
+
#controlled = new Map();
|
|
194
|
+
#workerExports = new Set();
|
|
195
|
+
#runtimeDiagnostics = [];
|
|
196
|
+
#exports;
|
|
197
|
+
#memories = {};
|
|
198
|
+
#promising = new Map();
|
|
199
|
+
#nativePending = new Set();
|
|
200
|
+
/** Thread ids of the worker isolates, in start order. */
|
|
201
|
+
threadIds = [];
|
|
202
|
+
#program;
|
|
203
|
+
#instance;
|
|
204
|
+
#workers = [];
|
|
205
|
+
#pending = new Map();
|
|
206
|
+
#fuel;
|
|
207
|
+
#maxBytes;
|
|
208
|
+
#minimumWork;
|
|
209
|
+
#profile;
|
|
210
|
+
#adaptive;
|
|
211
|
+
#routing = new Map();
|
|
212
|
+
#nextId = 0;
|
|
213
|
+
#busy = false;
|
|
214
|
+
#closed = false;
|
|
215
|
+
#closing;
|
|
216
|
+
#failure;
|
|
217
|
+
constructor(program, options, size, choice) {
|
|
218
|
+
this.#program = program;
|
|
219
|
+
if (choice && 'owner' in choice)
|
|
220
|
+
this.#iteration = choice;
|
|
221
|
+
else if (choice) {
|
|
222
|
+
this.#refusal = choice;
|
|
223
|
+
this.#runtimeDiagnostics.push(`iteration route refused: ${choice.detail}`);
|
|
224
|
+
}
|
|
225
|
+
const iteration = this.#iteration;
|
|
226
|
+
this.#fuel = options.fuel ?? 100_000_000;
|
|
227
|
+
this.#maxBytes = options.maxTransactionBytes ?? 262_144;
|
|
228
|
+
this.#minimumWork = options.minimumParallelWork ?? 100_000;
|
|
229
|
+
this.#profile = options.profile ?? false;
|
|
230
|
+
this.#adaptive = options.adaptiveRouting ?? false;
|
|
231
|
+
if (!Number.isInteger(this.#fuel) || this.#fuel < 2 || this.#fuel > 2_147_483_647)
|
|
232
|
+
throw new RangeError('invalid fuel');
|
|
233
|
+
if (!Number.isInteger(this.#maxBytes) || this.#maxBytes < 1)
|
|
234
|
+
throw new RangeError('invalid transaction budget');
|
|
235
|
+
if (!Number.isFinite(this.#minimumWork) || this.#minimumWork < 0)
|
|
236
|
+
throw new RangeError('invalid work threshold');
|
|
237
|
+
const native = program.compiled ?? new WebAssembly.Module(Uint8Array.from(program.original));
|
|
238
|
+
const runtime = WebAssembly;
|
|
239
|
+
let executable = native;
|
|
240
|
+
const control = program.control;
|
|
241
|
+
if (control && size > 1 && runtime.Suspending && runtime.promising) {
|
|
242
|
+
const candidate = new WebAssembly.Module(Uint8Array.from(control.coordinator));
|
|
243
|
+
const originalImports = WebAssembly.Module.imports(native);
|
|
244
|
+
const retainedImports = WebAssembly.Module.imports(candidate).filter((item) => item.module !== control.namespace);
|
|
245
|
+
// Binding accessors are effects too: retain the original engine lookup sequence.
|
|
246
|
+
if (JSON.stringify(originalImports) === JSON.stringify(retainedImports)) {
|
|
247
|
+
this.#control = control;
|
|
248
|
+
executable = candidate;
|
|
249
|
+
this.#serial = new WebAssembly.Global({ value: 'i32', mutable: true }, 1);
|
|
250
|
+
this.#queued = new WebAssembly.Global({ value: 'i32', mutable: true }, 0);
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
this.#runtimeDiagnostics.push('control extraction retained native binding order: rewritten import sequence differs');
|
|
254
|
+
}
|
|
255
|
+
if (iteration) {
|
|
256
|
+
executable = new WebAssembly.Module(Uint8Array.from(iteration.owner.module));
|
|
257
|
+
this.#runtimeDiagnostics.push(`iteration route: ${iteration.route.diagnostics.join('; ')}`);
|
|
258
|
+
}
|
|
259
|
+
const imported = WebAssembly.Module.imports(native).filter((item) => item.kind === 'memory');
|
|
260
|
+
if (imported.length > 1 && options.memory)
|
|
261
|
+
throw new TypeError('bind multiple memories by name in imports');
|
|
262
|
+
let descriptors = [];
|
|
263
|
+
try {
|
|
264
|
+
descriptors = memoryImports(program.original);
|
|
265
|
+
}
|
|
266
|
+
catch { }
|
|
267
|
+
const supplied = options.imports ?? Object.create(null);
|
|
268
|
+
const automatic = new Map();
|
|
269
|
+
let controlBindings;
|
|
270
|
+
let iterationBindings;
|
|
271
|
+
// Resolve bindings when the engine asks for them, in its original order.
|
|
272
|
+
// Enumerating/spreading caller namespaces would invoke accessors early or twice.
|
|
273
|
+
const imports = new Proxy(Object.create(null), {
|
|
274
|
+
get: (_, module) => {
|
|
275
|
+
if (this.#control && module === this.#control.namespace) {
|
|
276
|
+
if (controlBindings)
|
|
277
|
+
return controlBindings;
|
|
278
|
+
const bindings = {
|
|
279
|
+
[this.#control.serialGlobal]: this.#serial,
|
|
280
|
+
[this.#control.pendingGlobal]: this.#queued,
|
|
281
|
+
barrier: new runtime.Suspending(() => this.#coordinator?.flush()),
|
|
282
|
+
poll: new runtime.Suspending(() => this.#coordinator?.poll())
|
|
283
|
+
};
|
|
284
|
+
for (const region of this.#control.regions) {
|
|
285
|
+
bindings[region.importName] = new runtime.Suspending((...args) => {
|
|
286
|
+
if (!this.#coordinator || Number(this.#serial.value) !== 0) {
|
|
287
|
+
this.#instance.exports[region.exportName](...args);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
return this.#coordinator.enqueue({
|
|
291
|
+
export: region.exportName,
|
|
292
|
+
args
|
|
293
|
+
});
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
return (controlBindings = bindings);
|
|
297
|
+
}
|
|
298
|
+
if (iteration && module === iteration.owner.namespace)
|
|
299
|
+
return (iterationBindings ??= {
|
|
300
|
+
iterate: (...values) => this.#iterate(values)
|
|
301
|
+
});
|
|
302
|
+
const namespace = Reflect.get(supplied, module, supplied);
|
|
303
|
+
const memories = imported.filter((item) => item.module === module);
|
|
304
|
+
if (!memories.length ||
|
|
305
|
+
(namespace !== undefined &&
|
|
306
|
+
(namespace === null || !['object', 'function'].includes(typeof namespace))))
|
|
307
|
+
return namespace;
|
|
308
|
+
return new Proxy(Object.create(null), {
|
|
309
|
+
get: (_, name) => {
|
|
310
|
+
const item = memories.find((item) => item.name === name);
|
|
311
|
+
if (!item)
|
|
312
|
+
return namespace === undefined
|
|
313
|
+
? undefined
|
|
314
|
+
: Reflect.get(namespace, name, namespace);
|
|
315
|
+
let bound = iteration
|
|
316
|
+
? iteration.memory
|
|
317
|
+
: (options.memory ??
|
|
318
|
+
(namespace === undefined
|
|
319
|
+
? undefined
|
|
320
|
+
: Reflect.get(namespace, name, namespace)));
|
|
321
|
+
if (bound === undefined) {
|
|
322
|
+
const key = JSON.stringify([module, name]);
|
|
323
|
+
bound = automatic.get(key);
|
|
324
|
+
if (!bound) {
|
|
325
|
+
const descriptor = descriptors.find((value) => value.module === module && value.name === name);
|
|
326
|
+
if (!descriptor || descriptor.memory64)
|
|
327
|
+
throw new TypeError(`provide imported memory ${module}.${name}`);
|
|
328
|
+
bound = new WebAssembly.Memory({
|
|
329
|
+
initial: descriptor.initial,
|
|
330
|
+
...(descriptor.maximum === undefined
|
|
331
|
+
? {}
|
|
332
|
+
: { maximum: descriptor.maximum }),
|
|
333
|
+
shared: descriptor.shared
|
|
334
|
+
});
|
|
335
|
+
automatic.set(key, bound);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (isMemory(bound)) {
|
|
339
|
+
this.#memories[`${module}.${name}`] = bound;
|
|
340
|
+
if (imported.length === 1)
|
|
341
|
+
this.#memory = bound;
|
|
342
|
+
}
|
|
343
|
+
return bound;
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
});
|
|
348
|
+
// JSPI Promise resolution can assimilate an externref Promise result.
|
|
349
|
+
// Only explicitly asynchronous entries get that ABI; ordinary exports
|
|
350
|
+
// retain their native identity and return-value semantics.
|
|
351
|
+
const promising = options.promising ?? [];
|
|
352
|
+
for (const name of promising) {
|
|
353
|
+
if (!WebAssembly.Module.exports(native).some((value) => value.name === name && value.kind === 'function'))
|
|
354
|
+
throw new TypeError(`unknown promising export: ${name}`);
|
|
355
|
+
if (!runtime.promising)
|
|
356
|
+
throw new Error('this runtime does not support JSPI');
|
|
357
|
+
}
|
|
358
|
+
this.#instance = new WebAssembly.Instance(executable, imports);
|
|
359
|
+
if (this.#control) {
|
|
360
|
+
this.#exports = Object.create(null);
|
|
361
|
+
for (const item of WebAssembly.Module.exports(native)) {
|
|
362
|
+
Object.defineProperty(this.#exports, item.name, {
|
|
363
|
+
value: this.#instance.exports[item.name],
|
|
364
|
+
enumerable: true
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
Object.preventExtensions(this.#exports);
|
|
368
|
+
const arena = this.#instance.exports[this.#control.memoryExport];
|
|
369
|
+
if (isMemory(arena))
|
|
370
|
+
this.#memory = arena;
|
|
371
|
+
for (const entry of this.#control.entries) {
|
|
372
|
+
this.#controlled.set(entry, runtime.promising(this.#instance.exports[entry]));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
else if (iteration) {
|
|
376
|
+
this.#exports = Object.create(null);
|
|
377
|
+
for (const item of WebAssembly.Module.exports(native)) {
|
|
378
|
+
Object.defineProperty(this.#exports, item.name, {
|
|
379
|
+
value: this.#instance.exports[item.name],
|
|
380
|
+
enumerable: true
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
Object.preventExtensions(this.#exports);
|
|
384
|
+
if (iteration.owner.stackExport)
|
|
385
|
+
this.#ownerStack = this.#instance.exports[iteration.owner.stackExport];
|
|
386
|
+
}
|
|
387
|
+
else
|
|
388
|
+
this.#exports = this.#instance.exports;
|
|
389
|
+
for (const [name, value] of Object.entries(this.#exports)) {
|
|
390
|
+
if (isMemory(value))
|
|
391
|
+
this.#memories[`exports.${name}`] = value;
|
|
392
|
+
}
|
|
393
|
+
if (!imported.length) {
|
|
394
|
+
const own = Object.values(this.#exports).filter(isMemory);
|
|
395
|
+
if (own.length === 1)
|
|
396
|
+
this.#memory = own[0];
|
|
397
|
+
}
|
|
398
|
+
Object.freeze(this.#memories);
|
|
399
|
+
for (const name of promising) {
|
|
400
|
+
const entry = this.#exports[name];
|
|
401
|
+
this.#promising.set(name, runtime.promising(entry));
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/** Instantiates the program, starts the worker group and returns a ready pool. */
|
|
405
|
+
static async open(input, options = {}) {
|
|
406
|
+
const program = isModule(input)
|
|
407
|
+
? {
|
|
408
|
+
original: new Uint8Array(),
|
|
409
|
+
compiled: input,
|
|
410
|
+
loops: {},
|
|
411
|
+
reasons: ['compiled module has no inspectable source bytes']
|
|
412
|
+
}
|
|
413
|
+
: isUint8Array(input) || isArrayBuffer(input)
|
|
414
|
+
? (await import("./compiler.js")).prepare(isUint8Array(input) ? input : new Uint8Array(input), {
|
|
415
|
+
minimumRegionWork: options.minimumRegionWork,
|
|
416
|
+
assumedTripCount: options.assumedTripCount
|
|
417
|
+
})
|
|
418
|
+
: input;
|
|
419
|
+
const size = options.workers ?? Math.min(4, availableParallelism());
|
|
420
|
+
if (!Number.isInteger(size) || size < 1 || size > 64)
|
|
421
|
+
throw new RangeError('invalid worker count');
|
|
422
|
+
const pool = new Folio(program, options, size, await selectIteration(program, options, size));
|
|
423
|
+
const transactional = pool.#control?.transactional ?? program.transactional;
|
|
424
|
+
if (!transactional || size === 1)
|
|
425
|
+
return pool;
|
|
426
|
+
if (pool.#control && !isSharedArrayBuffer(pool.memory.buffer)) {
|
|
427
|
+
try {
|
|
428
|
+
pool.#workerMemory = new WebAssembly.Memory({
|
|
429
|
+
initial: pool.memory.buffer.byteLength / 65536,
|
|
430
|
+
maximum: pool.#control.maximum,
|
|
431
|
+
shared: true
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
if (!(error instanceof RangeError))
|
|
436
|
+
throw error;
|
|
437
|
+
pool.#runtimeDiagnostics.push('shared worker arena allocation unavailable; using native execution');
|
|
438
|
+
return pool;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
else
|
|
442
|
+
pool.#workerMemory = pool.memory;
|
|
443
|
+
if (!isSharedArrayBuffer(pool.#workerMemory.buffer))
|
|
444
|
+
throw new TypeError('physical sharing requires shared memory');
|
|
445
|
+
const module = new WebAssembly.Module(Uint8Array.from(transactional));
|
|
446
|
+
const nativeModule = new WebAssembly.Module(Uint8Array.from(pool.#control?.workerOriginal ?? program.original));
|
|
447
|
+
for (const entry of WebAssembly.Module.exports(nativeModule)) {
|
|
448
|
+
if (entry.kind === 'function')
|
|
449
|
+
pool.#workerExports.add(entry.name);
|
|
450
|
+
}
|
|
451
|
+
const memoryImport = WebAssembly.Module.imports(module).find((item) => item.kind === 'memory');
|
|
452
|
+
try {
|
|
453
|
+
await Promise.all(Array.from({ length: size }, () => new Promise((resolve, reject) => {
|
|
454
|
+
const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
|
|
455
|
+
const worker = new Worker(new URL(`./worker.${extension}`, import.meta.url), {
|
|
456
|
+
workerData: {
|
|
457
|
+
module,
|
|
458
|
+
nativeModule,
|
|
459
|
+
memory: pool.#workerMemory,
|
|
460
|
+
importModule: memoryImport.module,
|
|
461
|
+
importName: memoryImport.name
|
|
462
|
+
}
|
|
463
|
+
});
|
|
464
|
+
pool.#workers.push(worker);
|
|
465
|
+
worker.on('message', (message) => {
|
|
466
|
+
if (message.ready) {
|
|
467
|
+
pool.threadIds.push(message.threadId);
|
|
468
|
+
resolve();
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
if (message.results) {
|
|
472
|
+
for (const result of message.results) {
|
|
473
|
+
if (result.numberBits !== undefined)
|
|
474
|
+
result.value = restoreNumbers(result.value, result.numberBits);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (message.numberBits !== undefined)
|
|
478
|
+
message.value = restoreNumbers(message.value, message.numberBits);
|
|
479
|
+
const pending = pool.#pending.get(message.id);
|
|
480
|
+
pool.#pending.delete(message.id);
|
|
481
|
+
pending?.resolve(message.results ?? message);
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
const fail = (error) => {
|
|
485
|
+
pool.#failure = error;
|
|
486
|
+
reject(error);
|
|
487
|
+
for (const pending of pool.#pending.values())
|
|
488
|
+
pending.reject(error);
|
|
489
|
+
pool.#pending.clear();
|
|
490
|
+
};
|
|
491
|
+
worker.on('error', fail);
|
|
492
|
+
worker.on('exit', (code) => {
|
|
493
|
+
if (!pool.#closed)
|
|
494
|
+
fail(new Error(`isolate exited with code ${code}`));
|
|
495
|
+
});
|
|
496
|
+
})));
|
|
497
|
+
return pool;
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
await pool.close();
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
async #native(call) {
|
|
505
|
+
if (this.#closed)
|
|
506
|
+
throw new Error('folio is closed');
|
|
507
|
+
const entry = this.#instance.exports[call.export];
|
|
508
|
+
if (typeof entry !== 'function')
|
|
509
|
+
throw new TypeError(`unknown function export: ${call.export}`);
|
|
510
|
+
const wrapped = this.#promising.get(call.export) ?? this.#controlled.get(call.export);
|
|
511
|
+
if (!wrapped)
|
|
512
|
+
return { value: entry(...call.args) };
|
|
513
|
+
const pending = wrapped(...call.args);
|
|
514
|
+
this.#nativePending.add(pending);
|
|
515
|
+
try {
|
|
516
|
+
return { value: await pending };
|
|
517
|
+
}
|
|
518
|
+
finally {
|
|
519
|
+
this.#nativePending.delete(pending);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
#dispatch(worker, call, native = false) {
|
|
523
|
+
if (this.#closed)
|
|
524
|
+
return Promise.reject(new Error('folio is closed'));
|
|
525
|
+
return new Promise((resolve, reject) => {
|
|
526
|
+
const id = this.#nextId++;
|
|
527
|
+
this.#pending.set(id, { resolve, reject });
|
|
528
|
+
try {
|
|
529
|
+
worker.postMessage({
|
|
530
|
+
id,
|
|
531
|
+
call,
|
|
532
|
+
argumentBits: numberBits(call.args),
|
|
533
|
+
native,
|
|
534
|
+
profile: this.#profile,
|
|
535
|
+
fuel: this.#fuel,
|
|
536
|
+
maxBytes: this.#maxBytes
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
catch (error) {
|
|
540
|
+
this.#pending.delete(id);
|
|
541
|
+
reject(error);
|
|
542
|
+
}
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
#dispatchBatch(worker, calls) {
|
|
546
|
+
if (this.#closed)
|
|
547
|
+
return Promise.reject(new Error('folio is closed'));
|
|
548
|
+
return new Promise((resolve, reject) => {
|
|
549
|
+
const id = this.#nextId++;
|
|
550
|
+
this.#pending.set(id, { resolve, reject });
|
|
551
|
+
try {
|
|
552
|
+
worker.postMessage({
|
|
553
|
+
id,
|
|
554
|
+
calls,
|
|
555
|
+
argumentBits: calls.map((call) => numberBits(call.args)),
|
|
556
|
+
profile: this.#profile,
|
|
557
|
+
fuel: this.#fuel,
|
|
558
|
+
maxBytes: this.#maxBytes
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
catch (error) {
|
|
562
|
+
this.#pending.delete(id);
|
|
563
|
+
reject(error);
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
#width(options) {
|
|
568
|
+
const limit = options.maximumWorkers ?? this.#workers.length;
|
|
569
|
+
if (options.maximumWorkers !== undefined &&
|
|
570
|
+
(!Number.isInteger(limit) || limit < 1 || limit > 64))
|
|
571
|
+
throw new RangeError('invalid maximumWorkers');
|
|
572
|
+
return Math.min(limit, this.#workers.length);
|
|
573
|
+
}
|
|
574
|
+
/** Splits compiler-recognized loops automatically; otherwise runs the original entry. */
|
|
575
|
+
async run(entry, args = [], options = {}) {
|
|
576
|
+
const width = this.#width(options);
|
|
577
|
+
const plan = Object.hasOwn(this.#program.loops, entry)
|
|
578
|
+
? this.#program.loops[entry]
|
|
579
|
+
: undefined;
|
|
580
|
+
const proved = this.#program.native && Object.hasOwn(this.#program.native, entry)
|
|
581
|
+
? this.#program.native[entry]
|
|
582
|
+
: undefined;
|
|
583
|
+
const numeric = args.every((arg) => typeof arg === 'number');
|
|
584
|
+
const control = this.#controlled.get(entry);
|
|
585
|
+
const routeKey = this.#adaptive &&
|
|
586
|
+
options.parallel !== 'off' &&
|
|
587
|
+
options.parallel !== 'speculate' &&
|
|
588
|
+
width >= 2 &&
|
|
589
|
+
(plan || control) &&
|
|
590
|
+
args.every((arg) => typeof arg === 'number' || typeof arg === 'bigint')
|
|
591
|
+
? JSON.stringify([
|
|
592
|
+
entry,
|
|
593
|
+
width,
|
|
594
|
+
this.#memory?.buffer.byteLength,
|
|
595
|
+
args.map((arg) => (typeof arg === 'bigint' ? `${arg}n` : arg))
|
|
596
|
+
])
|
|
597
|
+
: undefined;
|
|
598
|
+
const history = routeKey ? this.#routing.get(routeKey) : undefined;
|
|
599
|
+
if (history && history.remaining > 0) {
|
|
600
|
+
history.remaining--;
|
|
601
|
+
const report = await this.runAll([{ export: entry, args }], { parallel: 'off' });
|
|
602
|
+
report.reason = 'previous-conflicts';
|
|
603
|
+
return report;
|
|
604
|
+
}
|
|
605
|
+
if (!plan &&
|
|
606
|
+
control &&
|
|
607
|
+
width >= 2 &&
|
|
608
|
+
options.parallel !== 'off' &&
|
|
609
|
+
args.every((arg) => typeof arg === 'number' || typeof arg === 'bigint')) {
|
|
610
|
+
const report = await this.#runControlled(control, args, width);
|
|
611
|
+
this.#observeRouting(routeKey, report);
|
|
612
|
+
return report;
|
|
613
|
+
}
|
|
614
|
+
if (!plan && this.#iteration && options.parallel !== 'off')
|
|
615
|
+
return this.#runIteration(entry, args, options);
|
|
616
|
+
const count = numeric && plan && typeof args[plan.countParameter] === 'number'
|
|
617
|
+
? Number(args[plan.countParameter]) >>> 0
|
|
618
|
+
: 0;
|
|
619
|
+
const work = numeric
|
|
620
|
+
? proved?.workParameters.reduce((value, parameter) => value * (Number(args[parameter]) >>> 0), count)
|
|
621
|
+
: undefined;
|
|
622
|
+
if (!plan || count < 2 || !numeric || width < 2 || options.parallel === 'off') {
|
|
623
|
+
const report = await this.runAll([{ export: entry, args }], { parallel: 'off' });
|
|
624
|
+
report.reason =
|
|
625
|
+
options.parallel === 'off'
|
|
626
|
+
? 'requested'
|
|
627
|
+
: !plan && this.#refusal
|
|
628
|
+
? this.#refusal.reason
|
|
629
|
+
: !numeric
|
|
630
|
+
? 'opaque-input'
|
|
631
|
+
: !this.#workers.length
|
|
632
|
+
? 'unsupported-module'
|
|
633
|
+
: !plan
|
|
634
|
+
? 'no-parallel-plan'
|
|
635
|
+
: 'single-region';
|
|
636
|
+
return report;
|
|
637
|
+
}
|
|
638
|
+
if (options.parallel !== 'speculate' && work !== undefined && work < this.#minimumWork) {
|
|
639
|
+
const report = await this.runAll([{ export: entry, args }], { parallel: 'off' });
|
|
640
|
+
report.reason = 'small-workload';
|
|
641
|
+
return report;
|
|
642
|
+
}
|
|
643
|
+
const regions = Math.min(count, width);
|
|
644
|
+
const calls = [];
|
|
645
|
+
let begin = 0;
|
|
646
|
+
for (let index = 0; index < regions; index++) {
|
|
647
|
+
const end = Math.floor(((index + 1) * count) / regions);
|
|
648
|
+
const parameters = [...args];
|
|
649
|
+
parameters[plan.countParameter] = end - begin;
|
|
650
|
+
for (const { parameter, step } of plan.steps) {
|
|
651
|
+
parameters[parameter] =
|
|
652
|
+
((Number(args[parameter]) | 0) + Math.imul(begin, step)) | 0;
|
|
653
|
+
}
|
|
654
|
+
calls.push({ export: entry, args: parameters });
|
|
655
|
+
begin = end;
|
|
656
|
+
}
|
|
657
|
+
const disjoint = proved && options.parallel !== 'speculate' && this.#disjoint(calls, proved, plan);
|
|
658
|
+
const report = disjoint
|
|
659
|
+
? await this.#nativeRegions(calls)
|
|
660
|
+
: await this.runAll(calls, options);
|
|
661
|
+
if (proved && !disjoint && options.parallel !== 'speculate' && !report.reason)
|
|
662
|
+
report.reason = 'guard-failed';
|
|
663
|
+
this.#observeRouting(routeKey, report);
|
|
664
|
+
return { ...report, values: [undefined] };
|
|
665
|
+
}
|
|
666
|
+
// the workers of the iteration route start at the first call that may dispatch
|
|
667
|
+
#iterationPool(width) {
|
|
668
|
+
const it = this.#iteration;
|
|
669
|
+
const opened = (it.opening ?? Promise.resolve()).then(async () => {
|
|
670
|
+
if (this.#closed || it.disabled || it.pool?.width === width)
|
|
671
|
+
return;
|
|
672
|
+
await it.pool?.close();
|
|
673
|
+
it.pool = undefined;
|
|
674
|
+
try {
|
|
675
|
+
const { IterationPool } = await import("./iteration.js");
|
|
676
|
+
it.pool = await IterationPool.open(it.route, it.memory, {
|
|
677
|
+
arenaBase: it.arenaBase,
|
|
678
|
+
width
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
catch (error) {
|
|
682
|
+
it.disabled = true;
|
|
683
|
+
this.#runtimeDiagnostics.push(`iteration workers unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
it.opening = opened.catch(() => { });
|
|
687
|
+
return opened.then(() => it.pool);
|
|
688
|
+
}
|
|
689
|
+
async #runIteration(entry, args, options) {
|
|
690
|
+
const it = this.#iteration;
|
|
691
|
+
if (this.#closed)
|
|
692
|
+
throw new Error('folio is closed');
|
|
693
|
+
if (this.#failure)
|
|
694
|
+
throw this.#failure;
|
|
695
|
+
if (this.#busy)
|
|
696
|
+
throw new Error('memory already has an active run');
|
|
697
|
+
const limit = options.maximumWorkers ?? it.size;
|
|
698
|
+
if (options.maximumWorkers !== undefined &&
|
|
699
|
+
(!Number.isInteger(limit) || limit < 1 || limit > 64))
|
|
700
|
+
throw new RangeError('invalid maximumWorkers');
|
|
701
|
+
const width = Math.min(limit, it.size);
|
|
702
|
+
const call = [{ export: entry, args }];
|
|
703
|
+
if (width < 2) {
|
|
704
|
+
const report = await this.runAll(call, { parallel: 'off' });
|
|
705
|
+
report.reason = 'single-region';
|
|
706
|
+
return report;
|
|
707
|
+
}
|
|
708
|
+
const route = it.route;
|
|
709
|
+
const parameter = route.trip?.parameter;
|
|
710
|
+
const small = entry === route.owner &&
|
|
711
|
+
parameter !== undefined &&
|
|
712
|
+
typeof args[parameter] === 'number' &&
|
|
713
|
+
Number(args[parameter]) >>> 0 < 2;
|
|
714
|
+
const pool = small ? undefined : await this.#iterationPool(width);
|
|
715
|
+
if (this.#closed)
|
|
716
|
+
throw new Error('folio is closed');
|
|
717
|
+
if (this.#busy)
|
|
718
|
+
throw new Error('memory already has an active run');
|
|
719
|
+
const run = { pool };
|
|
720
|
+
if (small)
|
|
721
|
+
run.reason = 'no-admission';
|
|
722
|
+
else if (!pool)
|
|
723
|
+
run.reason = 'workers-unavailable';
|
|
724
|
+
it.run = run;
|
|
725
|
+
let report;
|
|
726
|
+
try {
|
|
727
|
+
report = await this.runAll(call, { parallel: 'off' });
|
|
728
|
+
}
|
|
729
|
+
finally {
|
|
730
|
+
it.run = undefined;
|
|
731
|
+
}
|
|
732
|
+
const counts = run.iteration;
|
|
733
|
+
delete report.reason;
|
|
734
|
+
if (counts)
|
|
735
|
+
report.iteration = counts;
|
|
736
|
+
if (counts && counts.regions > 0) {
|
|
737
|
+
report.mode = 'speculative';
|
|
738
|
+
report.extraction = 'iteration';
|
|
739
|
+
report.memoryMode = 'shared';
|
|
740
|
+
report.workers = counts.workers;
|
|
741
|
+
report.regions = counts.regions;
|
|
742
|
+
report.replayed = counts.replayed;
|
|
743
|
+
report.fallbacks = counts.fallbacks;
|
|
744
|
+
if (report.profile) {
|
|
745
|
+
report.profile.validationMs = counts.validationMs;
|
|
746
|
+
report.profile.replayMs = counts.replayMs;
|
|
747
|
+
}
|
|
748
|
+
if (run.reason)
|
|
749
|
+
report.reason = run.reason;
|
|
750
|
+
else if (counts.replayed > 0)
|
|
751
|
+
report.reason = 'dependency';
|
|
752
|
+
}
|
|
753
|
+
else
|
|
754
|
+
report.reason = run.reason ?? 'no-parallel-plan';
|
|
755
|
+
return report;
|
|
756
|
+
}
|
|
757
|
+
// the host function the owner's loop calls: 1 when every iteration ran, 0 to run the loop itself
|
|
758
|
+
#iterate(values) {
|
|
759
|
+
const it = this.#iteration;
|
|
760
|
+
const run = it.run;
|
|
761
|
+
if (!run?.pool)
|
|
762
|
+
return 0;
|
|
763
|
+
const decline = (reason) => {
|
|
764
|
+
run.reason ??= reason;
|
|
765
|
+
return 0;
|
|
766
|
+
};
|
|
767
|
+
const route = it.route;
|
|
768
|
+
const pool = run.pool;
|
|
769
|
+
const entry = {};
|
|
770
|
+
it.owner.locals.forEach((local, index) => (entry[local] = values[index]));
|
|
771
|
+
const trip = Number(entry[route.trip.local]) >>> 0;
|
|
772
|
+
if (trip === 0)
|
|
773
|
+
return decline('trip-zero');
|
|
774
|
+
if (trip < 2)
|
|
775
|
+
return decline('no-admission');
|
|
776
|
+
if (it.memory.buffer.byteLength !== pool.arena.memoryBytes)
|
|
777
|
+
return decline('no-arena');
|
|
778
|
+
const frameBase = route.frame ? Number(entry[route.frame.local]) >>> 0 : 0;
|
|
779
|
+
const plain = (it.plain ??= this.#plain(it));
|
|
780
|
+
const replay = (k) => {
|
|
781
|
+
if (plain.stack && this.#ownerStack)
|
|
782
|
+
plain.stack.value = this.#ownerStack.value;
|
|
783
|
+
plain.iterate(...iterationArguments(route.locals, entry, k, frameBase));
|
|
784
|
+
};
|
|
785
|
+
try {
|
|
786
|
+
pool.run({
|
|
787
|
+
trip,
|
|
788
|
+
frameBase,
|
|
789
|
+
entry,
|
|
790
|
+
replay,
|
|
791
|
+
admit: (ms) => decideAdmission(ms, trip, pool.width),
|
|
792
|
+
loses: decideBatch,
|
|
793
|
+
collapses: decideCollapse
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
finally {
|
|
797
|
+
run.iteration = addCounts(run.iteration, pool.report);
|
|
798
|
+
}
|
|
799
|
+
if (pool.report.stopped)
|
|
800
|
+
run.reason ??= pool.report.stopped;
|
|
801
|
+
return 1;
|
|
802
|
+
}
|
|
803
|
+
// a plain instance of the worker module on the shared memory; replay runs iterations on it
|
|
804
|
+
#plain(it) {
|
|
805
|
+
const route = it.route;
|
|
806
|
+
const instance = new WebAssembly.Instance(new WebAssembly.Module(Uint8Array.from(route.module)), {
|
|
807
|
+
env: { memory: it.memory }
|
|
808
|
+
});
|
|
809
|
+
return {
|
|
810
|
+
stack: route.stackExport
|
|
811
|
+
? instance.exports[route.stackExport]
|
|
812
|
+
: undefined,
|
|
813
|
+
iterate: instance.exports[route.iterate]
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
#observeRouting(key, report) {
|
|
817
|
+
if (!key)
|
|
818
|
+
return;
|
|
819
|
+
const expensive = report.mode === 'speculative' &&
|
|
820
|
+
(report.fallbacks > 0 ||
|
|
821
|
+
(report.regions > 1 && report.replayed / (report.regions - 1) >= 0.5));
|
|
822
|
+
if (!expensive) {
|
|
823
|
+
this.#routing.delete(key);
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
const failures = Math.min(2, (this.#routing.get(key)?.failures ?? 0) + 1);
|
|
827
|
+
if (!this.#routing.has(key) && this.#routing.size >= 256)
|
|
828
|
+
this.#routing.delete(this.#routing.keys().next().value);
|
|
829
|
+
this.#routing.set(key, { failures, remaining: failures >= 2 ? 16 : 0 });
|
|
830
|
+
}
|
|
831
|
+
async #runControlled(entry, args, width) {
|
|
832
|
+
if (this.#closed)
|
|
833
|
+
throw new Error('folio is closed');
|
|
834
|
+
if (this.#failure)
|
|
835
|
+
throw this.#failure;
|
|
836
|
+
if (this.#busy)
|
|
837
|
+
throw new Error('memory already has an active run');
|
|
838
|
+
this.#busy = true;
|
|
839
|
+
const started = this.#profile ? performance.now() : 0;
|
|
840
|
+
const coordinator = new Coordinator({
|
|
841
|
+
memory: this.memory,
|
|
842
|
+
workerMemory: this.#workerMemory,
|
|
843
|
+
width,
|
|
844
|
+
profile: this.#profile,
|
|
845
|
+
pending: this.#queued,
|
|
846
|
+
dispatch: (worker, calls) => this.#dispatchBatch(this.#workers[worker], calls),
|
|
847
|
+
native: (call) => {
|
|
848
|
+
const previous = this.#serial.value;
|
|
849
|
+
this.#serial.value = 1;
|
|
850
|
+
try {
|
|
851
|
+
this.#instance.exports[call.export](...call.args);
|
|
852
|
+
}
|
|
853
|
+
finally {
|
|
854
|
+
this.#serial.value = previous;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
});
|
|
858
|
+
this.#coordinator = coordinator;
|
|
859
|
+
this.#serial.value = 0;
|
|
860
|
+
const pending = (async () => {
|
|
861
|
+
let value;
|
|
862
|
+
let failed = false;
|
|
863
|
+
let failure;
|
|
864
|
+
try {
|
|
865
|
+
value = await entry(...args);
|
|
866
|
+
}
|
|
867
|
+
catch (error) {
|
|
868
|
+
failed = true;
|
|
869
|
+
failure = error;
|
|
870
|
+
}
|
|
871
|
+
// If the original coordinator traps first, pending preceding regions still
|
|
872
|
+
// own the earlier effects/trap in program order.
|
|
873
|
+
await coordinator.flush();
|
|
874
|
+
if (failed)
|
|
875
|
+
throw failure;
|
|
876
|
+
coordinator.report.values = [value];
|
|
877
|
+
return coordinator.report;
|
|
878
|
+
})();
|
|
879
|
+
this.#nativePending.add(pending);
|
|
880
|
+
try {
|
|
881
|
+
return await pending;
|
|
882
|
+
}
|
|
883
|
+
finally {
|
|
884
|
+
if (coordinator.report.profile)
|
|
885
|
+
coordinator.report.profile.wallMs = performance.now() - started;
|
|
886
|
+
this.#nativePending.delete(pending);
|
|
887
|
+
this.#serial.value = 1;
|
|
888
|
+
this.#queued.value = 0;
|
|
889
|
+
this.#coordinator = undefined;
|
|
890
|
+
this.#busy = false;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
#disjoint(calls, proved, plan) {
|
|
894
|
+
const footprints = calls.map((call) => proved.accesses.map((access) => {
|
|
895
|
+
const first = Number(call.args[access.parameter]) >>> 0;
|
|
896
|
+
const count = Number(call.args[plan.countParameter]) >>> 0;
|
|
897
|
+
const step = plan.steps.find((item) => item.parameter === access.parameter)?.step ?? 0;
|
|
898
|
+
const last = first + (count - 1) * step;
|
|
899
|
+
return {
|
|
900
|
+
start: Math.min(first, last) + access.offset,
|
|
901
|
+
end: Math.max(first, last) + access.offset + access.bytes,
|
|
902
|
+
write: access.write,
|
|
903
|
+
wrap: last < 0 || last > 0xffffffff
|
|
904
|
+
};
|
|
905
|
+
}));
|
|
906
|
+
for (let i = 0; i < footprints.length; i++) {
|
|
907
|
+
for (const range of footprints[i]) {
|
|
908
|
+
if (range.wrap || range.start < 0 || range.end > this.memory.buffer.byteLength)
|
|
909
|
+
return false;
|
|
910
|
+
for (const other of footprints.slice(0, i).flat()) {
|
|
911
|
+
if ((range.write || other.write) &&
|
|
912
|
+
range.start < other.end &&
|
|
913
|
+
other.start < range.end)
|
|
914
|
+
return false;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return true;
|
|
919
|
+
}
|
|
920
|
+
async #nativeRegions(calls) {
|
|
921
|
+
if (this.#closed)
|
|
922
|
+
throw new Error('folio is closed');
|
|
923
|
+
if (this.#failure)
|
|
924
|
+
throw this.#failure;
|
|
925
|
+
if (this.#busy)
|
|
926
|
+
throw new Error('memory already has an active run');
|
|
927
|
+
this.#busy = true;
|
|
928
|
+
const started = this.#profile ? performance.now() : 0;
|
|
929
|
+
try {
|
|
930
|
+
const outcomes = await Promise.allSettled(calls.map((call, index) => this.#dispatch(this.#workers[index], call, true)));
|
|
931
|
+
for (const outcome of outcomes) {
|
|
932
|
+
if (outcome.status === 'rejected' || outcome.value.trap) {
|
|
933
|
+
this.#failure = new Error('native region failed; arena may contain partial writes');
|
|
934
|
+
await this.close();
|
|
935
|
+
throw this.#failure;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
const results = outcomes.map((outcome) => outcome.value);
|
|
939
|
+
return {
|
|
940
|
+
values: [],
|
|
941
|
+
workers: calls.length,
|
|
942
|
+
regions: calls.length,
|
|
943
|
+
replayed: 0,
|
|
944
|
+
fallbacks: 0,
|
|
945
|
+
mode: 'native-shared',
|
|
946
|
+
...(this.#profile
|
|
947
|
+
? {
|
|
948
|
+
profile: {
|
|
949
|
+
wallMs: performance.now() - started,
|
|
950
|
+
workerWallMs: results.map((r) => r.timing.wallMs),
|
|
951
|
+
workerCpuMs: results.map((r) => r.timing.cpuMs),
|
|
952
|
+
validationMs: 0,
|
|
953
|
+
commitMs: 0,
|
|
954
|
+
replayMs: 0,
|
|
955
|
+
readBytes: 0,
|
|
956
|
+
writeBytes: 0
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
: {})
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
finally {
|
|
963
|
+
this.#busy = false;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
/** Preserves call order while discovering memory dependencies at runtime. */
|
|
967
|
+
async runAll(calls, options = {}) {
|
|
968
|
+
const width = this.#width(options);
|
|
969
|
+
if (this.#closed)
|
|
970
|
+
throw new Error('folio is closed');
|
|
971
|
+
if (this.#failure)
|
|
972
|
+
throw this.#failure;
|
|
973
|
+
if (this.#busy)
|
|
974
|
+
throw new Error('memory already has an active run');
|
|
975
|
+
for (const call of calls) {
|
|
976
|
+
if (typeof this.#instance.exports[call.export] !== 'function')
|
|
977
|
+
throw new TypeError(`unknown function export: ${call.export}`);
|
|
978
|
+
}
|
|
979
|
+
this.#busy = true;
|
|
980
|
+
const started = this.#profile ? performance.now() : 0;
|
|
981
|
+
const report = {
|
|
982
|
+
values: [],
|
|
983
|
+
workers: 0,
|
|
984
|
+
regions: calls.length,
|
|
985
|
+
replayed: 0,
|
|
986
|
+
fallbacks: 0,
|
|
987
|
+
mode: 'serial'
|
|
988
|
+
};
|
|
989
|
+
const profile = this.#profile
|
|
990
|
+
? {
|
|
991
|
+
wallMs: 0,
|
|
992
|
+
workerWallMs: [],
|
|
993
|
+
workerCpuMs: [],
|
|
994
|
+
validationMs: 0,
|
|
995
|
+
commitMs: 0,
|
|
996
|
+
replayMs: 0,
|
|
997
|
+
readBytes: 0,
|
|
998
|
+
writeBytes: 0
|
|
999
|
+
}
|
|
1000
|
+
: undefined;
|
|
1001
|
+
if (profile)
|
|
1002
|
+
report.profile = profile;
|
|
1003
|
+
const observe = (result) => {
|
|
1004
|
+
if (!profile)
|
|
1005
|
+
return;
|
|
1006
|
+
profile.workerWallMs.push(result.timing.wallMs);
|
|
1007
|
+
profile.workerCpuMs.push(result.timing.cpuMs);
|
|
1008
|
+
profile.readBytes += result.reads.length;
|
|
1009
|
+
profile.writeBytes += result.writes.length;
|
|
1010
|
+
};
|
|
1011
|
+
const commit = (result, bytes, dirty) => {
|
|
1012
|
+
const before = profile ? performance.now() : 0;
|
|
1013
|
+
const shared = this.#workerMemory && this.#workerMemory !== this.#memory
|
|
1014
|
+
? new Uint8Array(this.#workerMemory.buffer)
|
|
1015
|
+
: undefined;
|
|
1016
|
+
for (const [address, value] of result.writes) {
|
|
1017
|
+
bytes[address] = value;
|
|
1018
|
+
if (shared)
|
|
1019
|
+
shared[address] = value;
|
|
1020
|
+
dirty.add(address);
|
|
1021
|
+
}
|
|
1022
|
+
if (profile)
|
|
1023
|
+
profile.commitMs += performance.now() - before;
|
|
1024
|
+
};
|
|
1025
|
+
try {
|
|
1026
|
+
const opaque = calls.some((call) => call.args.some((arg) => typeof arg !== 'number' && typeof arg !== 'bigint'));
|
|
1027
|
+
const unsupported = calls.some((call) => !this.#workerExports.has(call.export));
|
|
1028
|
+
if (width < 2 ||
|
|
1029
|
+
calls.length < 2 ||
|
|
1030
|
+
options.parallel === 'off' ||
|
|
1031
|
+
opaque ||
|
|
1032
|
+
unsupported) {
|
|
1033
|
+
report.reason =
|
|
1034
|
+
options.parallel === 'off'
|
|
1035
|
+
? 'requested'
|
|
1036
|
+
: opaque
|
|
1037
|
+
? 'opaque-input'
|
|
1038
|
+
: !this.#workers.length || unsupported
|
|
1039
|
+
? 'unsupported-module'
|
|
1040
|
+
: 'single-region';
|
|
1041
|
+
for (const call of calls)
|
|
1042
|
+
report.values.push((await this.#native(call)).value);
|
|
1043
|
+
return report;
|
|
1044
|
+
}
|
|
1045
|
+
report.mode = 'speculative';
|
|
1046
|
+
report.workers = Math.min(width, calls.length);
|
|
1047
|
+
for (let start = 0; start < calls.length; start += width) {
|
|
1048
|
+
const batch = calls.slice(start, start + width);
|
|
1049
|
+
if (this.#workerMemory && this.#workerMemory !== this.#memory) {
|
|
1050
|
+
try {
|
|
1051
|
+
const pages = this.memory.buffer.byteLength / 65536;
|
|
1052
|
+
const current = this.#workerMemory.buffer.byteLength / 65536;
|
|
1053
|
+
if (pages > current)
|
|
1054
|
+
this.#workerMemory.grow(pages - current);
|
|
1055
|
+
new Uint8Array(this.#workerMemory.buffer).set(new Uint8Array(this.memory.buffer));
|
|
1056
|
+
report.memoryMode = 'snapshot';
|
|
1057
|
+
report.snapshotBytes =
|
|
1058
|
+
(report.snapshotBytes ?? 0) + this.memory.buffer.byteLength;
|
|
1059
|
+
}
|
|
1060
|
+
catch (error) {
|
|
1061
|
+
if (!(error instanceof RangeError))
|
|
1062
|
+
throw error;
|
|
1063
|
+
report.fallbacks++;
|
|
1064
|
+
report.reason = 'snapshot-unavailable';
|
|
1065
|
+
if (start === 0) {
|
|
1066
|
+
report.mode = 'serial';
|
|
1067
|
+
report.workers = 0;
|
|
1068
|
+
}
|
|
1069
|
+
for (const call of calls.slice(start))
|
|
1070
|
+
report.values.push((await this.#native(call)).value);
|
|
1071
|
+
return report;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
const outcomes = await Promise.allSettled(batch.map((call, index) => this.#dispatch(this.#workers[index], call)));
|
|
1075
|
+
const failure = outcomes.find((outcome) => outcome.status === 'rejected');
|
|
1076
|
+
if (failure?.status === 'rejected') {
|
|
1077
|
+
await this.close();
|
|
1078
|
+
throw failure.reason;
|
|
1079
|
+
}
|
|
1080
|
+
const dirty = new Set();
|
|
1081
|
+
const bytes = new Uint8Array(this.memory.buffer);
|
|
1082
|
+
for (let index = 0; index < batch.length; index++) {
|
|
1083
|
+
const outcome = outcomes[index];
|
|
1084
|
+
if (outcome.status !== 'fulfilled')
|
|
1085
|
+
throw new Error('unreachable outcome');
|
|
1086
|
+
const result = outcome.value;
|
|
1087
|
+
observe(result);
|
|
1088
|
+
const validationStart = profile ? performance.now() : 0;
|
|
1089
|
+
const conflict = result.reads.some((address) => dirty.has(address));
|
|
1090
|
+
if (profile)
|
|
1091
|
+
profile.validationMs += performance.now() - validationStart;
|
|
1092
|
+
if (result.exhausted || conflict) {
|
|
1093
|
+
if (result.exhausted)
|
|
1094
|
+
report.fallbacks++;
|
|
1095
|
+
else {
|
|
1096
|
+
report.replayed++;
|
|
1097
|
+
report.reason = 'dependency';
|
|
1098
|
+
}
|
|
1099
|
+
// replay uses tracking so later validations include its actual writes
|
|
1100
|
+
const replayStart = profile ? performance.now() : 0;
|
|
1101
|
+
const replay = await this.#dispatch(this.#workers[0], batch[index]);
|
|
1102
|
+
observe(replay);
|
|
1103
|
+
if (profile)
|
|
1104
|
+
profile.replayMs += performance.now() - replayStart;
|
|
1105
|
+
if (replay.exhausted) {
|
|
1106
|
+
report.values.push((await this.#native(batch[index])).value);
|
|
1107
|
+
for (let rest = index + 1; rest < batch.length; rest++)
|
|
1108
|
+
report.values.push((await this.#native(batch[rest])).value);
|
|
1109
|
+
break;
|
|
1110
|
+
}
|
|
1111
|
+
commit(replay, bytes, dirty);
|
|
1112
|
+
throwTrap(replay);
|
|
1113
|
+
report.values.push(replay.value);
|
|
1114
|
+
}
|
|
1115
|
+
else {
|
|
1116
|
+
commit(result, bytes, dirty);
|
|
1117
|
+
throwTrap(result);
|
|
1118
|
+
report.values.push(result.value);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
return report;
|
|
1123
|
+
}
|
|
1124
|
+
finally {
|
|
1125
|
+
if (profile)
|
|
1126
|
+
profile.wallMs = performance.now() - started;
|
|
1127
|
+
this.#busy = false;
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
/** Joins worker termination and outstanding JSPI calls. Repeated calls share one join. */
|
|
1131
|
+
close() {
|
|
1132
|
+
if (this.#closing)
|
|
1133
|
+
return this.#closing;
|
|
1134
|
+
this.#closed = true;
|
|
1135
|
+
for (const pending of this.#pending.values())
|
|
1136
|
+
pending.reject(new Error('folio is closed'));
|
|
1137
|
+
this.#pending.clear();
|
|
1138
|
+
this.#closing = Promise.all([
|
|
1139
|
+
...this.#workers.map((worker) => worker.terminate()),
|
|
1140
|
+
...Array.from(this.#nativePending, (pending) => pending.catch(() => { })),
|
|
1141
|
+
...(this.#iteration
|
|
1142
|
+
? [
|
|
1143
|
+
(this.#iteration.opening ?? Promise.resolve()).then(() => this.#iteration.pool?.close())
|
|
1144
|
+
]
|
|
1145
|
+
: [])
|
|
1146
|
+
]).then(() => { });
|
|
1147
|
+
return this.#closing;
|
|
1148
|
+
}
|
|
1149
|
+
/** `await using` support; equivalent to `close()`. */
|
|
1150
|
+
[Symbol.asyncDispose]() {
|
|
1151
|
+
return this.close();
|
|
1152
|
+
}
|
|
1153
|
+
}
|