@gmitch215/folio 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +455 -26
- package/dist/affine-state.d.ts +171 -0
- package/dist/affine-state.js +763 -0
- package/dist/affine.d.ts +160 -0
- package/dist/affine.js +571 -0
- package/dist/bake.d.ts +8 -3
- package/dist/bake.js +5 -2
- package/dist/boundaries.d.ts +59 -0
- package/dist/boundaries.js +127 -0
- package/dist/certified.d.ts +66 -0
- package/dist/certified.js +192 -0
- package/dist/certify.d.ts +98 -0
- package/dist/certify.js +2628 -0
- package/dist/compiler.d.ts +37 -1
- package/dist/compiler.js +116 -1
- package/dist/context.d.ts +47 -0
- package/dist/context.js +139 -0
- package/dist/coordinator.d.ts +1 -1
- package/dist/coordinator.js +54 -5
- package/dist/extract.d.ts +114 -1
- package/dist/extract.js +1011 -242
- package/dist/fold.d.ts +32 -0
- package/dist/fold.js +105 -0
- package/dist/frames.d.ts +20 -2
- package/dist/frames.js +205 -10
- package/dist/inline.d.ts +182 -0
- package/dist/inline.js +766 -0
- package/dist/iteration-admission.d.ts +185 -0
- package/dist/iteration-admission.js +201 -0
- package/dist/iteration-layout.d.ts +135 -0
- package/dist/iteration-layout.js +169 -0
- package/dist/iteration-owner.d.ts +45 -0
- package/dist/iteration-owner.js +223 -0
- package/dist/iteration-worker.d.ts +1 -0
- package/dist/iteration-worker.js +216 -0
- package/dist/iteration.d.ts +329 -0
- package/dist/iteration.js +1210 -0
- package/dist/lease.d.ts +45 -0
- package/dist/lease.js +274 -0
- package/dist/managed.d.ts +78 -0
- package/dist/managed.js +448 -27
- package/dist/memo.d.ts +99 -0
- package/dist/memo.js +250 -0
- package/dist/node.d.ts +61 -5
- package/dist/node.js +421 -23
- package/dist/ownership-redirect.d.ts +30 -0
- package/dist/ownership-redirect.js +179 -0
- package/dist/ownership-slices.d.ts +44 -0
- package/dist/ownership-slices.js +72 -0
- package/dist/ownership.d.ts +161 -0
- package/dist/ownership.js +6568 -0
- package/dist/ranges.d.ts +78 -0
- package/dist/ranges.js +263 -0
- package/dist/read-scan.d.ts +18 -0
- package/dist/read-scan.js +94 -0
- package/dist/read-windows.d.ts +103 -0
- package/dist/read-windows.js +244 -0
- package/dist/router-worker.d.ts +1 -0
- package/dist/router-worker.js +4 -0
- package/dist/router.d.ts +203 -0
- package/dist/router.js +667 -0
- package/dist/runs.d.ts +44 -0
- package/dist/runs.js +182 -0
- package/dist/slices-worker.d.ts +1 -0
- package/dist/slices-worker.js +38 -0
- package/dist/slices.d.ts +126 -0
- package/dist/slices.js +441 -0
- package/dist/tasks.d.ts +14 -4
- package/dist/tasks.js +23 -9
- package/dist/transaction.d.ts +10 -0
- package/package.json +44 -4
package/dist/node.js
CHANGED
|
@@ -2,6 +2,8 @@ import { availableParallelism } from 'node:os';
|
|
|
2
2
|
import { isArrayBuffer, isSharedArrayBuffer, isUint8Array } from 'node:util/types';
|
|
3
3
|
import { Worker } from 'node:worker_threads';
|
|
4
4
|
import { Coordinator } from "./coordinator.js";
|
|
5
|
+
import { decideAdmission, decideBatch, decideBound, decideCollapse, decideProof, decideRemaining } from "./iteration-admission.js";
|
|
6
|
+
import { iterationArguments, iterationFit, iterationWindowBytes } from "./iteration-layout.js";
|
|
5
7
|
import { memoryImports } from "./memory.js";
|
|
6
8
|
import { numberBits, restoreNumbers } from "./values.js";
|
|
7
9
|
/** Wraps an asynchronous host import for Wasm stack suspension. */
|
|
@@ -29,6 +31,113 @@ function isMemory(value) {
|
|
|
29
31
|
return false;
|
|
30
32
|
}
|
|
31
33
|
}
|
|
34
|
+
const PAGE = 65536;
|
|
35
|
+
/** Calls that skip dispatch after a stop that one call recorded, before one tries again. */
|
|
36
|
+
const iterationReprobe = 16;
|
|
37
|
+
function addCounts(total, part) {
|
|
38
|
+
if (!total)
|
|
39
|
+
return structuredClone(part);
|
|
40
|
+
for (const key of Object.keys(part)) {
|
|
41
|
+
if (key === 'stopped')
|
|
42
|
+
total.stopped ??= part.stopped;
|
|
43
|
+
else if (key === 'windowRefused')
|
|
44
|
+
total.windowRefused ??= part.windowRefused;
|
|
45
|
+
else if (key === 'readWindowRefused')
|
|
46
|
+
total.readWindowRefused ??= part.readWindowRefused;
|
|
47
|
+
else if (key === 'readWindowGate')
|
|
48
|
+
total.readWindowGate ??= part.readWindowGate;
|
|
49
|
+
else if (key === 'readWindows') {
|
|
50
|
+
if (part.readWindows && total.readWindows)
|
|
51
|
+
total.readWindows.batches += part.readWindows.batches;
|
|
52
|
+
else
|
|
53
|
+
total.readWindows ??= part.readWindows;
|
|
54
|
+
}
|
|
55
|
+
else if (key === 'window') {
|
|
56
|
+
if (part.window && total.window)
|
|
57
|
+
total.window.batches += part.window.batches;
|
|
58
|
+
else
|
|
59
|
+
total.window ??= part.window;
|
|
60
|
+
}
|
|
61
|
+
else if (key === 'admission')
|
|
62
|
+
total.admission = part.admission ?? total.admission;
|
|
63
|
+
else if (key === 'workers')
|
|
64
|
+
total.workers = Math.max(total.workers, part.workers);
|
|
65
|
+
else if (key === 'maxLogEntries')
|
|
66
|
+
total.maxLogEntries = Math.max(total.maxLogEntries, part.maxLogEntries);
|
|
67
|
+
else if (key === 'conflicts') {
|
|
68
|
+
total.conflicts.raw += part.conflicts.raw;
|
|
69
|
+
total.conflicts.war += part.conflicts.war;
|
|
70
|
+
total.conflicts.waw += part.conflicts.waw;
|
|
71
|
+
total.conflicts.frame += part.conflicts.frame;
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
total[key] += part[key];
|
|
75
|
+
}
|
|
76
|
+
return total;
|
|
77
|
+
}
|
|
78
|
+
// true when the host supplies the memory import through `imports`, or it cannot be told safely
|
|
79
|
+
function suppliesMemory(imports, module, name) {
|
|
80
|
+
if (!imports || !(module in imports))
|
|
81
|
+
return false;
|
|
82
|
+
const descriptor = Object.getOwnPropertyDescriptor(imports, module);
|
|
83
|
+
if (!descriptor || !('value' in descriptor))
|
|
84
|
+
return true;
|
|
85
|
+
const value = descriptor.value;
|
|
86
|
+
return value !== null && ['object', 'function'].includes(typeof value) && name in value;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Chooses the iteration route for a program no older route covers, and builds its owner module and
|
|
90
|
+
* shared memory. A refusal names its reason; a program that is not a candidate returns nothing.
|
|
91
|
+
*/
|
|
92
|
+
async function selectIteration(program, options, size) {
|
|
93
|
+
const route = program.iterationRoute;
|
|
94
|
+
if (!route?.eligible ||
|
|
95
|
+
size < 2 ||
|
|
96
|
+
program.control ||
|
|
97
|
+
program.compiled ||
|
|
98
|
+
Object.keys(program.loops).length ||
|
|
99
|
+
Object.keys(program.native ?? {}).length)
|
|
100
|
+
return;
|
|
101
|
+
const refuse = (reason, detail) => ({ reason, detail });
|
|
102
|
+
const { iterationOwner } = await import("./iteration-owner.js");
|
|
103
|
+
const built = iterationOwner(program.original, route, program.stackRoute?.stack?.name);
|
|
104
|
+
if (!('owner' in built))
|
|
105
|
+
return built;
|
|
106
|
+
const owner = built.owner;
|
|
107
|
+
if (suppliesMemory(options.imports, owner.memory.module, owner.memory.name))
|
|
108
|
+
return refuse('no-arena', 'the memory import is supplied through imports');
|
|
109
|
+
if (options.memory && !isMemory(options.memory))
|
|
110
|
+
return;
|
|
111
|
+
if (options.memory && !isSharedArrayBuffer(options.memory.buffer))
|
|
112
|
+
return refuse('no-arena', 'the host memory is not shared');
|
|
113
|
+
const start = options.memory ? options.memory.buffer.byteLength : owner.memory.initial * PAGE;
|
|
114
|
+
const fit = iterationFit(start, {
|
|
115
|
+
frameBytes: route.frame?.size,
|
|
116
|
+
windowBytes: iterationWindowBytes,
|
|
117
|
+
readSummary: Boolean(options.iterationReadSummary)
|
|
118
|
+
});
|
|
119
|
+
if (!fit)
|
|
120
|
+
return refuse('no-arena', 'the arena does not fit in 65536 pages');
|
|
121
|
+
if (owner.memory.maximum !== undefined && fit.pages > owner.memory.maximum)
|
|
122
|
+
return refuse('no-arena', `the declared maximum of ${owner.memory.maximum} pages is below the ${fit.pages} the arena needs`);
|
|
123
|
+
let memory = options.memory;
|
|
124
|
+
try {
|
|
125
|
+
if (memory)
|
|
126
|
+
memory.grow(fit.pages - start / PAGE);
|
|
127
|
+
else
|
|
128
|
+
memory = new WebAssembly.Memory({
|
|
129
|
+
initial: fit.pages,
|
|
130
|
+
maximum: Math.max(owner.memory.maximum ?? fit.pages, fit.pages),
|
|
131
|
+
shared: true
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (!(error instanceof RangeError))
|
|
136
|
+
throw error;
|
|
137
|
+
return refuse('no-arena', `memory cannot hold an arena of ${fit.bytes} bytes`);
|
|
138
|
+
}
|
|
139
|
+
return { route, verdicts: new Map(), owner, memory, arenaBase: fit.base, size };
|
|
140
|
+
}
|
|
32
141
|
function throwTrap(result) {
|
|
33
142
|
if (!result.trap)
|
|
34
143
|
return;
|
|
@@ -43,13 +152,19 @@ export class Folio {
|
|
|
43
152
|
/** Active sharing, extraction and validation mode; a one-worker pool reports none and serial. */
|
|
44
153
|
get capabilities() {
|
|
45
154
|
return Object.freeze({
|
|
46
|
-
physicalSharing: this.#workers.length
|
|
47
|
-
|
|
48
|
-
? this.#control
|
|
49
|
-
? 'control-flow'
|
|
50
|
-
: 'counted-loops'
|
|
155
|
+
physicalSharing: this.#workers.length || this.#iteration
|
|
156
|
+
? 'same-process'
|
|
51
157
|
: 'none',
|
|
52
|
-
|
|
158
|
+
automaticRegions: this.#iteration
|
|
159
|
+
? 'iteration'
|
|
160
|
+
: this.#workers.length
|
|
161
|
+
? this.#control
|
|
162
|
+
? 'control-flow'
|
|
163
|
+
: 'counted-loops'
|
|
164
|
+
: 'none',
|
|
165
|
+
dependence: this.#workers.length || this.#iteration
|
|
166
|
+
? 'ordered-validation'
|
|
167
|
+
: 'serial'
|
|
53
168
|
});
|
|
54
169
|
}
|
|
55
170
|
/** The original native exports, for trusted host integration. Raw calls bypass tracking. */
|
|
@@ -93,6 +208,9 @@ export class Folio {
|
|
|
93
208
|
});
|
|
94
209
|
}
|
|
95
210
|
#memory;
|
|
211
|
+
#iteration;
|
|
212
|
+
#ownerStack;
|
|
213
|
+
#refusal;
|
|
96
214
|
#workerMemory;
|
|
97
215
|
#control;
|
|
98
216
|
#serial;
|
|
@@ -115,17 +233,37 @@ export class Folio {
|
|
|
115
233
|
#maxBytes;
|
|
116
234
|
#minimumWork;
|
|
117
235
|
#profile;
|
|
236
|
+
#adaptive;
|
|
237
|
+
#logCeiling;
|
|
238
|
+
#readWindows;
|
|
239
|
+
#readSummary;
|
|
240
|
+
#stall;
|
|
241
|
+
#secondChance;
|
|
242
|
+
#routing = new Map();
|
|
118
243
|
#nextId = 0;
|
|
119
244
|
#busy = false;
|
|
120
245
|
#closed = false;
|
|
121
246
|
#closing;
|
|
122
247
|
#failure;
|
|
123
|
-
constructor(program, options, size) {
|
|
248
|
+
constructor(program, options, size, choice) {
|
|
124
249
|
this.#program = program;
|
|
250
|
+
if (choice && 'owner' in choice)
|
|
251
|
+
this.#iteration = choice;
|
|
252
|
+
else if (choice) {
|
|
253
|
+
this.#refusal = choice;
|
|
254
|
+
this.#runtimeDiagnostics.push(`iteration route refused: ${choice.detail}`);
|
|
255
|
+
}
|
|
256
|
+
const iteration = this.#iteration;
|
|
125
257
|
this.#fuel = options.fuel ?? 100_000_000;
|
|
126
258
|
this.#maxBytes = options.maxTransactionBytes ?? 262_144;
|
|
127
259
|
this.#minimumWork = options.minimumParallelWork ?? 100_000;
|
|
128
260
|
this.#profile = options.profile ?? false;
|
|
261
|
+
this.#adaptive = options.adaptiveRouting ?? false;
|
|
262
|
+
this.#logCeiling = options.iterationLogCeiling;
|
|
263
|
+
this.#readWindows = Boolean(options.iterationReadWindows);
|
|
264
|
+
this.#readSummary = Boolean(options.iterationReadSummary);
|
|
265
|
+
this.#stall = options.iterationStall;
|
|
266
|
+
this.#secondChance = Boolean(options.iterationSecondChance);
|
|
129
267
|
if (!Number.isInteger(this.#fuel) || this.#fuel < 2 || this.#fuel > 2_147_483_647)
|
|
130
268
|
throw new RangeError('invalid fuel');
|
|
131
269
|
if (!Number.isInteger(this.#maxBytes) || this.#maxBytes < 1)
|
|
@@ -150,6 +288,10 @@ export class Folio {
|
|
|
150
288
|
else
|
|
151
289
|
this.#runtimeDiagnostics.push('control extraction retained native binding order: rewritten import sequence differs');
|
|
152
290
|
}
|
|
291
|
+
if (iteration) {
|
|
292
|
+
executable = new WebAssembly.Module(Uint8Array.from(iteration.owner.module));
|
|
293
|
+
this.#runtimeDiagnostics.push(`iteration route: ${iteration.route.diagnostics.join('; ')}`);
|
|
294
|
+
}
|
|
153
295
|
const imported = WebAssembly.Module.imports(native).filter((item) => item.kind === 'memory');
|
|
154
296
|
if (imported.length > 1 && options.memory)
|
|
155
297
|
throw new TypeError('bind multiple memories by name in imports');
|
|
@@ -161,6 +303,7 @@ export class Folio {
|
|
|
161
303
|
const supplied = options.imports ?? Object.create(null);
|
|
162
304
|
const automatic = new Map();
|
|
163
305
|
let controlBindings;
|
|
306
|
+
let iterationBindings;
|
|
164
307
|
// Resolve bindings when the engine asks for them, in its original order.
|
|
165
308
|
// Enumerating/spreading caller namespaces would invoke accessors early or twice.
|
|
166
309
|
const imports = new Proxy(Object.create(null), {
|
|
@@ -188,6 +331,10 @@ export class Folio {
|
|
|
188
331
|
}
|
|
189
332
|
return (controlBindings = bindings);
|
|
190
333
|
}
|
|
334
|
+
if (iteration && module === iteration.owner.namespace)
|
|
335
|
+
return (iterationBindings ??= {
|
|
336
|
+
iterate: (...values) => this.#iterate(values)
|
|
337
|
+
});
|
|
191
338
|
const namespace = Reflect.get(supplied, module, supplied);
|
|
192
339
|
const memories = imported.filter((item) => item.module === module);
|
|
193
340
|
if (!memories.length ||
|
|
@@ -201,10 +348,12 @@ export class Folio {
|
|
|
201
348
|
return namespace === undefined
|
|
202
349
|
? undefined
|
|
203
350
|
: Reflect.get(namespace, name, namespace);
|
|
204
|
-
let bound =
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
351
|
+
let bound = iteration
|
|
352
|
+
? iteration.memory
|
|
353
|
+
: (options.memory ??
|
|
354
|
+
(namespace === undefined
|
|
355
|
+
? undefined
|
|
356
|
+
: Reflect.get(namespace, name, namespace)));
|
|
208
357
|
if (bound === undefined) {
|
|
209
358
|
const key = JSON.stringify([module, name]);
|
|
210
359
|
bound = automatic.get(key);
|
|
@@ -242,7 +391,15 @@ export class Folio {
|
|
|
242
391
|
if (!runtime.promising)
|
|
243
392
|
throw new Error('this runtime does not support JSPI');
|
|
244
393
|
}
|
|
245
|
-
|
|
394
|
+
try {
|
|
395
|
+
this.#instance = new WebAssembly.Instance(executable, imports);
|
|
396
|
+
}
|
|
397
|
+
catch (error) {
|
|
398
|
+
if (error instanceof WebAssembly.LinkError &&
|
|
399
|
+
/shared state of memory/.test(error.message))
|
|
400
|
+
throw new TypeError('the host memory and the program memory import differ in shared state; pass a shared memory only for a program the route can run on one');
|
|
401
|
+
throw error;
|
|
402
|
+
}
|
|
246
403
|
if (this.#control) {
|
|
247
404
|
this.#exports = Object.create(null);
|
|
248
405
|
for (const item of WebAssembly.Module.exports(native)) {
|
|
@@ -259,6 +416,18 @@ export class Folio {
|
|
|
259
416
|
this.#controlled.set(entry, runtime.promising(this.#instance.exports[entry]));
|
|
260
417
|
}
|
|
261
418
|
}
|
|
419
|
+
else if (iteration) {
|
|
420
|
+
this.#exports = Object.create(null);
|
|
421
|
+
for (const item of WebAssembly.Module.exports(native)) {
|
|
422
|
+
Object.defineProperty(this.#exports, item.name, {
|
|
423
|
+
value: this.#instance.exports[item.name],
|
|
424
|
+
enumerable: true
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
Object.preventExtensions(this.#exports);
|
|
428
|
+
if (iteration.owner.stackExport)
|
|
429
|
+
this.#ownerStack = this.#instance.exports[iteration.owner.stackExport];
|
|
430
|
+
}
|
|
262
431
|
else
|
|
263
432
|
this.#exports = this.#instance.exports;
|
|
264
433
|
for (const [name, value] of Object.entries(this.#exports)) {
|
|
@@ -294,7 +463,7 @@ export class Folio {
|
|
|
294
463
|
const size = options.workers ?? Math.min(4, availableParallelism());
|
|
295
464
|
if (!Number.isInteger(size) || size < 1 || size > 64)
|
|
296
465
|
throw new RangeError('invalid worker count');
|
|
297
|
-
const pool = new Folio(program, options, size);
|
|
466
|
+
const pool = new Folio(program, options, size, await selectIteration(program, options, size));
|
|
298
467
|
const transactional = pool.#control?.transactional ?? program.transactional;
|
|
299
468
|
if (!transactional || size === 1)
|
|
300
469
|
return pool;
|
|
@@ -382,7 +551,7 @@ export class Folio {
|
|
|
382
551
|
const entry = this.#instance.exports[call.export];
|
|
383
552
|
if (typeof entry !== 'function')
|
|
384
553
|
throw new TypeError(`unknown function export: ${call.export}`);
|
|
385
|
-
const wrapped = this.#promising.get(call.export);
|
|
554
|
+
const wrapped = this.#promising.get(call.export) ?? this.#controlled.get(call.export);
|
|
386
555
|
if (!wrapped)
|
|
387
556
|
return { value: entry(...call.args) };
|
|
388
557
|
const pending = wrapped(...call.args);
|
|
@@ -457,13 +626,37 @@ export class Folio {
|
|
|
457
626
|
: undefined;
|
|
458
627
|
const numeric = args.every((arg) => typeof arg === 'number');
|
|
459
628
|
const control = this.#controlled.get(entry);
|
|
629
|
+
const routeKey = this.#adaptive &&
|
|
630
|
+
options.parallel !== 'off' &&
|
|
631
|
+
options.parallel !== 'speculate' &&
|
|
632
|
+
width >= 2 &&
|
|
633
|
+
(plan || control) &&
|
|
634
|
+
args.every((arg) => typeof arg === 'number' || typeof arg === 'bigint')
|
|
635
|
+
? JSON.stringify([
|
|
636
|
+
entry,
|
|
637
|
+
width,
|
|
638
|
+
this.#memory?.buffer.byteLength,
|
|
639
|
+
args.map((arg) => (typeof arg === 'bigint' ? `${arg}n` : arg))
|
|
640
|
+
])
|
|
641
|
+
: undefined;
|
|
642
|
+
const history = routeKey ? this.#routing.get(routeKey) : undefined;
|
|
643
|
+
if (history && history.remaining > 0) {
|
|
644
|
+
history.remaining--;
|
|
645
|
+
const report = await this.runAll([{ export: entry, args }], { parallel: 'off' });
|
|
646
|
+
report.reason = 'previous-conflicts';
|
|
647
|
+
return report;
|
|
648
|
+
}
|
|
460
649
|
if (!plan &&
|
|
461
650
|
control &&
|
|
462
651
|
width >= 2 &&
|
|
463
652
|
options.parallel !== 'off' &&
|
|
464
653
|
args.every((arg) => typeof arg === 'number' || typeof arg === 'bigint')) {
|
|
465
|
-
|
|
654
|
+
const report = await this.#runControlled(control, args, width);
|
|
655
|
+
this.#observeRouting(routeKey, report);
|
|
656
|
+
return report;
|
|
466
657
|
}
|
|
658
|
+
if (!plan && this.#iteration && options.parallel !== 'off')
|
|
659
|
+
return this.#runIteration(entry, args, options);
|
|
467
660
|
const count = numeric && plan && typeof args[plan.countParameter] === 'number'
|
|
468
661
|
? Number(args[plan.countParameter]) >>> 0
|
|
469
662
|
: 0;
|
|
@@ -475,13 +668,15 @@ export class Folio {
|
|
|
475
668
|
report.reason =
|
|
476
669
|
options.parallel === 'off'
|
|
477
670
|
? 'requested'
|
|
478
|
-
: !
|
|
479
|
-
?
|
|
480
|
-
: !
|
|
481
|
-
? '
|
|
482
|
-
: !
|
|
483
|
-
? '
|
|
484
|
-
:
|
|
671
|
+
: !plan && this.#refusal
|
|
672
|
+
? this.#refusal.reason
|
|
673
|
+
: !numeric
|
|
674
|
+
? 'opaque-input'
|
|
675
|
+
: !this.#workers.length
|
|
676
|
+
? 'unsupported-module'
|
|
677
|
+
: !plan
|
|
678
|
+
? 'no-parallel-plan'
|
|
679
|
+
: 'single-region';
|
|
485
680
|
return report;
|
|
486
681
|
}
|
|
487
682
|
if (options.parallel !== 'speculate' && work !== undefined && work < this.#minimumWork) {
|
|
@@ -509,8 +704,206 @@ export class Folio {
|
|
|
509
704
|
: await this.runAll(calls, options);
|
|
510
705
|
if (proved && !disjoint && options.parallel !== 'speculate' && !report.reason)
|
|
511
706
|
report.reason = 'guard-failed';
|
|
707
|
+
this.#observeRouting(routeKey, report);
|
|
512
708
|
return { ...report, values: [undefined] };
|
|
513
709
|
}
|
|
710
|
+
// the workers of the iteration route start at the first call that may dispatch
|
|
711
|
+
#iterationPool(width) {
|
|
712
|
+
const it = this.#iteration;
|
|
713
|
+
const opened = (it.opening ?? Promise.resolve()).then(async () => {
|
|
714
|
+
if (this.#closed || it.disabled || it.pool?.width === width)
|
|
715
|
+
return;
|
|
716
|
+
await it.pool?.close();
|
|
717
|
+
it.pool = undefined;
|
|
718
|
+
try {
|
|
719
|
+
const { IterationPool } = await import("./iteration.js");
|
|
720
|
+
it.pool = await IterationPool.open(it.route, it.memory, {
|
|
721
|
+
arenaBase: it.arenaBase,
|
|
722
|
+
windowBytes: iterationWindowBytes,
|
|
723
|
+
width,
|
|
724
|
+
...(this.#logCeiling === undefined ? {} : { logCeiling: this.#logCeiling }),
|
|
725
|
+
...(this.#readWindows ? { readWindows: true } : {}),
|
|
726
|
+
...(this.#readSummary ? { readSummary: true } : {}),
|
|
727
|
+
...(this.#stall ? { stall: this.#stall } : {})
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
it.disabled = true;
|
|
732
|
+
this.#runtimeDiagnostics.push(`iteration workers unavailable: ${error instanceof Error ? error.message : String(error)}`);
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
it.opening = opened.catch(() => { });
|
|
736
|
+
return opened.then(() => it.pool);
|
|
737
|
+
}
|
|
738
|
+
async #runIteration(entry, args, options) {
|
|
739
|
+
const it = this.#iteration;
|
|
740
|
+
if (this.#closed)
|
|
741
|
+
throw new Error('folio is closed');
|
|
742
|
+
if (this.#failure)
|
|
743
|
+
throw this.#failure;
|
|
744
|
+
if (this.#busy)
|
|
745
|
+
throw new Error('memory already has an active run');
|
|
746
|
+
const limit = options.maximumWorkers ?? it.size;
|
|
747
|
+
if (options.maximumWorkers !== undefined &&
|
|
748
|
+
(!Number.isInteger(limit) || limit < 1 || limit > 64))
|
|
749
|
+
throw new RangeError('invalid maximumWorkers');
|
|
750
|
+
const width = Math.min(limit, it.size);
|
|
751
|
+
const call = [{ export: entry, args }];
|
|
752
|
+
if (width < 2) {
|
|
753
|
+
const report = await this.runAll(call, { parallel: 'off' });
|
|
754
|
+
report.reason = 'single-region';
|
|
755
|
+
return report;
|
|
756
|
+
}
|
|
757
|
+
const route = it.route;
|
|
758
|
+
const parameter = route.trip?.parameter;
|
|
759
|
+
const small = entry === route.owner &&
|
|
760
|
+
parameter !== undefined &&
|
|
761
|
+
typeof args[parameter] === 'number' &&
|
|
762
|
+
Number(args[parameter]) >>> 0 < 2;
|
|
763
|
+
const pool = small ? undefined : await this.#iterationPool(width);
|
|
764
|
+
if (this.#closed)
|
|
765
|
+
throw new Error('folio is closed');
|
|
766
|
+
if (this.#busy)
|
|
767
|
+
throw new Error('memory already has an active run');
|
|
768
|
+
const run = { pool };
|
|
769
|
+
if (small)
|
|
770
|
+
run.reason = 'no-admission';
|
|
771
|
+
else if (!pool)
|
|
772
|
+
run.reason = 'workers-unavailable';
|
|
773
|
+
it.run = run;
|
|
774
|
+
let report;
|
|
775
|
+
try {
|
|
776
|
+
report = await this.runAll(call, { parallel: 'off' });
|
|
777
|
+
}
|
|
778
|
+
finally {
|
|
779
|
+
it.run = undefined;
|
|
780
|
+
}
|
|
781
|
+
const counts = run.iteration;
|
|
782
|
+
delete report.reason;
|
|
783
|
+
if (counts)
|
|
784
|
+
report.iteration = counts;
|
|
785
|
+
if (counts && counts.regions > 0) {
|
|
786
|
+
report.mode = 'speculative';
|
|
787
|
+
report.extraction = 'iteration';
|
|
788
|
+
report.memoryMode = 'shared';
|
|
789
|
+
report.workers = counts.workers;
|
|
790
|
+
report.regions = counts.regions;
|
|
791
|
+
report.replayed = counts.replayed;
|
|
792
|
+
report.fallbacks = counts.fallbacks;
|
|
793
|
+
if (report.profile) {
|
|
794
|
+
report.profile.validationMs = counts.validationMs;
|
|
795
|
+
report.profile.replayMs = counts.replayMs;
|
|
796
|
+
}
|
|
797
|
+
if (run.reason)
|
|
798
|
+
report.reason = run.reason;
|
|
799
|
+
else if (counts.replayed > 0)
|
|
800
|
+
report.reason = 'dependency';
|
|
801
|
+
}
|
|
802
|
+
else
|
|
803
|
+
report.reason = run.reason ?? 'no-parallel-plan';
|
|
804
|
+
return report;
|
|
805
|
+
}
|
|
806
|
+
// the host function the owner's loop calls: 1 when every iteration ran, 0 to run the loop itself
|
|
807
|
+
#iterate(values) {
|
|
808
|
+
const it = this.#iteration;
|
|
809
|
+
const run = it.run;
|
|
810
|
+
if (!run?.pool)
|
|
811
|
+
return 0;
|
|
812
|
+
const decline = (reason) => {
|
|
813
|
+
run.reason ??= reason;
|
|
814
|
+
return 0;
|
|
815
|
+
};
|
|
816
|
+
const route = it.route;
|
|
817
|
+
const pool = run.pool;
|
|
818
|
+
const secondChance = this.#secondChance;
|
|
819
|
+
const entry = {};
|
|
820
|
+
it.owner.locals.forEach((local, index) => (entry[local] = values[index]));
|
|
821
|
+
const trip = Number(entry[route.trip.local]) >>> 0;
|
|
822
|
+
if (trip === 0)
|
|
823
|
+
return decline('trip-zero');
|
|
824
|
+
if (trip < 2)
|
|
825
|
+
return decline('no-admission');
|
|
826
|
+
if (it.memory.buffer.byteLength !== pool.memoryBytes)
|
|
827
|
+
return decline('no-arena');
|
|
828
|
+
const key = `${route.owner}|${pool.width}|${this.#logCeiling ?? ''}`;
|
|
829
|
+
const known = it.verdicts.get(key);
|
|
830
|
+
if (known?.stop) {
|
|
831
|
+
if (known.skipped++ < iterationReprobe)
|
|
832
|
+
return decline(known.stop);
|
|
833
|
+
it.verdicts.delete(key);
|
|
834
|
+
}
|
|
835
|
+
const frameBase = route.frame ? Number(entry[route.frame.local]) >>> 0 : 0;
|
|
836
|
+
const plain = (it.plain ??= this.#plain(it));
|
|
837
|
+
const replay = (k) => {
|
|
838
|
+
if (plain.stack && this.#ownerStack)
|
|
839
|
+
plain.stack.value = this.#ownerStack.value;
|
|
840
|
+
plain.iterate(...iterationArguments(route.locals, entry, k, frameBase));
|
|
841
|
+
};
|
|
842
|
+
try {
|
|
843
|
+
pool.run({
|
|
844
|
+
trip,
|
|
845
|
+
frameBase,
|
|
846
|
+
entry,
|
|
847
|
+
replay,
|
|
848
|
+
window: known?.window,
|
|
849
|
+
admit: (ms) => decideAdmission(ms, trip, pool.width, secondChance),
|
|
850
|
+
loses: decideBatch,
|
|
851
|
+
collapses: decideCollapse,
|
|
852
|
+
hopeless: decideBound,
|
|
853
|
+
unproven: decideProof,
|
|
854
|
+
reconsider: (ms, remaining, last) => decideRemaining(ms, remaining, pool.width, secondChance ? last : undefined)
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
finally {
|
|
858
|
+
run.iteration = addCounts(run.iteration, pool.report);
|
|
859
|
+
}
|
|
860
|
+
const stopped = pool.report.stopped;
|
|
861
|
+
if (stopped)
|
|
862
|
+
run.reason ??= stopped;
|
|
863
|
+
const structural = stopped === 'dependency' ||
|
|
864
|
+
stopped === 'log-exhausted' ||
|
|
865
|
+
stopped === 'frame-carried dependence' ||
|
|
866
|
+
stopped === 'stalled';
|
|
867
|
+
const w = pool.report.window;
|
|
868
|
+
const learned = w?.source === 'discovered' && !w.batches;
|
|
869
|
+
if (structural && !learned)
|
|
870
|
+
it.verdicts.set(key, { stop: stopped, skipped: 0 });
|
|
871
|
+
else if (pool.report.admission?.probeLost)
|
|
872
|
+
it.verdicts.set(key, { stop: 'no-admission', skipped: 0 });
|
|
873
|
+
else if (w && (w.batches || learned))
|
|
874
|
+
it.verdicts.set(key, { window: { low: w.low, end: w.end }, skipped: 0 });
|
|
875
|
+
else if (known)
|
|
876
|
+
it.verdicts.delete(key);
|
|
877
|
+
return 1;
|
|
878
|
+
}
|
|
879
|
+
// a plain instance of the worker module on the shared memory; replay runs iterations on it
|
|
880
|
+
#plain(it) {
|
|
881
|
+
const route = it.route;
|
|
882
|
+
const instance = new WebAssembly.Instance(new WebAssembly.Module(Uint8Array.from(route.module)), {
|
|
883
|
+
env: { memory: it.memory }
|
|
884
|
+
});
|
|
885
|
+
return {
|
|
886
|
+
stack: route.stackExport
|
|
887
|
+
? instance.exports[route.stackExport]
|
|
888
|
+
: undefined,
|
|
889
|
+
iterate: instance.exports[route.iterate]
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
#observeRouting(key, report) {
|
|
893
|
+
if (!key)
|
|
894
|
+
return;
|
|
895
|
+
const expensive = report.mode === 'speculative' &&
|
|
896
|
+
(report.fallbacks > 0 ||
|
|
897
|
+
(report.regions > 1 && report.replayed / (report.regions - 1) >= 0.5));
|
|
898
|
+
if (!expensive) {
|
|
899
|
+
this.#routing.delete(key);
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
const failures = Math.min(2, (this.#routing.get(key)?.failures ?? 0) + 1);
|
|
903
|
+
if (!this.#routing.has(key) && this.#routing.size >= 256)
|
|
904
|
+
this.#routing.delete(this.#routing.keys().next().value);
|
|
905
|
+
this.#routing.set(key, { failures, remaining: failures >= 2 ? 16 : 0 });
|
|
906
|
+
}
|
|
514
907
|
async #runControlled(entry, args, width) {
|
|
515
908
|
if (this.#closed)
|
|
516
909
|
throw new Error('folio is closed');
|
|
@@ -820,7 +1213,12 @@ export class Folio {
|
|
|
820
1213
|
this.#pending.clear();
|
|
821
1214
|
this.#closing = Promise.all([
|
|
822
1215
|
...this.#workers.map((worker) => worker.terminate()),
|
|
823
|
-
...Array.from(this.#nativePending, (pending) => pending.catch(() => { }))
|
|
1216
|
+
...Array.from(this.#nativePending, (pending) => pending.catch(() => { })),
|
|
1217
|
+
...(this.#iteration
|
|
1218
|
+
? [
|
|
1219
|
+
(this.#iteration.opening ?? Promise.resolve()).then(() => this.#iteration.pool?.close())
|
|
1220
|
+
]
|
|
1221
|
+
: [])
|
|
824
1222
|
]).then(() => { });
|
|
825
1223
|
return this.#closing;
|
|
826
1224
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type IterationRoute, type OwnershipPlan } from './extract.ts';
|
|
2
|
+
import { type OwnershipCertificate } from './ownership.ts';
|
|
3
|
+
export type RedirectErrorCode = 'unbound' | 'stale' | 'invalid' | 'unsupported';
|
|
4
|
+
export declare class OwnershipRedirectError extends Error {
|
|
5
|
+
readonly code: RedirectErrorCode;
|
|
6
|
+
constructor(code: RedirectErrorCode, detail: string);
|
|
7
|
+
}
|
|
8
|
+
export interface RedirectStats {
|
|
9
|
+
redirected: number;
|
|
10
|
+
skipped: number;
|
|
11
|
+
bulk: number;
|
|
12
|
+
straddle: number;
|
|
13
|
+
functions: number;
|
|
14
|
+
}
|
|
15
|
+
export interface OwnershipRedirect {
|
|
16
|
+
module: Uint8Array;
|
|
17
|
+
plan: OwnershipPlan;
|
|
18
|
+
stats: RedirectStats;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Rewrites the closure of a certified module so each window access adds a per-worker delta. The
|
|
22
|
+
* delta globals start at 0, so the module still runs in place. Throws `OwnershipRedirectError`
|
|
23
|
+
* when the certificate does not bind to the bytes or the module cannot be rewritten.
|
|
24
|
+
*/
|
|
25
|
+
export declare function redirectOwnership(bytes: Uint8Array, certificate: OwnershipCertificate): OwnershipRedirect;
|
|
26
|
+
/** The iteration route of the redirected module, with the plan the executor needs. */
|
|
27
|
+
export declare function ownershipRoute(bytes: Uint8Array, certificate: OwnershipCertificate): {
|
|
28
|
+
route: IterationRoute;
|
|
29
|
+
redirect: OwnershipRedirect;
|
|
30
|
+
};
|