@gmitch215/folio 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -19
- package/dist/bake.d.ts +8 -3
- package/dist/bake.js +5 -2
- package/dist/compiler.d.ts +37 -1
- package/dist/compiler.js +116 -1
- package/dist/context.d.ts +33 -0
- package/dist/context.js +93 -0
- package/dist/coordinator.d.ts +1 -1
- package/dist/coordinator.js +4 -2
- package/dist/extract.d.ts +95 -1
- package/dist/extract.js +883 -242
- package/dist/frames.d.ts +15 -1
- package/dist/frames.js +49 -1
- 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 +6 -0
- package/dist/managed.js +33 -10
- package/dist/node.d.ts +19 -5
- package/dist/node.js +344 -22
- package/dist/tasks.js +16 -3
- package/package.json +6 -2
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { availableParallelism } from 'node:os';
|
|
2
|
+
import { isSharedArrayBuffer } from 'node:util/types';
|
|
3
|
+
import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
|
|
4
|
+
import { inlineGlobals, lowerInline } from "./inline.js";
|
|
5
|
+
import { iterationArena, iterationEntryBytes, iterationGranules } from "./iteration-layout.js";
|
|
6
|
+
export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules } from "./iteration-layout.js";
|
|
7
|
+
const newReport = (workers) => ({
|
|
8
|
+
workers,
|
|
9
|
+
regions: 0,
|
|
10
|
+
replayed: 0,
|
|
11
|
+
rolledBack: 0,
|
|
12
|
+
fallbacks: 0,
|
|
13
|
+
traps: 0,
|
|
14
|
+
exhausted: 0,
|
|
15
|
+
batches: 0,
|
|
16
|
+
failedBatches: 0,
|
|
17
|
+
undoEntries: 0,
|
|
18
|
+
conflicts: { raw: 0, war: 0, waw: 0, frame: 0 },
|
|
19
|
+
dispatchMs: 0,
|
|
20
|
+
validationMs: 0,
|
|
21
|
+
rollbackMs: 0,
|
|
22
|
+
replayMs: 0,
|
|
23
|
+
workerRunMs: 0,
|
|
24
|
+
workerScanMs: 0,
|
|
25
|
+
serial: 0
|
|
26
|
+
});
|
|
27
|
+
const shift = Math.log2(iterationGranules.read / iterationGranules.write);
|
|
28
|
+
// sorted write granules against sorted read runs
|
|
29
|
+
function hitsReads(writes, runs) {
|
|
30
|
+
let p = 0;
|
|
31
|
+
for (let i = 0; i < writes.length; i++) {
|
|
32
|
+
const g = writes[i] >> shift;
|
|
33
|
+
while (p < runs.length && runs[p] + runs[p + 1] <= g)
|
|
34
|
+
p += 2;
|
|
35
|
+
if (p >= runs.length)
|
|
36
|
+
return false;
|
|
37
|
+
if (runs[p] <= g)
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
function hitsWrites(a, b) {
|
|
43
|
+
let i = 0;
|
|
44
|
+
let j = 0;
|
|
45
|
+
while (i < a.length && j < b.length) {
|
|
46
|
+
if (a[i] === b[j])
|
|
47
|
+
return true;
|
|
48
|
+
if (a[i] < b[j])
|
|
49
|
+
i++;
|
|
50
|
+
else
|
|
51
|
+
j++;
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Index of the first outcome that cannot keep its writes, or -1. Writes land in place, so every
|
|
57
|
+
* ordered pair is checked three ways: RAW marks the reader, WAR the earlier reader, WAW the earlier
|
|
58
|
+
* writer. A fourth check covers the frame, which each iteration owns as a private copy: an
|
|
59
|
+
* iteration fails when it read a frame byte before writing it that an earlier iteration wrote, and
|
|
60
|
+
* counts once. Works on the returned lists, never on dense bitmaps.
|
|
61
|
+
*/
|
|
62
|
+
export function iterationVerdict(outcomes, skip = []) {
|
|
63
|
+
const conflicts = { raw: 0, war: 0, waw: 0, frame: 0 };
|
|
64
|
+
let frameFirst = outcomes.length;
|
|
65
|
+
let firstFailure = outcomes.length;
|
|
66
|
+
outcomes.forEach((o, k) => {
|
|
67
|
+
if (o.status)
|
|
68
|
+
firstFailure = Math.min(firstFailure, k);
|
|
69
|
+
});
|
|
70
|
+
let first = firstFailure;
|
|
71
|
+
for (let j = 0; j < outcomes.length; j++) {
|
|
72
|
+
for (let k = j + 1; k < outcomes.length; k++) {
|
|
73
|
+
const a = outcomes[j];
|
|
74
|
+
const b = outcomes[k];
|
|
75
|
+
if (!skip.includes('raw') && hitsReads(a.written, b.reads)) {
|
|
76
|
+
conflicts.raw++;
|
|
77
|
+
first = Math.min(first, k);
|
|
78
|
+
}
|
|
79
|
+
if (!skip.includes('war') && hitsReads(b.written, a.reads)) {
|
|
80
|
+
conflicts.war++;
|
|
81
|
+
first = Math.min(first, j);
|
|
82
|
+
}
|
|
83
|
+
if (!skip.includes('waw') && hitsWrites(a.written, b.written)) {
|
|
84
|
+
conflicts.waw++;
|
|
85
|
+
first = Math.min(first, j);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (!skip.includes('frame')) {
|
|
90
|
+
// the frame bytes written by the iterations before k, against the bytes k read unwritten
|
|
91
|
+
let union;
|
|
92
|
+
outcomes.forEach((o, k) => {
|
|
93
|
+
const exposed = o.frameExposed;
|
|
94
|
+
if (union && exposed?.length && exposed.some((word, w) => word & (union[w] ?? 0))) {
|
|
95
|
+
conflicts.frame++;
|
|
96
|
+
first = Math.min(first, k);
|
|
97
|
+
frameFirst = Math.min(frameFirst, k);
|
|
98
|
+
}
|
|
99
|
+
const written = o.frameWritten;
|
|
100
|
+
if (!written?.length)
|
|
101
|
+
return;
|
|
102
|
+
union ??= new Uint32Array(written.length);
|
|
103
|
+
written.forEach((word, w) => (union[w] |= word));
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
const none = outcomes.length;
|
|
107
|
+
return {
|
|
108
|
+
first: first === none ? -1 : first,
|
|
109
|
+
firstFailure: firstFailure === none ? -1 : firstFailure,
|
|
110
|
+
frameFirst: frameFirst === none ? -1 : frameFirst,
|
|
111
|
+
conflicts
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Runs the loop of one owner call on worker threads. Each iteration gets a private stack slot and
|
|
116
|
+
* tracks its reads and writes inline. The owner validates a batch in order, rolls back the first
|
|
117
|
+
* failing iteration and every later one from the undo logs, and replays them through `replay`.
|
|
118
|
+
* The arena belongs to the pool until `close`.
|
|
119
|
+
*
|
|
120
|
+
* Each iteration runs on a private copy of the owner frame, taken from the owner frame when its
|
|
121
|
+
* batch is dispatched. The lowered module tracks the frame: a written bit per frame byte, and an
|
|
122
|
+
* exposed bit per 32-byte frame granule that the iteration read before it wrote the byte. An
|
|
123
|
+
* iteration fails validation, like a RAW pair, when it has an exposed granule that an earlier
|
|
124
|
+
* iteration of the same batch wrote (`conflicts.frame`); it and every later one in the batch roll
|
|
125
|
+
* back and replay. After a batch validates, each kept
|
|
126
|
+
* iteration's written frame bytes are copied into the owner frame in order, so the next batch
|
|
127
|
+
* starts from the serial frame and a replay runs on it. The guarantee: a read of an owner frame
|
|
128
|
+
* byte that the same iteration has not written yet, with a write by an earlier iteration of the
|
|
129
|
+
* batch to that byte, is detected, and an earlier batch's writes are seen through the copy.
|
|
130
|
+
* Excluded: a read of stack below the frame (callee frames, indeterminate before the callee writes
|
|
131
|
+
* them) is not tracked, and imported host functions that touch memory are not seen. The shadow
|
|
132
|
+
* is byte-exact for scalar accesses and ranges; a conservative read would only add reports.
|
|
133
|
+
*
|
|
134
|
+
* With `admit`, iteration 0 runs first on the owner and the batches cover the rest. Dispatch
|
|
135
|
+
* stops after a batch that exhausted an undo log, had a frame conflict, replayed more than half of
|
|
136
|
+
* its iterations, or (with `loses` and `collapses`) two batches in a row did not beat the serial
|
|
137
|
+
* time of their iterations or one took far longer than it; the rest of the loop runs through
|
|
138
|
+
* `replay` and `report.stopped` names the reason. Once an iteration fails, the workers start no
|
|
139
|
+
* further iteration of that batch, because it and every later one replay anyway.
|
|
140
|
+
*/
|
|
141
|
+
export class IterationPool {
|
|
142
|
+
arena;
|
|
143
|
+
width;
|
|
144
|
+
#report;
|
|
145
|
+
#memory;
|
|
146
|
+
#links = [];
|
|
147
|
+
#control = new Int32Array(new SharedArrayBuffer(4));
|
|
148
|
+
#u8;
|
|
149
|
+
#u32;
|
|
150
|
+
#closed = false;
|
|
151
|
+
constructor(memory, arena, width) {
|
|
152
|
+
this.#memory = memory;
|
|
153
|
+
this.arena = arena;
|
|
154
|
+
this.width = width;
|
|
155
|
+
this.#report = newReport(0);
|
|
156
|
+
this.#u8 = new Uint8Array(memory.buffer);
|
|
157
|
+
this.#u32 = new Uint32Array(memory.buffer);
|
|
158
|
+
}
|
|
159
|
+
/** The report of the last run, also after a run that threw. */
|
|
160
|
+
get report() {
|
|
161
|
+
return this.#report;
|
|
162
|
+
}
|
|
163
|
+
/** Lowers the route's worker module inline and starts `width` workers over `memory`. */
|
|
164
|
+
static async open(route, memory, options) {
|
|
165
|
+
if (!route.eligible || !route.module || !route.iterate)
|
|
166
|
+
throw new TypeError('iteration route is not eligible');
|
|
167
|
+
const memoryBytes = memory.buffer.byteLength;
|
|
168
|
+
if (!isSharedArrayBuffer(memory.buffer))
|
|
169
|
+
throw new TypeError('iteration pool requires shared memory');
|
|
170
|
+
const width = options.width ?? Math.min(4, availableParallelism());
|
|
171
|
+
if (!Number.isInteger(width) || width < 1 || width > 64)
|
|
172
|
+
throw new RangeError('invalid worker count');
|
|
173
|
+
const frameSize = route.frame?.size ?? 0;
|
|
174
|
+
const arena = iterationArena(options.arenaBase, memoryBytes, {
|
|
175
|
+
...options,
|
|
176
|
+
frameBytes: frameSize
|
|
177
|
+
});
|
|
178
|
+
if (arena.base + arena.bytes > arena.memoryBytes)
|
|
179
|
+
throw new RangeError('arena does not fit in memory');
|
|
180
|
+
if (frameSize >= arena.slotBytes)
|
|
181
|
+
throw new RangeError('slot is smaller than the frame');
|
|
182
|
+
const lowered = lowerInline(route.module, {
|
|
183
|
+
readGranule: iterationGranules.read,
|
|
184
|
+
writeGranule: iterationGranules.write,
|
|
185
|
+
frame: frameSize > 0
|
|
186
|
+
});
|
|
187
|
+
const module = new WebAssembly.Module(Uint8Array.from(lowered));
|
|
188
|
+
const pool = new IterationPool(memory, arena, width);
|
|
189
|
+
pool.#u8.fill(0, arena.stamp, arena.stamp + 64);
|
|
190
|
+
pool.#u8.fill(0, arena.rmaps, arena.wmaps + arena.batch * arena.wsize);
|
|
191
|
+
const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
|
|
192
|
+
try {
|
|
193
|
+
await Promise.all(Array.from({ length: width }, () => {
|
|
194
|
+
const channel = new MessageChannel();
|
|
195
|
+
const signal = new SharedArrayBuffer(4);
|
|
196
|
+
const worker = new Worker(new URL(`./iteration-worker.${extension}`, import.meta.url), {
|
|
197
|
+
workerData: {
|
|
198
|
+
module,
|
|
199
|
+
memory,
|
|
200
|
+
arena,
|
|
201
|
+
globals: inlineGlobals,
|
|
202
|
+
iterate: route.iterate,
|
|
203
|
+
locals: route.locals,
|
|
204
|
+
frameSize,
|
|
205
|
+
port: channel.port2,
|
|
206
|
+
signal,
|
|
207
|
+
control: pool.#control.buffer
|
|
208
|
+
},
|
|
209
|
+
transferList: [channel.port2]
|
|
210
|
+
});
|
|
211
|
+
pool.#links.push({
|
|
212
|
+
worker,
|
|
213
|
+
port: channel.port1,
|
|
214
|
+
signal: new Int32Array(signal)
|
|
215
|
+
});
|
|
216
|
+
return new Promise((resolve, reject) => {
|
|
217
|
+
worker.once('message', () => resolve());
|
|
218
|
+
worker.once('error', reject);
|
|
219
|
+
});
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
await pool.close();
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
return pool;
|
|
227
|
+
}
|
|
228
|
+
// blocks the owner thread until the worker replies, the idiom of TaskPool.join
|
|
229
|
+
#join(link) {
|
|
230
|
+
for (;;) {
|
|
231
|
+
const seen = Atomics.load(link.signal, 0);
|
|
232
|
+
const message = receiveMessageOnPort(link.port);
|
|
233
|
+
if (message)
|
|
234
|
+
return message.message;
|
|
235
|
+
Atomics.wait(link.signal, 0, seen);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/** Runs the loop to completion with ordered validation. Blocks the calling thread. */
|
|
239
|
+
run(job) {
|
|
240
|
+
if (this.#closed)
|
|
241
|
+
throw new Error('iteration pool is closed');
|
|
242
|
+
if (this.#memory.buffer.byteLength !== this.arena.memoryBytes)
|
|
243
|
+
throw new Error('memory changed size while the iteration pool was open');
|
|
244
|
+
if (!Number.isSafeInteger(job.trip) || job.trip < 0)
|
|
245
|
+
throw new RangeError('invalid trip count');
|
|
246
|
+
const A = this.arena;
|
|
247
|
+
const report = (this.#report = newReport(Math.min(this.width, Math.max(job.trip, 0))));
|
|
248
|
+
let plainMs = 0;
|
|
249
|
+
let from = 0;
|
|
250
|
+
if (job.admit && job.trip > 0) {
|
|
251
|
+
// iteration 0 is the serial program's own first iteration, so its writes stay
|
|
252
|
+
const t = performance.now();
|
|
253
|
+
report.serial = 1;
|
|
254
|
+
job.replay(0);
|
|
255
|
+
plainMs = performance.now() - t;
|
|
256
|
+
from = 1;
|
|
257
|
+
report.admission = job.admit(plainMs);
|
|
258
|
+
if (!report.admission.admitted) {
|
|
259
|
+
report.stopped = 'no-admission';
|
|
260
|
+
for (let k = 1; k < job.trip; k++) {
|
|
261
|
+
report.serial++;
|
|
262
|
+
job.replay(k);
|
|
263
|
+
}
|
|
264
|
+
return report;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
let stopped = false;
|
|
268
|
+
let slow = 0;
|
|
269
|
+
for (let first = from; first < job.trip; first += A.batch) {
|
|
270
|
+
const count = Math.min(A.batch, job.trip - first);
|
|
271
|
+
if (stopped) {
|
|
272
|
+
const t = performance.now();
|
|
273
|
+
try {
|
|
274
|
+
for (let k = 0; k < count; k++) {
|
|
275
|
+
report.serial++;
|
|
276
|
+
job.replay(first + k);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
report.replayMs += performance.now() - t;
|
|
281
|
+
}
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
report.batches++;
|
|
285
|
+
const t0 = performance.now();
|
|
286
|
+
const outcomes = this.#dispatch(first, count, job, report);
|
|
287
|
+
report.regions += outcomes.length;
|
|
288
|
+
const t1 = performance.now();
|
|
289
|
+
report.dispatchMs += t1 - t0;
|
|
290
|
+
for (const o of outcomes) {
|
|
291
|
+
report.undoEntries += o.entries;
|
|
292
|
+
if (o.status === 1)
|
|
293
|
+
report.traps++;
|
|
294
|
+
if (o.status === 2)
|
|
295
|
+
report.exhausted++;
|
|
296
|
+
}
|
|
297
|
+
const v = iterationVerdict(outcomes, job.skip);
|
|
298
|
+
report.conflicts.raw += v.conflicts.raw;
|
|
299
|
+
report.conflicts.war += v.conflicts.war;
|
|
300
|
+
report.conflicts.waw += v.conflicts.waw;
|
|
301
|
+
report.conflicts.frame += v.conflicts.frame;
|
|
302
|
+
const t2 = performance.now();
|
|
303
|
+
report.validationMs += t2 - t1;
|
|
304
|
+
let replays = 0;
|
|
305
|
+
if (v.first < 0)
|
|
306
|
+
this.#commitFrame(job, outcomes, count);
|
|
307
|
+
else {
|
|
308
|
+
replays = count - v.first;
|
|
309
|
+
report.failedBatches++;
|
|
310
|
+
if (v.firstFailure === v.first)
|
|
311
|
+
report.fallbacks++;
|
|
312
|
+
this.#rollback(first, outcomes, v.first);
|
|
313
|
+
report.rolledBack += outcomes.length - v.first;
|
|
314
|
+
this.#commitFrame(job, outcomes, v.first);
|
|
315
|
+
const t3 = performance.now();
|
|
316
|
+
report.rollbackMs += t3 - t2;
|
|
317
|
+
try {
|
|
318
|
+
for (let k = v.first; k < count; k++) {
|
|
319
|
+
if (k < outcomes.length)
|
|
320
|
+
report.replayed++;
|
|
321
|
+
else
|
|
322
|
+
report.serial++;
|
|
323
|
+
job.replay(first + k);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
report.replayMs += performance.now() - t3;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
const wallMs = performance.now() - t0;
|
|
331
|
+
const serialMs = count * plainMs;
|
|
332
|
+
if (report.admission) {
|
|
333
|
+
report.admission.batchWallMs = wallMs;
|
|
334
|
+
report.admission.batchSerialMs = serialMs;
|
|
335
|
+
}
|
|
336
|
+
// the first batch also pays for waking the workers, so a batch that is merely slow is not a
|
|
337
|
+
// verdict until a second one confirms it
|
|
338
|
+
slow = job.admit && job.loses?.(wallMs, serialMs) ? slow + 1 : 0;
|
|
339
|
+
const collapsed = job.admit && job.collapses?.(wallMs, serialMs);
|
|
340
|
+
const stop = outcomes.some((o) => o.status === 2)
|
|
341
|
+
? 'log-exhausted'
|
|
342
|
+
: v.frameFirst >= 0
|
|
343
|
+
? 'frame-carried dependence'
|
|
344
|
+
: replays * 2 > count
|
|
345
|
+
? 'dependency'
|
|
346
|
+
: (slow >= 2 || collapsed) && first + count < job.trip
|
|
347
|
+
? 'no-admission'
|
|
348
|
+
: undefined;
|
|
349
|
+
if (stop) {
|
|
350
|
+
report.stopped ??= stop;
|
|
351
|
+
stopped = true;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return report;
|
|
355
|
+
}
|
|
356
|
+
#dispatch(first, count, job, report) {
|
|
357
|
+
this.#control[0] = 0;
|
|
358
|
+
Atomics.store(this.#u32, this.arena.stamp / 4, 0);
|
|
359
|
+
const used = this.#links.slice(0, Math.min(this.width, count));
|
|
360
|
+
const message = {
|
|
361
|
+
first,
|
|
362
|
+
count,
|
|
363
|
+
entry: job.entry,
|
|
364
|
+
frameBase: job.frameBase,
|
|
365
|
+
reverse: job.schedule === 'reverse'
|
|
366
|
+
};
|
|
367
|
+
for (const link of used)
|
|
368
|
+
link.port.postMessage(message);
|
|
369
|
+
const outcomes = [];
|
|
370
|
+
let failure;
|
|
371
|
+
for (const link of used) {
|
|
372
|
+
const reply = this.#join(link);
|
|
373
|
+
if (reply.error !== undefined)
|
|
374
|
+
failure ??= reply.error;
|
|
375
|
+
else {
|
|
376
|
+
outcomes.push(...reply.done);
|
|
377
|
+
report.workerRunMs += reply.runMs;
|
|
378
|
+
report.workerScanMs += reply.scanMs;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (failure !== undefined)
|
|
382
|
+
throw new Error(`iteration worker failed: ${failure}`);
|
|
383
|
+
return outcomes.sort((a, b) => a.index - b.index);
|
|
384
|
+
}
|
|
385
|
+
// the written frame bytes of the first `kept` iterations of a batch, in order, into the owner frame
|
|
386
|
+
#commitFrame(job, outcomes, kept) {
|
|
387
|
+
const A = this.arena;
|
|
388
|
+
if (!A.frameBytes)
|
|
389
|
+
return;
|
|
390
|
+
for (let k = 0; k < kept; k++) {
|
|
391
|
+
const o = outcomes[k];
|
|
392
|
+
const slot = o.index - outcomes[0].index;
|
|
393
|
+
const frame = A.slots + (slot + 1) * A.slotBytes - A.frameBytes;
|
|
394
|
+
o.frameWritten.forEach((word, g) => {
|
|
395
|
+
for (let b = 0; b < 32; b++)
|
|
396
|
+
if ((word >>> b) & 1) {
|
|
397
|
+
const at = 32 * g + b;
|
|
398
|
+
this.#u8[job.frameBase + at] = this.#u8[frame + at];
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
// newest stamp first across every iteration being rolled back
|
|
404
|
+
#rollback(first, outcomes, from) {
|
|
405
|
+
const A = this.arena;
|
|
406
|
+
const entries = [];
|
|
407
|
+
for (let k = from; k < outcomes.length; k++) {
|
|
408
|
+
const o = outcomes[k];
|
|
409
|
+
const base = A.logs + (o.index - first) * A.logBytes;
|
|
410
|
+
for (let e = 0; e < o.entries; e++) {
|
|
411
|
+
const at = base + e * iterationEntryBytes;
|
|
412
|
+
entries.push({
|
|
413
|
+
address: this.#u32[at / 4],
|
|
414
|
+
stamp: this.#u32[at / 4 + 1],
|
|
415
|
+
data: at + 8
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
entries.sort((a, b) => b.stamp - a.stamp);
|
|
420
|
+
for (const e of entries)
|
|
421
|
+
this.#u8.copyWithin(e.address, e.data, e.data + iterationGranules.write);
|
|
422
|
+
}
|
|
423
|
+
/** Stops the workers. Safe to call twice. */
|
|
424
|
+
async close() {
|
|
425
|
+
if (this.#closed)
|
|
426
|
+
return;
|
|
427
|
+
this.#closed = true;
|
|
428
|
+
await Promise.all(this.#links.map((link) => link.worker.terminate()));
|
|
429
|
+
for (const link of this.#links)
|
|
430
|
+
link.port.close();
|
|
431
|
+
}
|
|
432
|
+
[Symbol.asyncDispose]() {
|
|
433
|
+
return this.close();
|
|
434
|
+
}
|
|
435
|
+
}
|
package/dist/managed.d.ts
CHANGED
|
@@ -23,6 +23,8 @@ export interface ManagedLaneTransport {
|
|
|
23
23
|
}
|
|
24
24
|
/** An `ExecutionReport` for the managed backend, which always copies snapshots. */
|
|
25
25
|
export interface ManagedReport extends Omit<ExecutionReport, 'memoryMode'> {
|
|
26
|
+
/** Logical snapshot bytes represented across lanes; encoded traffic is in transportBytes. */
|
|
27
|
+
snapshotBytes?: number;
|
|
26
28
|
/** Always `managed-coherent`. */
|
|
27
29
|
backend: 'managed-coherent';
|
|
28
30
|
/** Lanes read copied snapshots, never shared memory. */
|
|
@@ -68,9 +70,13 @@ export declare class ManagedFolio {
|
|
|
68
70
|
memory?: WebAssembly.Memory;
|
|
69
71
|
fuel?: number;
|
|
70
72
|
maxTransactionBytes?: number;
|
|
73
|
+
/** Largest arena a run may snapshot; the default is 31 MiB. */
|
|
71
74
|
maximumSnapshotBytes?: number;
|
|
75
|
+
/** Largest request frame a lane transport accepts. A larger frame is not sent and the call falls back to the owner. The default is the snapshot limit plus 1 MiB, capped below the 32 MiB Workers RPC argument limit. */
|
|
72
76
|
maximumFrameBytes?: number;
|
|
73
77
|
promising?: readonly string[];
|
|
78
|
+
/** `dense` (default) sends the whole snapshot; `auto` elides zero pages, which lanes from 1.0.0 reject. */
|
|
79
|
+
snapshotEncoding?: 'auto' | 'dense';
|
|
74
80
|
});
|
|
75
81
|
/** The canonical memory, which must fit the owner runtime. Throws when there is no unique one. */
|
|
76
82
|
get memory(): WebAssembly.Memory;
|
package/dist/managed.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { Coordinator } from "./coordinator.js";
|
|
2
|
-
import { decodeFrame, decodeResults, encodeFrame, encodeResults, validateIdentity } from "./frames.js";
|
|
2
|
+
import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, snapshotLength, validateIdentity } from "./frames.js";
|
|
3
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;
|
|
4
6
|
function integer(value, minimum, maximum, label) {
|
|
5
7
|
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
6
8
|
throw new RangeError(`invalid ${label}`);
|
|
@@ -43,13 +45,14 @@ export class FolioLane {
|
|
|
43
45
|
call.args.some((value) => typeof value !== 'number' && typeof value !== 'bigint'))
|
|
44
46
|
throw new TypeError('invalid lane call');
|
|
45
47
|
}
|
|
46
|
-
const
|
|
48
|
+
const memoryBytes = snapshotLength(header.snapshot, payload);
|
|
49
|
+
const pages = memoryBytes / 65536;
|
|
47
50
|
if (!Number.isInteger(pages) ||
|
|
48
51
|
pages < this.#initial ||
|
|
49
52
|
pages > this.#maximum ||
|
|
50
|
-
|
|
53
|
+
memoryBytes > this.#maximumMemoryBytes)
|
|
51
54
|
throw new RangeError('invalid lane snapshot');
|
|
52
|
-
if (!this.#memory || !this.#instance || this.#memory.buffer.byteLength !==
|
|
55
|
+
if (!this.#memory || !this.#instance || this.#memory.buffer.byteLength !== memoryBytes) {
|
|
53
56
|
const binding = WebAssembly.Module.imports(this.#module).filter((item) => item.kind === 'memory');
|
|
54
57
|
if (binding.length !== 1)
|
|
55
58
|
throw new TypeError('one lane memory required');
|
|
@@ -73,7 +76,7 @@ export class FolioLane {
|
|
|
73
76
|
}
|
|
74
77
|
});
|
|
75
78
|
}
|
|
76
|
-
new Uint8Array(this.#memory.buffer).
|
|
79
|
+
restoreSnapshot(new Uint8Array(this.#memory.buffer), payload, header.snapshot);
|
|
77
80
|
let remaining = header.maxBytes;
|
|
78
81
|
const results = [];
|
|
79
82
|
for (const call of header.calls) {
|
|
@@ -129,6 +132,7 @@ export class ManagedFolio {
|
|
|
129
132
|
#maximumFrameBytes;
|
|
130
133
|
#fuel;
|
|
131
134
|
#maxBytes;
|
|
135
|
+
#snapshotEncoding;
|
|
132
136
|
#session = crypto.randomUUID();
|
|
133
137
|
#memory;
|
|
134
138
|
#scheduler;
|
|
@@ -140,10 +144,14 @@ export class ManagedFolio {
|
|
|
140
144
|
#closing;
|
|
141
145
|
constructor(artifact, options) {
|
|
142
146
|
this.#artifact = artifact;
|
|
147
|
+
this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
|
|
148
|
+
if (!['auto', 'dense'].includes(this.#snapshotEncoding))
|
|
149
|
+
throw new TypeError('invalid snapshot encoding');
|
|
143
150
|
this.#lanes = options.lanes;
|
|
144
151
|
integer(this.#lanes.length, 1, 64, 'lane count');
|
|
145
|
-
this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ??
|
|
146
|
-
this.#maximumFrameBytes = integer(options.maximumFrameBytes ??
|
|
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');
|
|
147
155
|
this.#fuel = integer(options.fuel ?? 100000000, 1, 1000000000, 'fuel');
|
|
148
156
|
this.#maxBytes = integer(options.maxTransactionBytes ?? 262144, 8, 1048576, 'tracking budget');
|
|
149
157
|
const runtime = WebAssembly;
|
|
@@ -313,6 +321,7 @@ export class ManagedFolio {
|
|
|
313
321
|
});
|
|
314
322
|
}
|
|
315
323
|
const epoch = ++this.#epoch;
|
|
324
|
+
let snapshotGeneration = -1, snapshot;
|
|
316
325
|
const scheduler = new Coordinator({
|
|
317
326
|
memory: this.memory,
|
|
318
327
|
workerMemory: this.memory,
|
|
@@ -329,12 +338,26 @@ export class ManagedFolio {
|
|
|
329
338
|
this.#serial.value = previous;
|
|
330
339
|
}
|
|
331
340
|
},
|
|
332
|
-
dispatch: async (lane, calls) => {
|
|
341
|
+
dispatch: async (lane, calls, generation) => {
|
|
333
342
|
try {
|
|
334
343
|
if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
|
|
335
|
-
throw new RangeError(
|
|
344
|
+
throw new RangeError(`snapshot of ${this.memory.buffer.byteLength} bytes exceeds the limit of ${this.#maximumSnapshotBytes} bytes`);
|
|
336
345
|
const identity = { session: this.#session, epoch, sequence: ++this.#sequence };
|
|
337
|
-
|
|
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);
|
|
338
361
|
snapshotBytes += this.memory.buffer.byteLength;
|
|
339
362
|
bytes.sent += frame.length;
|
|
340
363
|
const response = await this.#lanes[lane].execute(frame);
|
package/dist/node.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { PreparedProgram } from './compiler.ts';
|
|
2
|
+
import type { IterationReason } from './iteration-owner.ts';
|
|
3
|
+
import type { IterationReport } from './iteration.ts';
|
|
2
4
|
/** Wraps an asynchronous host import for Wasm stack suspension. */
|
|
3
5
|
export declare function suspending<Args extends unknown[], Value>(fn: (...args: Args) => Promise<Value>): WebAssembly.ImportValue;
|
|
4
6
|
/** Source bytes, a compiled module, or a plan from `prepare`. A compiled module keeps its native path. */
|
|
@@ -31,14 +33,16 @@ export interface ExecutionReport {
|
|
|
31
33
|
fallbacks: number;
|
|
32
34
|
/** `native-shared` ran proved kernels on the shared allocation without tracking. */
|
|
33
35
|
mode: 'serial' | 'speculative' | 'native-shared';
|
|
34
|
-
/** Set when the
|
|
35
|
-
extraction?: 'control-flow';
|
|
36
|
+
/** Set when the control-flow extractor or the iteration route produced the regions. */
|
|
37
|
+
extraction?: 'control-flow' | 'iteration';
|
|
36
38
|
/** `shared` regions read the physical allocation; `snapshot` ran on a copied arena. */
|
|
37
39
|
memoryMode?: 'shared' | 'snapshot';
|
|
38
40
|
/** Bytes copied into the worker group for snapshot execution. */
|
|
39
41
|
snapshotBytes?: number;
|
|
40
42
|
/** Why a run stayed serial or left the fast path. */
|
|
41
|
-
reason?: 'requested' | 'small-workload' | 'no-parallel-plan' | 'single-region' | 'unsupported-module' | 'dependency' | 'guard-failed' | 'snapshot-unavailable' | 'opaque-input';
|
|
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;
|
|
42
46
|
/** Present when `FolioOptions.profile` is set. */
|
|
43
47
|
profile?: ExecutionProfile;
|
|
44
48
|
}
|
|
@@ -63,7 +67,11 @@ export interface ExecutionProfile {
|
|
|
63
67
|
}
|
|
64
68
|
/** Pool construction options. */
|
|
65
69
|
export interface FolioOptions {
|
|
66
|
-
/**
|
|
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
|
+
*/
|
|
67
75
|
memory?: WebAssembly.Memory;
|
|
68
76
|
/** Isolate count; defaults to up to four. One worker uses the native entry and creates no thread. */
|
|
69
77
|
workers?: number;
|
|
@@ -83,6 +91,12 @@ export interface FolioOptions {
|
|
|
83
91
|
minimumRegionWork?: number;
|
|
84
92
|
/** Iterations assumed for loops with no constant bound when `open` prepares raw bytes. */
|
|
85
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;
|
|
86
100
|
}
|
|
87
101
|
/** A same-process isolate group; callers give it exclusive memory access during each run. */
|
|
88
102
|
export declare class Folio {
|
|
@@ -90,7 +104,7 @@ export declare class Folio {
|
|
|
90
104
|
/** Active sharing, extraction and validation mode; a one-worker pool reports none and serial. */
|
|
91
105
|
get capabilities(): Readonly<{
|
|
92
106
|
physicalSharing: "none" | "same-process";
|
|
93
|
-
automaticRegions: "none" | "control-flow" | "counted-loops";
|
|
107
|
+
automaticRegions: "none" | "control-flow" | "iteration" | "counted-loops";
|
|
94
108
|
dependence: "serial" | "ordered-validation";
|
|
95
109
|
}>;
|
|
96
110
|
/** The original native exports, for trusted host integration. Raw calls bypass tracking. */
|