@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/managed.js
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { Coordinator } from "./coordinator.js";
|
|
2
|
+
import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, snapshotLength, validateIdentity } from "./frames.js";
|
|
3
|
+
import { SpeculationLimit, transaction } from "./transaction.js";
|
|
4
|
+
// workers rpc rejects serialized arguments over 32 MiB; the margin covers the other arguments and serializer tags
|
|
5
|
+
const rpcFrameLimit = 32 * 1048576 - 4096;
|
|
6
|
+
function integer(value, minimum, maximum, label) {
|
|
7
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
8
|
+
throw new RangeError(`invalid ${label}`);
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The lane runtime: runs tracked regions from a binary frame against a private copy of the
|
|
13
|
+
* frozen snapshot and returns byte read and write sets. Holds no state between frames.
|
|
14
|
+
*/
|
|
15
|
+
export class FolioLane {
|
|
16
|
+
#module;
|
|
17
|
+
#initial;
|
|
18
|
+
#maximum;
|
|
19
|
+
#maximumFrameBytes;
|
|
20
|
+
#maximumMemoryBytes;
|
|
21
|
+
#memory;
|
|
22
|
+
#instance;
|
|
23
|
+
#active;
|
|
24
|
+
constructor(module, options) {
|
|
25
|
+
this.#module = module;
|
|
26
|
+
this.#initial = integer(options.initial, 0, 65536, 'initial memory');
|
|
27
|
+
this.#maximum = integer(options.maximum, this.#initial, 65536, 'maximum memory');
|
|
28
|
+
this.#maximumMemoryBytes = options.maximumMemoryBytes ?? 32 * 1048576;
|
|
29
|
+
this.#maximumFrameBytes = options.maximumFrameBytes ?? this.#maximumMemoryBytes + 1048576;
|
|
30
|
+
integer(this.#maximumMemoryBytes, 65536, 0x100000000, 'lane memory limit');
|
|
31
|
+
integer(this.#maximumFrameBytes, 65536, 0x100100000, 'lane frame limit');
|
|
32
|
+
}
|
|
33
|
+
/** Validates the frame, runs its calls in order and returns the encoded results. */
|
|
34
|
+
execute(frame) {
|
|
35
|
+
const { header, payload } = decodeFrame(frame, this.#maximumFrameBytes);
|
|
36
|
+
validateIdentity(header);
|
|
37
|
+
integer(header.fuel, 1, 1000000000, 'fuel');
|
|
38
|
+
integer(header.maxBytes, 8, 1048576, 'tracking budget');
|
|
39
|
+
if (!Array.isArray(header.calls) || !header.calls.length || header.calls.length > 16)
|
|
40
|
+
throw new RangeError('invalid lane call count');
|
|
41
|
+
for (const call of header.calls) {
|
|
42
|
+
if (typeof call?.export !== 'string' ||
|
|
43
|
+
!Array.isArray(call.args) ||
|
|
44
|
+
call.args.length > 256 ||
|
|
45
|
+
call.args.some((value) => typeof value !== 'number' && typeof value !== 'bigint'))
|
|
46
|
+
throw new TypeError('invalid lane call');
|
|
47
|
+
}
|
|
48
|
+
const memoryBytes = snapshotLength(header.snapshot, payload);
|
|
49
|
+
const pages = memoryBytes / 65536;
|
|
50
|
+
if (!Number.isInteger(pages) ||
|
|
51
|
+
pages < this.#initial ||
|
|
52
|
+
pages > this.#maximum ||
|
|
53
|
+
memoryBytes > this.#maximumMemoryBytes)
|
|
54
|
+
throw new RangeError('invalid lane snapshot');
|
|
55
|
+
if (!this.#memory || !this.#instance || this.#memory.buffer.byteLength !== memoryBytes) {
|
|
56
|
+
const binding = WebAssembly.Module.imports(this.#module).filter((item) => item.kind === 'memory');
|
|
57
|
+
if (binding.length !== 1)
|
|
58
|
+
throw new TypeError('one lane memory required');
|
|
59
|
+
this.#memory = new WebAssembly.Memory({
|
|
60
|
+
initial: pages,
|
|
61
|
+
maximum: this.#maximum,
|
|
62
|
+
shared: true
|
|
63
|
+
});
|
|
64
|
+
this.#instance = new WebAssembly.Instance(this.#module, {
|
|
65
|
+
[binding[0].module]: { [binding[0].name]: this.#memory },
|
|
66
|
+
folio: {
|
|
67
|
+
load: (...args) => this.#active.load(...args),
|
|
68
|
+
store: (...args) => this.#active.store(...args),
|
|
69
|
+
load64: (...args) => this.#active.load64(...args),
|
|
70
|
+
store64: (...args) => this.#active.store64(...args),
|
|
71
|
+
copy: (...args) => this.#active.copy(...args),
|
|
72
|
+
fill: (...args) => this.#active.fill(...args),
|
|
73
|
+
exhausted: () => {
|
|
74
|
+
throw new SpeculationLimit('speculative instruction budget');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
restoreSnapshot(new Uint8Array(this.#memory.buffer), payload, header.snapshot);
|
|
80
|
+
let remaining = header.maxBytes;
|
|
81
|
+
const results = [];
|
|
82
|
+
for (const call of header.calls) {
|
|
83
|
+
if (remaining <= 0) {
|
|
84
|
+
results.push({ reads: [], writes: [], exhausted: true });
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
this.#active = transaction(this.#memory, remaining);
|
|
88
|
+
let error, value;
|
|
89
|
+
try {
|
|
90
|
+
this.#instance.exports.__folio_set_fuel(header.fuel);
|
|
91
|
+
const entry = this.#instance.exports[call.export];
|
|
92
|
+
if (typeof entry !== 'function')
|
|
93
|
+
throw new TypeError('unknown lane export');
|
|
94
|
+
value = entry(...call.args);
|
|
95
|
+
}
|
|
96
|
+
catch (caught) {
|
|
97
|
+
error = caught;
|
|
98
|
+
}
|
|
99
|
+
if (error instanceof RangeError) {
|
|
100
|
+
results.push({ reads: [], writes: [], exhausted: true });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const result = this.#active.result(value, error);
|
|
104
|
+
remaining -= result.reads.length + result.writes.length;
|
|
105
|
+
results.push(result);
|
|
106
|
+
}
|
|
107
|
+
this.#active = undefined;
|
|
108
|
+
return encodeResults(header, results, this.#maximumFrameBytes);
|
|
109
|
+
}
|
|
110
|
+
/** Drops the instance and its memory; a later frame builds them again. */
|
|
111
|
+
close() {
|
|
112
|
+
this.#active = this.#instance = this.#memory = undefined;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The owner side of the managed backend. The original Wasm stack keeps control flow and host
|
|
117
|
+
* effects, and JSPI joins regions that lanes execute over copied snapshots.
|
|
118
|
+
*/
|
|
119
|
+
export class ManagedFolio {
|
|
120
|
+
/** The original native exports. */
|
|
121
|
+
exports;
|
|
122
|
+
/** Optimization refusals and fallbacks seen so far. */
|
|
123
|
+
diagnostics = [];
|
|
124
|
+
#artifact;
|
|
125
|
+
#lanes;
|
|
126
|
+
#instance;
|
|
127
|
+
#serial = new WebAssembly.Global({ value: 'i32', mutable: true }, 1);
|
|
128
|
+
#pendingGlobal = new WebAssembly.Global({ value: 'i32', mutable: true }, 0);
|
|
129
|
+
#controlled = new Map();
|
|
130
|
+
#promising = new Map();
|
|
131
|
+
#maximumSnapshotBytes;
|
|
132
|
+
#maximumFrameBytes;
|
|
133
|
+
#fuel;
|
|
134
|
+
#maxBytes;
|
|
135
|
+
#snapshotEncoding;
|
|
136
|
+
#session = crypto.randomUUID();
|
|
137
|
+
#memory;
|
|
138
|
+
#scheduler;
|
|
139
|
+
#epoch = 0;
|
|
140
|
+
#sequence = 0;
|
|
141
|
+
#busy = false;
|
|
142
|
+
#closed = false;
|
|
143
|
+
#pending;
|
|
144
|
+
#closing;
|
|
145
|
+
constructor(artifact, options) {
|
|
146
|
+
this.#artifact = artifact;
|
|
147
|
+
this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
|
|
148
|
+
if (!['auto', 'dense'].includes(this.#snapshotEncoding))
|
|
149
|
+
throw new TypeError('invalid snapshot encoding');
|
|
150
|
+
this.#lanes = options.lanes;
|
|
151
|
+
integer(this.#lanes.length, 1, 64, 'lane count');
|
|
152
|
+
this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ?? 31 * 1048576, 65536, 0x100000000, 'snapshot limit');
|
|
153
|
+
this.#maximumFrameBytes = integer(options.maximumFrameBytes ??
|
|
154
|
+
Math.min(this.#maximumSnapshotBytes + 1048576, rpcFrameLimit), 65536, 0x100100000, 'frame limit');
|
|
155
|
+
this.#fuel = integer(options.fuel ?? 100000000, 1, 1000000000, 'fuel');
|
|
156
|
+
this.#maxBytes = integer(options.maxTransactionBytes ?? 262144, 8, 1048576, 'tracking budget');
|
|
157
|
+
const runtime = WebAssembly;
|
|
158
|
+
const control = artifact.control;
|
|
159
|
+
let module = artifact.original, enabled = false;
|
|
160
|
+
if (control &&
|
|
161
|
+
artifact.coordinator &&
|
|
162
|
+
runtime.Suspending &&
|
|
163
|
+
runtime.promising &&
|
|
164
|
+
this.#lanes.length > 1) {
|
|
165
|
+
const original = WebAssembly.Module.imports(artifact.original);
|
|
166
|
+
const retained = WebAssembly.Module.imports(artifact.coordinator).filter((item) => item.module !== control.namespace);
|
|
167
|
+
if (JSON.stringify(original) === JSON.stringify(retained)) {
|
|
168
|
+
module = artifact.coordinator;
|
|
169
|
+
enabled = true;
|
|
170
|
+
}
|
|
171
|
+
else
|
|
172
|
+
this.diagnostics.push('rewritten import sequence differs; using native execution');
|
|
173
|
+
}
|
|
174
|
+
else
|
|
175
|
+
this.diagnostics.push('no active coordinator; using native execution');
|
|
176
|
+
const supplied = options.imports ?? Object.create(null);
|
|
177
|
+
const memories = WebAssembly.Module.imports(artifact.original).filter((item) => item.kind === 'memory');
|
|
178
|
+
if (memories.length > 1 && options.memory)
|
|
179
|
+
throw new TypeError('bind multiple memories by name in imports');
|
|
180
|
+
const automatic = new Map();
|
|
181
|
+
const imports = new Proxy(Object.create(null), {
|
|
182
|
+
get: (_, namespace) => {
|
|
183
|
+
if (enabled && namespace === control.namespace) {
|
|
184
|
+
const bindings = {
|
|
185
|
+
[control.serialGlobal]: this.#serial,
|
|
186
|
+
[control.pendingGlobal]: this.#pendingGlobal,
|
|
187
|
+
barrier: new runtime.Suspending(() => this.#scheduler?.flush()),
|
|
188
|
+
poll: new runtime.Suspending(() => this.#scheduler?.poll())
|
|
189
|
+
};
|
|
190
|
+
for (const region of control.regions)
|
|
191
|
+
bindings[region.importName] = new runtime.Suspending((...args) => {
|
|
192
|
+
if (this.#scheduler && this.#serial.value === 0)
|
|
193
|
+
return this.#scheduler.enqueue({
|
|
194
|
+
export: region.exportName,
|
|
195
|
+
args
|
|
196
|
+
});
|
|
197
|
+
this.#instance.exports[region.exportName](...args);
|
|
198
|
+
});
|
|
199
|
+
return bindings;
|
|
200
|
+
}
|
|
201
|
+
const bound = Reflect.get(supplied, namespace, supplied);
|
|
202
|
+
if (!memories.some((item) => item.module === namespace))
|
|
203
|
+
return bound;
|
|
204
|
+
if (bound !== undefined &&
|
|
205
|
+
(bound === null || !['object', 'function'].includes(typeof bound)))
|
|
206
|
+
return bound;
|
|
207
|
+
return new Proxy(Object.create(null), {
|
|
208
|
+
get: (_, name) => {
|
|
209
|
+
if (!memories.some((item) => item.module === namespace && item.name === name))
|
|
210
|
+
return bound === undefined
|
|
211
|
+
? undefined
|
|
212
|
+
: Reflect.get(bound, name, bound);
|
|
213
|
+
let memory = (memories.length === 1 ? options.memory : undefined) ??
|
|
214
|
+
(bound === undefined ? undefined : Reflect.get(bound, name, bound));
|
|
215
|
+
if (memory === undefined) {
|
|
216
|
+
const key = JSON.stringify([namespace, name]);
|
|
217
|
+
memory = automatic.get(key);
|
|
218
|
+
if (!memory) {
|
|
219
|
+
const limits = artifact.memories?.find((item) => item.module === namespace && item.name === name);
|
|
220
|
+
if (!limits || limits.memory64)
|
|
221
|
+
throw new TypeError(`provide imported memory ${namespace}.${name}`);
|
|
222
|
+
memory = new WebAssembly.Memory({
|
|
223
|
+
initial: limits.initial,
|
|
224
|
+
...(limits.maximum === undefined
|
|
225
|
+
? {}
|
|
226
|
+
: { maximum: limits.maximum }),
|
|
227
|
+
shared: limits.shared
|
|
228
|
+
});
|
|
229
|
+
automatic.set(key, memory);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (memories.length === 1)
|
|
233
|
+
this.#memory = memory;
|
|
234
|
+
return memory;
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
this.#instance = new WebAssembly.Instance(module, imports);
|
|
240
|
+
this.exports = Object.create(null);
|
|
241
|
+
for (const item of WebAssembly.Module.exports(artifact.original))
|
|
242
|
+
Object.defineProperty(this.exports, item.name, {
|
|
243
|
+
value: this.#instance.exports[item.name],
|
|
244
|
+
enumerable: true
|
|
245
|
+
});
|
|
246
|
+
Object.freeze(this.exports);
|
|
247
|
+
if (enabled) {
|
|
248
|
+
this.#memory = this.#instance.exports[control.memoryExport];
|
|
249
|
+
for (const name of control.entries)
|
|
250
|
+
this.#controlled.set(name, runtime.promising(this.#instance.exports[name]));
|
|
251
|
+
}
|
|
252
|
+
else if (!this.#memory) {
|
|
253
|
+
const own = Object.values(this.exports).filter((item) => item instanceof WebAssembly.Memory);
|
|
254
|
+
if (own.length === 1)
|
|
255
|
+
this.#memory = own[0];
|
|
256
|
+
}
|
|
257
|
+
for (const name of options.promising ?? []) {
|
|
258
|
+
if (!runtime.promising || typeof this.exports[name] !== 'function')
|
|
259
|
+
throw new TypeError('invalid promising export');
|
|
260
|
+
this.#promising.set(name, runtime.promising(this.exports[name]));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
/** The canonical memory, which must fit the owner runtime. Throws when there is no unique one. */
|
|
264
|
+
get memory() {
|
|
265
|
+
if (!this.#memory)
|
|
266
|
+
throw new TypeError('no unique accessible memory');
|
|
267
|
+
return this.#memory;
|
|
268
|
+
}
|
|
269
|
+
/** Runs one entry; regions go to lanes and results commit in order. One run at a time. */
|
|
270
|
+
run(name, args = [], options = {}) {
|
|
271
|
+
if (this.#closed)
|
|
272
|
+
return Promise.reject(new Error('folio is closed'));
|
|
273
|
+
if (this.#busy)
|
|
274
|
+
return Promise.reject(new Error('memory already has an active run'));
|
|
275
|
+
const entry = this.exports[name];
|
|
276
|
+
if (typeof entry !== 'function')
|
|
277
|
+
return Promise.reject(new TypeError('unknown function export'));
|
|
278
|
+
const width = Math.min(this.#lanes.length, integer(options.maximumWorkers ?? this.#lanes.length, 1, 64, 'maximumWorkers'));
|
|
279
|
+
this.#busy = true;
|
|
280
|
+
let resolve, reject;
|
|
281
|
+
const pending = new Promise((success, failure) => {
|
|
282
|
+
resolve = success;
|
|
283
|
+
reject = failure;
|
|
284
|
+
});
|
|
285
|
+
this.#pending = pending;
|
|
286
|
+
void pending
|
|
287
|
+
.finally(() => {
|
|
288
|
+
this.#busy = false;
|
|
289
|
+
this.#pending = undefined;
|
|
290
|
+
})
|
|
291
|
+
.catch(() => { });
|
|
292
|
+
void this.#execute(name, entry, args, width, options.parallel === 'off').then(resolve, reject);
|
|
293
|
+
return pending;
|
|
294
|
+
}
|
|
295
|
+
async #execute(name, entry, args, width, serial) {
|
|
296
|
+
const bytes = { sent: 0, received: 0 };
|
|
297
|
+
let snapshotBytes = 0;
|
|
298
|
+
let transportFallbacks = 0;
|
|
299
|
+
const finish = (report) => ({
|
|
300
|
+
...report,
|
|
301
|
+
backend: 'managed-coherent',
|
|
302
|
+
memoryMode: 'copied',
|
|
303
|
+
transportBytes: bytes,
|
|
304
|
+
transportFallbacks
|
|
305
|
+
});
|
|
306
|
+
const controlled = this.#controlled.get(name);
|
|
307
|
+
if (serial ||
|
|
308
|
+
!controlled ||
|
|
309
|
+
width < 2 ||
|
|
310
|
+
args.some((value) => typeof value !== 'number' && typeof value !== 'bigint')) {
|
|
311
|
+
const value = this.#promising.has(name)
|
|
312
|
+
? await this.#promising.get(name)(...args)
|
|
313
|
+
: entry(...args);
|
|
314
|
+
return finish({
|
|
315
|
+
values: [value],
|
|
316
|
+
workers: 0,
|
|
317
|
+
regions: 1,
|
|
318
|
+
replayed: 0,
|
|
319
|
+
fallbacks: 0,
|
|
320
|
+
mode: 'serial'
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
const epoch = ++this.#epoch;
|
|
324
|
+
let snapshotGeneration = -1, snapshot;
|
|
325
|
+
const scheduler = new Coordinator({
|
|
326
|
+
memory: this.memory,
|
|
327
|
+
workerMemory: this.memory,
|
|
328
|
+
width,
|
|
329
|
+
profile: false,
|
|
330
|
+
pending: this.#pendingGlobal,
|
|
331
|
+
native: (call) => {
|
|
332
|
+
const previous = this.#serial.value;
|
|
333
|
+
this.#serial.value = 1;
|
|
334
|
+
try {
|
|
335
|
+
this.#instance.exports[call.export](...call.args);
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
this.#serial.value = previous;
|
|
339
|
+
}
|
|
340
|
+
},
|
|
341
|
+
dispatch: async (lane, calls, generation) => {
|
|
342
|
+
try {
|
|
343
|
+
if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
|
|
344
|
+
throw new RangeError(`snapshot of ${this.memory.buffer.byteLength} bytes exceeds the limit of ${this.#maximumSnapshotBytes} bytes`);
|
|
345
|
+
const identity = { session: this.#session, epoch, sequence: ++this.#sequence };
|
|
346
|
+
if (snapshotGeneration !== generation) {
|
|
347
|
+
const memory = new Uint8Array(this.memory.buffer);
|
|
348
|
+
snapshot =
|
|
349
|
+
this.#snapshotEncoding === 'dense'
|
|
350
|
+
? { payload: memory }
|
|
351
|
+
: encodeSnapshot(memory);
|
|
352
|
+
snapshotGeneration = generation;
|
|
353
|
+
}
|
|
354
|
+
const frame = encodeFrame({
|
|
355
|
+
...identity,
|
|
356
|
+
calls,
|
|
357
|
+
fuel: this.#fuel,
|
|
358
|
+
maxBytes: this.#maxBytes,
|
|
359
|
+
...(snapshot.snapshot ? { snapshot: snapshot.snapshot } : {})
|
|
360
|
+
}, snapshot.payload, this.#maximumFrameBytes);
|
|
361
|
+
snapshotBytes += this.memory.buffer.byteLength;
|
|
362
|
+
bytes.sent += frame.length;
|
|
363
|
+
const response = await this.#lanes[lane].execute(frame);
|
|
364
|
+
bytes.received += response.length;
|
|
365
|
+
return decodeResults(response, identity, {
|
|
366
|
+
maximumFrameBytes: this.#maximumFrameBytes,
|
|
367
|
+
memoryBytes: this.memory.buffer.byteLength,
|
|
368
|
+
maxBytes: this.#maxBytes,
|
|
369
|
+
calls: calls.length
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
transportFallbacks++;
|
|
374
|
+
this.diagnostics.push(`lane unavailable; native fallback: ${error instanceof Error ? error.message : String(error)}`);
|
|
375
|
+
return calls.map(() => ({ reads: [], writes: [], exhausted: true }));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
});
|
|
379
|
+
this.#scheduler = scheduler;
|
|
380
|
+
this.#serial.value = 0;
|
|
381
|
+
try {
|
|
382
|
+
let value, failure, failed = false;
|
|
383
|
+
try {
|
|
384
|
+
value = await controlled(...args);
|
|
385
|
+
}
|
|
386
|
+
catch (error) {
|
|
387
|
+
failed = true;
|
|
388
|
+
failure = error;
|
|
389
|
+
}
|
|
390
|
+
await scheduler.flush();
|
|
391
|
+
if (failed)
|
|
392
|
+
throw failure;
|
|
393
|
+
scheduler.report.values = [value];
|
|
394
|
+
scheduler.report.snapshotBytes = snapshotBytes;
|
|
395
|
+
return finish(scheduler.report);
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
this.#serial.value = 1;
|
|
399
|
+
this.#pendingGlobal.value = 0;
|
|
400
|
+
this.#scheduler = undefined;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Waits for the active run, then closes every lane. A failed disposer does not skip the rest. */
|
|
404
|
+
close() {
|
|
405
|
+
if (this.#closing)
|
|
406
|
+
return this.#closing;
|
|
407
|
+
this.#closed = true;
|
|
408
|
+
this.#closing = (async () => {
|
|
409
|
+
await this.#pending?.catch(() => { });
|
|
410
|
+
const outcomes = await Promise.allSettled(this.#lanes.map(async (lane) => lane.close?.()));
|
|
411
|
+
const failed = outcomes.find((result) => result.status === 'rejected');
|
|
412
|
+
if (failed?.status === 'rejected')
|
|
413
|
+
throw failed.reason;
|
|
414
|
+
})();
|
|
415
|
+
return this.#closing;
|
|
416
|
+
}
|
|
417
|
+
/** `await using` support; equivalent to `close()`. */
|
|
418
|
+
[Symbol.asyncDispose]() {
|
|
419
|
+
return this.close();
|
|
420
|
+
}
|
|
421
|
+
}
|
package/dist/memory.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface MemoryImport {
|
|
2
|
+
module: string;
|
|
3
|
+
name: string;
|
|
4
|
+
initial: number;
|
|
5
|
+
maximum?: number;
|
|
6
|
+
shared: boolean;
|
|
7
|
+
memory64: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** Reads imported memory limits without changing the module or compiling its functions. */
|
|
10
|
+
export declare function memoryImports(bytes: Uint8Array): MemoryImport[];
|
package/dist/memory.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Reads imported memory limits without changing the module or compiling its functions. */
|
|
2
|
+
export function memoryImports(bytes) {
|
|
3
|
+
let offset = 8;
|
|
4
|
+
const byte = () => {
|
|
5
|
+
if (offset >= bytes.length)
|
|
6
|
+
throw new RangeError('truncated wasm metadata');
|
|
7
|
+
return bytes[offset++];
|
|
8
|
+
};
|
|
9
|
+
const unsigned = () => {
|
|
10
|
+
let value = 0n, shift = 0n;
|
|
11
|
+
for (let i = 0; i < 10; i++) {
|
|
12
|
+
const part = byte();
|
|
13
|
+
value |= BigInt(part & 127) << shift;
|
|
14
|
+
if (!(part & 128)) {
|
|
15
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER))
|
|
16
|
+
throw new RangeError('memory limit exceeds JS integer precision');
|
|
17
|
+
return Number(value);
|
|
18
|
+
}
|
|
19
|
+
shift += 7n;
|
|
20
|
+
}
|
|
21
|
+
throw new RangeError('invalid wasm integer');
|
|
22
|
+
};
|
|
23
|
+
const name = () => {
|
|
24
|
+
const length = unsigned();
|
|
25
|
+
const end = offset + length;
|
|
26
|
+
if (end > bytes.length)
|
|
27
|
+
throw new RangeError('truncated wasm name');
|
|
28
|
+
const value = new TextDecoder().decode(bytes.subarray(offset, end));
|
|
29
|
+
offset = end;
|
|
30
|
+
return value;
|
|
31
|
+
};
|
|
32
|
+
const reference = () => {
|
|
33
|
+
const type = byte();
|
|
34
|
+
if (type === 0x63 || type === 0x64) {
|
|
35
|
+
while (byte() & 128) { }
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
while (offset < bytes.length) {
|
|
39
|
+
const section = byte();
|
|
40
|
+
const length = unsigned();
|
|
41
|
+
const end = offset + length;
|
|
42
|
+
if (end > bytes.length)
|
|
43
|
+
throw new RangeError('truncated wasm section');
|
|
44
|
+
if (section !== 2) {
|
|
45
|
+
offset = end;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const count = unsigned();
|
|
49
|
+
const memories = [];
|
|
50
|
+
for (let i = 0; i < count; i++) {
|
|
51
|
+
const module = name(), base = name(), kind = byte();
|
|
52
|
+
if (kind === 0)
|
|
53
|
+
unsigned();
|
|
54
|
+
else if (kind === 1) {
|
|
55
|
+
reference();
|
|
56
|
+
const flags = unsigned();
|
|
57
|
+
unsigned();
|
|
58
|
+
if (flags & 1)
|
|
59
|
+
unsigned();
|
|
60
|
+
}
|
|
61
|
+
else if (kind === 2) {
|
|
62
|
+
const flags = unsigned();
|
|
63
|
+
if (flags & ~7)
|
|
64
|
+
throw new TypeError('unsupported memory-limit metadata');
|
|
65
|
+
const initial = unsigned(), maximum = flags & 1 ? unsigned() : undefined;
|
|
66
|
+
memories.push({
|
|
67
|
+
module,
|
|
68
|
+
name: base,
|
|
69
|
+
initial,
|
|
70
|
+
maximum,
|
|
71
|
+
shared: Boolean(flags & 2),
|
|
72
|
+
memory64: Boolean(flags & 4)
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
else if (kind === 3) {
|
|
76
|
+
reference();
|
|
77
|
+
byte();
|
|
78
|
+
}
|
|
79
|
+
else if (kind === 4) {
|
|
80
|
+
byte();
|
|
81
|
+
unsigned();
|
|
82
|
+
}
|
|
83
|
+
else
|
|
84
|
+
throw new TypeError('unsupported wasm import metadata');
|
|
85
|
+
}
|
|
86
|
+
return memories;
|
|
87
|
+
}
|
|
88
|
+
return [];
|
|
89
|
+
}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { PreparedProgram } from './compiler.ts';
|
|
2
|
+
import type { IterationReason } from './iteration-owner.ts';
|
|
3
|
+
import type { IterationReport } from './iteration.ts';
|
|
4
|
+
/** Wraps an asynchronous host import for Wasm stack suspension. */
|
|
5
|
+
export declare function suspending<Args extends unknown[], Value>(fn: (...args: Args) => Promise<Value>): WebAssembly.ImportValue;
|
|
6
|
+
/** Source bytes, a compiled module, or a plan from `prepare`. A compiled module keeps its native path. */
|
|
7
|
+
export type ProgramInput = PreparedProgram | Uint8Array | ArrayBuffer | WebAssembly.Module;
|
|
8
|
+
/** One exported call in an ordered `runAll` batch. */
|
|
9
|
+
export interface Call {
|
|
10
|
+
/** Name of the exported function. */
|
|
11
|
+
export: string;
|
|
12
|
+
/** Arguments in Wasm order; i64 parameters take bigint. */
|
|
13
|
+
args: readonly unknown[];
|
|
14
|
+
}
|
|
15
|
+
/** Per-run routing and worker limits. */
|
|
16
|
+
export interface RunOptions {
|
|
17
|
+
/** `auto` routes by plan, `off` runs the original entry, `speculate` forces tracked regions. */
|
|
18
|
+
parallel?: 'auto' | 'off' | 'speculate';
|
|
19
|
+
/** Bound participating workers without rebuilding the isolate group. */
|
|
20
|
+
maximumWorkers?: number;
|
|
21
|
+
}
|
|
22
|
+
/** What a run did: results, how it was routed and what the speculation cost. */
|
|
23
|
+
export interface ExecutionReport {
|
|
24
|
+
/** Return values of the call, or of each call in a batch. */
|
|
25
|
+
values: unknown[];
|
|
26
|
+
/** Workers that executed regions; zero for a serial run. */
|
|
27
|
+
workers: number;
|
|
28
|
+
/** Regions discovered and dispatched. */
|
|
29
|
+
regions: number;
|
|
30
|
+
/** Regions that conflicted and replayed against committed state. */
|
|
31
|
+
replayed: number;
|
|
32
|
+
/** Regions or batches that fell back to native execution at the owner. */
|
|
33
|
+
fallbacks: number;
|
|
34
|
+
/** `native-shared` ran proved kernels on the shared allocation without tracking. */
|
|
35
|
+
mode: 'serial' | 'speculative' | 'native-shared';
|
|
36
|
+
/** Set when the control-flow extractor or the iteration route produced the regions. */
|
|
37
|
+
extraction?: 'control-flow' | 'iteration';
|
|
38
|
+
/** `shared` regions read the physical allocation; `snapshot` ran on a copied arena. */
|
|
39
|
+
memoryMode?: 'shared' | 'snapshot';
|
|
40
|
+
/** Bytes copied into the worker group for snapshot execution. */
|
|
41
|
+
snapshotBytes?: number;
|
|
42
|
+
/** Why a run stayed serial or left the fast path. */
|
|
43
|
+
reason?: 'requested' | 'small-workload' | 'no-parallel-plan' | 'single-region' | 'unsupported-module' | 'dependency' | 'guard-failed' | 'snapshot-unavailable' | 'previous-conflicts' | 'opaque-input' | IterationReason;
|
|
44
|
+
/** The iteration executor's counts, summed over the owner calls of the run. */
|
|
45
|
+
iteration?: IterationReport;
|
|
46
|
+
/** Present when `FolioOptions.profile` is set. */
|
|
47
|
+
profile?: ExecutionProfile;
|
|
48
|
+
}
|
|
49
|
+
/** Opt-in timings. Process CPU is measured once at the coordinator, not summed from these. */
|
|
50
|
+
export interface ExecutionProfile {
|
|
51
|
+
/** Elapsed time of the whole run. */
|
|
52
|
+
wallMs: number;
|
|
53
|
+
/** Elapsed time of each region or batch observation on its worker. */
|
|
54
|
+
workerWallMs: number[];
|
|
55
|
+
/** Thread CPU time of each observation. */
|
|
56
|
+
workerCpuMs: number[];
|
|
57
|
+
/** Ordered dependency validation. */
|
|
58
|
+
validationMs: number;
|
|
59
|
+
/** Committing validated writes to canonical memory. */
|
|
60
|
+
commitMs: number;
|
|
61
|
+
/** Re-executing conflicted regions. */
|
|
62
|
+
replayMs: number;
|
|
63
|
+
/** Bytes tracked as read by speculative regions. */
|
|
64
|
+
readBytes: number;
|
|
65
|
+
/** Bytes tracked as written by speculative regions. */
|
|
66
|
+
writeBytes: number;
|
|
67
|
+
}
|
|
68
|
+
/** Pool construction options. */
|
|
69
|
+
export interface FolioOptions {
|
|
70
|
+
/**
|
|
71
|
+
* Bind an existing single imported memory instead of allocating one from the module's limits.
|
|
72
|
+
* The iteration route needs it shared and grows it by the arena it asks for; an unshared or
|
|
73
|
+
* fixed-size memory keeps the program serial.
|
|
74
|
+
*/
|
|
75
|
+
memory?: WebAssembly.Memory;
|
|
76
|
+
/** Isolate count; defaults to up to four. One worker uses the native entry and creates no thread. */
|
|
77
|
+
workers?: number;
|
|
78
|
+
/** Host imports, memories, tables and globals as for native instantiation. */
|
|
79
|
+
imports?: WebAssembly.Imports;
|
|
80
|
+
/** Instruction budget per speculative region before it yields to the native head. */
|
|
81
|
+
fuel?: number;
|
|
82
|
+
/** Bytes of read and write tracking a lane may retain. */
|
|
83
|
+
maxTransactionBytes?: number;
|
|
84
|
+
/** Estimated iterations below which a proved kernel stays at its original entry. */
|
|
85
|
+
minimumParallelWork?: number;
|
|
86
|
+
/** Exports that return a Promise because they suspend on async host imports. */
|
|
87
|
+
promising?: readonly string[];
|
|
88
|
+
/** Collect execution timings; disabled by default to keep the hot path small. */
|
|
89
|
+
profile?: boolean;
|
|
90
|
+
/** Static admission threshold used when `open` prepares raw bytes; a prepared plan keeps its own. */
|
|
91
|
+
minimumRegionWork?: number;
|
|
92
|
+
/** Iterations assumed for loops with no constant bound when `open` prepares raw bytes. */
|
|
93
|
+
assumedTripCount?: number;
|
|
94
|
+
/**
|
|
95
|
+
* Run a call shape natively for 16 calls after two runs that mostly replayed or fell back, then
|
|
96
|
+
* probe again. A shape is the entry, width, memory size and numeric arguments. Off by default.
|
|
97
|
+
* @since 1.0.1
|
|
98
|
+
*/
|
|
99
|
+
adaptiveRouting?: boolean;
|
|
100
|
+
}
|
|
101
|
+
/** A same-process isolate group; callers give it exclusive memory access during each run. */
|
|
102
|
+
export declare class Folio {
|
|
103
|
+
#private;
|
|
104
|
+
/** Active sharing, extraction and validation mode; a one-worker pool reports none and serial. */
|
|
105
|
+
get capabilities(): Readonly<{
|
|
106
|
+
physicalSharing: "none" | "same-process";
|
|
107
|
+
automaticRegions: "none" | "control-flow" | "iteration" | "counted-loops";
|
|
108
|
+
dependence: "serial" | "ordered-validation";
|
|
109
|
+
}>;
|
|
110
|
+
/** The original native exports, for trusted host integration. Raw calls bypass tracking. */
|
|
111
|
+
get exports(): WebAssembly.Exports;
|
|
112
|
+
/** The unique accessible arena, including a coordinator-exposed hidden memory. Throws otherwise. */
|
|
113
|
+
get memory(): WebAssembly.Memory;
|
|
114
|
+
/** Named imported and exported memory wrappers. */
|
|
115
|
+
get memories(): Readonly<Record<string, WebAssembly.Memory>>;
|
|
116
|
+
/** Module-wide reasons the optimizer refused or fell back. A refusal is not a proved dependency. */
|
|
117
|
+
get diagnostics(): readonly string[];
|
|
118
|
+
/** Whether `entry` has an automatic plan or a native guard, by which mechanism, and why not. */
|
|
119
|
+
inspect(entry: string): Readonly<{
|
|
120
|
+
automatic: boolean;
|
|
121
|
+
nativeGuard: boolean;
|
|
122
|
+
mechanism: "counted-loop" | "control-flow" | "native";
|
|
123
|
+
diagnostics: readonly string[];
|
|
124
|
+
}>;
|
|
125
|
+
/** Thread ids of the worker isolates, in start order. */
|
|
126
|
+
readonly threadIds: number[];
|
|
127
|
+
private constructor();
|
|
128
|
+
/** Instantiates the program, starts the worker group and returns a ready pool. */
|
|
129
|
+
static open(input: ProgramInput, options?: FolioOptions): Promise<Folio>;
|
|
130
|
+
/** Splits compiler-recognized loops automatically; otherwise runs the original entry. */
|
|
131
|
+
run(entry: string, args?: Call['args'], options?: RunOptions): Promise<ExecutionReport>;
|
|
132
|
+
/** Preserves call order while discovering memory dependencies at runtime. */
|
|
133
|
+
runAll(calls: readonly Call[], options?: RunOptions): Promise<ExecutionReport>;
|
|
134
|
+
/** Joins worker termination and outstanding JSPI calls. Repeated calls share one join. */
|
|
135
|
+
close(): Promise<void>;
|
|
136
|
+
/** `await using` support; equivalent to `close()`. */
|
|
137
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
138
|
+
}
|