@gmitch215/folio 1.0.1 → 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.
Files changed (65) hide show
  1. package/README.md +398 -28
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/boundaries.d.ts +59 -0
  7. package/dist/boundaries.js +127 -0
  8. package/dist/certified.d.ts +66 -0
  9. package/dist/certified.js +192 -0
  10. package/dist/certify.d.ts +98 -0
  11. package/dist/certify.js +2628 -0
  12. package/dist/context.d.ts +16 -2
  13. package/dist/context.js +60 -14
  14. package/dist/coordinator.js +50 -3
  15. package/dist/extract.d.ts +19 -0
  16. package/dist/extract.js +133 -5
  17. package/dist/fold.d.ts +32 -0
  18. package/dist/fold.js +105 -0
  19. package/dist/frames.d.ts +5 -1
  20. package/dist/frames.js +156 -9
  21. package/dist/inline.d.ts +114 -0
  22. package/dist/inline.js +276 -13
  23. package/dist/iteration-admission.d.ts +116 -7
  24. package/dist/iteration-admission.js +137 -8
  25. package/dist/iteration-layout.d.ts +60 -0
  26. package/dist/iteration-layout.js +54 -3
  27. package/dist/iteration-owner.d.ts +14 -1
  28. package/dist/iteration-owner.js +2 -2
  29. package/dist/iteration-worker.js +124 -58
  30. package/dist/iteration.d.ts +179 -13
  31. package/dist/iteration.js +845 -70
  32. package/dist/lease.d.ts +45 -0
  33. package/dist/lease.js +274 -0
  34. package/dist/managed.d.ts +72 -0
  35. package/dist/managed.js +425 -27
  36. package/dist/memo.d.ts +99 -0
  37. package/dist/memo.js +250 -0
  38. package/dist/node.d.ts +43 -1
  39. package/dist/node.js +87 -11
  40. package/dist/ownership-redirect.d.ts +30 -0
  41. package/dist/ownership-redirect.js +179 -0
  42. package/dist/ownership-slices.d.ts +44 -0
  43. package/dist/ownership-slices.js +72 -0
  44. package/dist/ownership.d.ts +161 -0
  45. package/dist/ownership.js +6568 -0
  46. package/dist/ranges.d.ts +78 -0
  47. package/dist/ranges.js +263 -0
  48. package/dist/read-scan.d.ts +18 -0
  49. package/dist/read-scan.js +94 -0
  50. package/dist/read-windows.d.ts +103 -0
  51. package/dist/read-windows.js +244 -0
  52. package/dist/router-worker.d.ts +1 -0
  53. package/dist/router-worker.js +4 -0
  54. package/dist/router.d.ts +203 -0
  55. package/dist/router.js +667 -0
  56. package/dist/runs.d.ts +44 -0
  57. package/dist/runs.js +182 -0
  58. package/dist/slices-worker.d.ts +1 -0
  59. package/dist/slices-worker.js +38 -0
  60. package/dist/slices.d.ts +126 -0
  61. package/dist/slices.js +441 -0
  62. package/dist/tasks.d.ts +14 -4
  63. package/dist/tasks.js +12 -11
  64. package/dist/transaction.d.ts +10 -0
  65. package/package.json +40 -4
package/dist/slices.js ADDED
@@ -0,0 +1,441 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { availableParallelism } from 'node:os';
10
+ import { Worker } from 'node:worker_threads';
11
+ import { prepareContext } from "./compiler.js";
12
+ import { TaskPool } from "./tasks.js";
13
+ const PAGE = 65536;
14
+ const SNAPSHOT_LIMIT = 1 << 26;
15
+ /** The audit found the parallel run differs from the serial one. */
16
+ export class SliceConflictError extends Error {
17
+ kind;
18
+ /** First differing byte for `memory`, the slice index for `result`. */
19
+ at;
20
+ constructor(kind, at) {
21
+ super(kind === 'memory'
22
+ ? `slices differ from the serial run at byte ${at}; the calls are not independent`
23
+ : `slice ${at} returned a different value than the serial run`);
24
+ this.name = 'SliceConflictError';
25
+ this.kind = kind;
26
+ this.at = at;
27
+ }
28
+ }
29
+ const encoder = (_, value) => typeof value === 'bigint' ? { $bigint: value.toString() } : value;
30
+ const decoder = (_, value) => value && typeof value === 'object' && '$bigint' in value
31
+ ? BigInt(value.$bigint)
32
+ : value;
33
+ const decodeAll = (done) => done.map((item) => {
34
+ const text = item.text();
35
+ return (text ? decodeValues(text) : undefined);
36
+ });
37
+ /** @internal */
38
+ export const encodeValues = (values) => JSON.stringify(values, encoder);
39
+ /** @internal */
40
+ export const decodeValues = (text) => JSON.parse(text, decoder);
41
+ /**
42
+ * Marks the imported memory of a module as shared by setting its limits flag. The module has to
43
+ * declare a maximum already.
44
+ * @internal
45
+ */
46
+ export function sharedMemoryImport(bytes) {
47
+ const out = new Uint8Array(bytes.length);
48
+ out.set(bytes);
49
+ let at = 8;
50
+ const leb = () => {
51
+ let value = 0, shift = 0, byte;
52
+ do {
53
+ byte = out[at++];
54
+ value |= (byte & 0x7f) << shift;
55
+ shift += 7;
56
+ } while (byte & 0x80);
57
+ return value;
58
+ };
59
+ const skip = (length) => (at += length);
60
+ while (at < out.length) {
61
+ const id = out[at++];
62
+ const size = leb();
63
+ const end = at + size;
64
+ if (id === 2) {
65
+ for (let count = leb(); count > 0; count--) {
66
+ skip(leb());
67
+ skip(leb());
68
+ const kind = out[at++];
69
+ if (kind === 2) {
70
+ if (out[at] === 1)
71
+ out[at] = 3;
72
+ else if (out[at] !== 3)
73
+ throw new Error('the memory import needs a maximum');
74
+ return out;
75
+ }
76
+ if (kind === 0)
77
+ leb();
78
+ else if (kind === 1) {
79
+ at++;
80
+ const flags = out[at++];
81
+ leb();
82
+ if (flags & 1)
83
+ leb();
84
+ }
85
+ else if (kind === 3)
86
+ at += 2;
87
+ }
88
+ }
89
+ at = end;
90
+ }
91
+ throw new Error('the module imports no memory');
92
+ }
93
+ /**
94
+ * Runs slices of a call range on several threads over one shared memory, in place. The caller
95
+ * declares that the calls are independent and nothing tracks reads or writes, so a program that
96
+ * touches state the serial program would share returns a different result; `audit` finds that.
97
+ * Nothing is copied into a private context, which is why a bandwidth-bound kernel can win here
98
+ * while a route that copies its input first cannot. The module runs unmodified except for its
99
+ * memory import, which is marked shared. A module that keeps a stack pointer global gets one
100
+ * private stack per worker; any other mutable global, a start function or a data segment that
101
+ * is dropped refuses the module.
102
+ * @since 1.1.0
103
+ */
104
+ export class SlicePool {
105
+ #memory;
106
+ #module;
107
+ #tasks;
108
+ #workers;
109
+ #stack;
110
+ #importSlot;
111
+ #extra;
112
+ #exports;
113
+ #own;
114
+ #grown;
115
+ #closed = false;
116
+ constructor(memory, module, tasks, workers, stack, slot, extra, grown, own) {
117
+ this.#memory = memory;
118
+ this.#module = module;
119
+ this.#tasks = tasks;
120
+ this.#workers = workers;
121
+ this.#stack = stack;
122
+ this.#importSlot = slot;
123
+ this.#extra = extra;
124
+ this.#grown = grown;
125
+ this.#own = own;
126
+ this.#exports = new Set(WebAssembly.Module.exports(module)
127
+ .filter((item) => item.kind === 'function')
128
+ .map((item) => item.name));
129
+ }
130
+ /** The shared memory. Write the records into it after `open`, and read the results from it. */
131
+ get memory() {
132
+ return this.#memory;
133
+ }
134
+ /** Worker count. */
135
+ get size() {
136
+ return this.#workers.length;
137
+ }
138
+ /** First byte of the private stacks and window copies, or undefined when there are none. */
139
+ get privateBase() {
140
+ return this.#grown;
141
+ }
142
+ /** First byte of the private stacks, or undefined when the module has no stack pointer. */
143
+ get stackBase() {
144
+ return this.#stack?.base;
145
+ }
146
+ /**
147
+ * Compiles the module, grows the memory by one stack per worker when the module has a stack
148
+ * pointer, and starts the workers. Opening applies the module's data segments to the memory,
149
+ * so write the records after it returns.
150
+ */
151
+ static async open(bytes, options) {
152
+ const { memory } = options;
153
+ if (Object.prototype.toString.call(memory.buffer) !== '[object SharedArrayBuffer]')
154
+ throw new TypeError('slices need a shared memory');
155
+ const plan = prepareContext(bytes);
156
+ if (plan.reasons.length)
157
+ throw new TypeError(`module cannot run on slices: ${plan.reasons.join('; ')}`);
158
+ const ownership = options.ownership;
159
+ const deltas = ownership?.windows.length ?? 0;
160
+ if (plan.globals.length - deltas > 1)
161
+ throw new TypeError(`module keeps ${plan.globals.length - deltas} mutable globals; slices handle at most a stack pointer`);
162
+ const hasStack = plan.globals.length > deltas;
163
+ let patched;
164
+ try {
165
+ patched = sharedMemoryImport(Uint8Array.from(plan.bytes));
166
+ }
167
+ catch (error) {
168
+ throw new TypeError(`module cannot take a shared memory: ${error.message}`);
169
+ }
170
+ const module = new WebAssembly.Module(patched);
171
+ const slot = WebAssembly.Module.imports(module).find((item) => item.kind === 'memory');
172
+ if (!slot)
173
+ throw new TypeError('module must import its memory');
174
+ const width = options.workers ?? Math.max(1, Math.min(availableParallelism(), 8));
175
+ if (!Number.isSafeInteger(width) || width < 1)
176
+ throw new RangeError('invalid worker count');
177
+ let stack;
178
+ let grown;
179
+ let copies;
180
+ if (ownership) {
181
+ const names = new Set(WebAssembly.Module.exports(module)
182
+ .filter((item) => item.kind === 'global')
183
+ .map((item) => item.name));
184
+ const sorted = [...ownership.windows].sort((a, b) => a.low - b.low);
185
+ sorted.forEach((w, at) => {
186
+ if (!names.has(w.delta))
187
+ throw new TypeError(`module does not export the delta global ${w.delta}`);
188
+ if (w.low % 64 ||
189
+ w.end % 64 ||
190
+ w.end <= w.low ||
191
+ (at && w.low < sorted[at - 1].end))
192
+ throw new TypeError('ownership windows must be disjoint, 64-aligned and not empty');
193
+ });
194
+ if (!ownership.windows.length)
195
+ throw new TypeError('ownership plan has no window');
196
+ for (const [from, to] of ownership.copyOut)
197
+ if (!ownership.windows.some((w) => w.low <= from && from <= to && to <= w.end))
198
+ throw new TypeError('a copy-out range lies outside every window');
199
+ }
200
+ const shadowBytes = ownership
201
+ ? ownership.windows.reduce((sum, w) => sum + w.end - w.low, 0)
202
+ : 0;
203
+ if (hasStack || ownership) {
204
+ const bytesPerStack = hasStack ? (options.stackBytes ?? PAGE) : 0;
205
+ if (hasStack &&
206
+ (!Number.isSafeInteger(bytesPerStack) ||
207
+ bytesPerStack < PAGE ||
208
+ bytesPerStack % PAGE))
209
+ throw new RangeError('stackBytes must be a positive multiple of 65536');
210
+ const each = bytesPerStack + Math.ceil(shadowBytes / PAGE) * PAGE;
211
+ const base = memory.buffer.byteLength;
212
+ if (ownership?.windows.some((w) => w.end > base))
213
+ throw new RangeError('an ownership window lies past the memory');
214
+ try {
215
+ memory.grow((width * each) / PAGE);
216
+ }
217
+ catch (error) {
218
+ if (!(error instanceof RangeError))
219
+ throw error;
220
+ throw new RangeError(`the memory maximum leaves no room for ${width} stacks of ${each} bytes`);
221
+ }
222
+ grown = base;
223
+ // each worker's region: the stack grows down from the copies at its top
224
+ const top = (index) => base + (index + 1) * each - shadowBytes;
225
+ if (hasStack)
226
+ stack = {
227
+ name: plan.globals[0],
228
+ base,
229
+ tops: Array.from({ length: width }, (_, index) => top(index))
230
+ };
231
+ if (ownership)
232
+ copies = Array.from({ length: width }, (_, index) => {
233
+ let at = top(index);
234
+ return ownership.windows.map((w) => {
235
+ const copy = at;
236
+ at += w.end - w.low;
237
+ return copy;
238
+ });
239
+ });
240
+ }
241
+ const extra = options.imports
242
+ ? (await import(__rewriteRelativeImportExtension(String(options.imports)))).default()
243
+ : {};
244
+ let own;
245
+ if (ownership) {
246
+ const owner = new WebAssembly.Instance(module, {
247
+ ...extra,
248
+ [slot.module]: { ...(extra[slot.module] ?? {}), [slot.name]: memory }
249
+ });
250
+ const global = stack && owner.exports[stack.name];
251
+ own = {
252
+ plan: ownership,
253
+ copies: copies,
254
+ owner,
255
+ stack: global && { global, home: global.value }
256
+ };
257
+ }
258
+ const tasks = new TaskPool(width);
259
+ const workers = [];
260
+ const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
261
+ try {
262
+ await Promise.all(Array.from({ length: width }, (_, index) => {
263
+ const link = tasks.link(index);
264
+ return new Promise((resolve, reject) => {
265
+ const worker = new Worker(new URL(`./slices-worker.${extension}`, import.meta.url), {
266
+ workerData: {
267
+ module,
268
+ memory,
269
+ link,
270
+ slot,
271
+ stack: stack && { name: stack.name, top: stack.tops[index] },
272
+ windows: ownership &&
273
+ ownership.windows.map((w, at) => ({
274
+ low: w.low,
275
+ end: w.end,
276
+ delta: w.delta,
277
+ copy: copies[index][at]
278
+ })),
279
+ imports: options.imports && String(options.imports)
280
+ },
281
+ transferList: [link.port]
282
+ });
283
+ workers.push(worker);
284
+ worker.once('message', () => resolve());
285
+ worker.once('error', reject);
286
+ });
287
+ }));
288
+ }
289
+ catch (error) {
290
+ tasks.close();
291
+ await Promise.all(workers.map((worker) => worker.terminate()));
292
+ throw error;
293
+ }
294
+ return new SlicePool(memory, module, tasks, workers, stack, slot, extra, grown, own);
295
+ }
296
+ /**
297
+ * Calls the exported function `entry` for the range `[0, count)` in slices, one slice per task.
298
+ * `args(from, to)` returns the i32 (or i64 as bigint) arguments of the call for a slice, in the
299
+ * owner thread. The caller guarantees the slices are independent.
300
+ */
301
+ async run(entry, count, args, options = {}) {
302
+ if (this.#closed)
303
+ throw new Error('slice pool is closed');
304
+ if (!this.#exports.has(entry))
305
+ throw new TypeError(`module exports no function ${entry}`);
306
+ if (!Number.isSafeInteger(count) || count < 0)
307
+ throw new RangeError('invalid count');
308
+ const width = this.#workers.length;
309
+ const grain = options.grain ?? Math.max(1, Math.ceil(count / width));
310
+ if (!Number.isSafeInteger(grain) || grain < 1)
311
+ throw new RangeError('invalid grain');
312
+ const slices = [];
313
+ for (let from = 0; from < count; from += grain)
314
+ slices.push([from, Math.min(from + grain, count)]);
315
+ const before = options.audit ? new Uint8Array(this.#memory.buffer).slice() : undefined;
316
+ const calls = slices.map(([from, to]) => encodeValues(args(from, to)));
317
+ if (this.#own && !options.writes)
318
+ throw new TypeError('an ownership pool needs the byte ranges the calls write');
319
+ const start = performance.now();
320
+ let results;
321
+ let owned;
322
+ if (this.#own)
323
+ ({ results, owned } = await this.#runOwned(this.#own, entry, calls, options));
324
+ else {
325
+ const done = await this.#tasks.run(calls.map((call) => [entry, call]));
326
+ results = decodeAll(done);
327
+ }
328
+ const wallMs = performance.now() - start;
329
+ if (before)
330
+ this.#audit(entry, calls, results, before);
331
+ return {
332
+ slices: slices.length,
333
+ workers: width,
334
+ wallMs,
335
+ results,
336
+ audited: Boolean(before),
337
+ ownership: owned
338
+ };
339
+ }
340
+ // A trap leaves the writes of records after it in place, so the serial run decides: put the
341
+ // writes back, whose only other writers are private (windows, stacks), and run in place.
342
+ async #runOwned(own, entry, calls, options) {
343
+ const writes = options.writes;
344
+ const bytes = new Uint8Array(this.#memory.buffer);
345
+ for (const [from, to] of writes)
346
+ if (!Number.isSafeInteger(from) || from < 0 || from > to || to > this.#grown)
347
+ throw new RangeError('a write range lies outside the memory below the private regions');
348
+ const owned = {
349
+ snapshotBytes: writes.reduce((sum, [from, to]) => sum + to - from, 0),
350
+ snapshotMs: 0,
351
+ copyOutMs: 0,
352
+ restoreMs: 0,
353
+ replayed: false,
354
+ tasks: []
355
+ };
356
+ if (!calls.length)
357
+ return { results: [], owned };
358
+ if (owned.snapshotBytes > (options.snapshotLimit ?? SNAPSHOT_LIMIT)) {
359
+ owned.refused = 'snapshot';
360
+ return { results: this.#replay(own, entry, calls), owned };
361
+ }
362
+ let at = performance.now();
363
+ const saved = writes.map(([from, to]) => bytes.slice(from, to));
364
+ owned.snapshotMs = performance.now() - at;
365
+ const handles = calls.map((call) => this.#tasks.submit(entry, call));
366
+ // every task has to finish before the memory is touched again
367
+ const done = [];
368
+ let failure;
369
+ for (const handle of handles) {
370
+ try {
371
+ done.push(await this.#tasks.joinAsync(handle));
372
+ }
373
+ catch (error) {
374
+ failure ??= error;
375
+ done.push(undefined);
376
+ }
377
+ }
378
+ if (failure === undefined) {
379
+ const finished = done;
380
+ owned.tasks = finished.map((item) => item.record);
381
+ at = performance.now();
382
+ const copies = own.copies[finished[finished.length - 1].record.worker];
383
+ for (const [from, to] of own.plan.copyOut) {
384
+ const index = own.plan.windows.findIndex((w) => w.low <= from && to <= w.end);
385
+ const source = copies[index] + from - own.plan.windows[index].low;
386
+ bytes.copyWithin(from, source, source + to - from);
387
+ }
388
+ owned.copyOutMs = performance.now() - at;
389
+ return { results: decodeAll(finished), owned };
390
+ }
391
+ at = performance.now();
392
+ writes.forEach(([from], index) => bytes.set(saved[index], from));
393
+ owned.restoreMs = performance.now() - at;
394
+ owned.replayed = true;
395
+ owned.trap = String(failure?.message ?? failure).split('\n')[0];
396
+ return { results: this.#replay(own, entry, calls), owned };
397
+ }
398
+ #replay(own, entry, calls) {
399
+ if (own.stack)
400
+ own.stack.global.value = own.stack.home;
401
+ const run = own.owner.exports[entry];
402
+ return calls.map((call) => run(...decodeValues(call)));
403
+ }
404
+ #audit(entry, calls, results, before) {
405
+ const after = new Uint8Array(this.#memory.buffer).slice();
406
+ const copy = new WebAssembly.Memory({
407
+ initial: before.length / PAGE,
408
+ maximum: before.length / PAGE,
409
+ shared: true
410
+ });
411
+ const { module: moduleName, name } = this.#importSlot;
412
+ const imports = {
413
+ ...this.#extra,
414
+ [moduleName]: { ...(this.#extra[moduleName] ?? {}), [name]: copy }
415
+ };
416
+ const instance = new WebAssembly.Instance(this.#module, imports);
417
+ // instantiating applied the data segments over the copy; put the snapshot back
418
+ new Uint8Array(copy.buffer).set(before);
419
+ if (this.#stack)
420
+ instance.exports[this.#stack.name].value = this.#stack.tops[0];
421
+ const run = instance.exports[entry];
422
+ calls.forEach((call, index) => {
423
+ const serial = run(...decodeValues(call));
424
+ if (serial !== results[index])
425
+ throw new SliceConflictError('result', index);
426
+ });
427
+ const limit = this.#grown ?? Math.min(before.length, after.length);
428
+ const reference = new Uint8Array(copy.buffer);
429
+ for (let at = 0; at < limit; at++)
430
+ if (after[at] !== reference[at])
431
+ throw new SliceConflictError('memory', at);
432
+ }
433
+ /** Stops the workers. */
434
+ async close() {
435
+ if (this.#closed)
436
+ return;
437
+ this.#closed = true;
438
+ this.#tasks.close();
439
+ await Promise.all(this.#workers.map((worker) => worker.terminate()));
440
+ }
441
+ }
package/dist/tasks.d.ts CHANGED
@@ -1,6 +1,16 @@
1
1
  import { type MessagePort } from 'node:worker_threads';
2
2
  /** Task input and output are copied between threads. Strings and bytes are both accepted. */
3
3
  export type TaskInput = string | Uint8Array;
4
+ /** Options for one submitted task. */
5
+ export interface SubmitOptions {
6
+ /**
7
+ * Posts a `SharedArrayBuffer`-backed byte input without copying it. The caller promises not to
8
+ * write to those bytes until the task is joined. The audit reads the same bytes at join. The
9
+ * default copies, so a later write to the buffer never reaches the task. Strings and inputs
10
+ * on other buffers are copied either way.
11
+ */
12
+ share?: boolean;
13
+ }
4
14
  /** The end of a pool link that a worker passes to `serveTasks`. */
5
15
  export interface TaskLink {
6
16
  port: MessagePort;
@@ -80,17 +90,17 @@ export declare class TaskPool {
80
90
  /** The worker end of link `index`. List its port in the worker's `transferList`. */
81
91
  link(index: number): TaskLink;
82
92
  /** Starts a task and returns a handle for `join`. */
83
- submit(name: string, input?: TaskInput): string;
93
+ submit(name: string, input?: TaskInput, options?: SubmitOptions): string;
84
94
  /** Starts a task whose input is a JSON value. */
85
95
  submitJson(name: string, value: unknown): string;
86
96
  /** Blocks the calling thread until the task finishes. Use it where the caller cannot yield. */
87
97
  join(handle: string): TaskResult;
88
98
  /** Waits for the task without blocking the event loop. */
89
99
  joinAsync(handle: string): Promise<TaskResult>;
90
- /** Submits every job, then joins them in submission order. */
91
- run(jobs: [name: string, input?: TaskInput][]): Promise<TaskResult[]>;
100
+ /** Submits every job, then joins them in submission order. `options` applies to every job. */
101
+ run(jobs: [name: string, input?: TaskInput][], options?: SubmitOptions): Promise<TaskResult[]>;
92
102
  /** Blocking form of `run`. */
93
- runSync(jobs: [name: string, input?: TaskInput][]): TaskResult[];
103
+ runSync(jobs: [name: string, input?: TaskInput][], options?: SubmitOptions): TaskResult[];
94
104
  /** Returns the records of tasks joined since the last call and clears them. */
95
105
  drain(): TaskRecord[];
96
106
  /** Closes the channels. Tasks that were not joined are dropped. */
package/dist/tasks.js CHANGED
@@ -128,17 +128,16 @@ export class TaskPool {
128
128
  return link;
129
129
  }
130
130
  /** Starts a task and returns a handle for `join`. */
131
- submit(name, input = '') {
131
+ submit(name, input = '', options = {}) {
132
132
  if (this.#closed)
133
133
  throw new Error('task pool is closed');
134
134
  const worker = this.#next++ % this.#width;
135
135
  const seq = this.#seq++;
136
136
  const id = `${worker}:${seq}`;
137
137
  const submitMs = now();
138
- // postMessage shares a SharedArrayBuffer instead of copying it
139
- const posted = typeof input !== 'string' && input.buffer instanceof SharedArrayBuffer
140
- ? Uint8Array.from(input)
141
- : input;
138
+ const shared = typeof input !== 'string' && input.buffer instanceof SharedArrayBuffer;
139
+ // postMessage shares a SharedArrayBuffer view as it is, so the default copies it first
140
+ const posted = shared && !options.share ? Uint8Array.from(input) : input;
142
141
  this.#owner[worker].port.postMessage({
143
142
  id,
144
143
  name,
@@ -149,7 +148,9 @@ export class TaskPool {
149
148
  const audited = sampled
150
149
  ? typeof input === 'string' || posted !== input
151
150
  ? posted
152
- : Uint8Array.from(input)
151
+ : shared && options.share
152
+ ? input
153
+ : Uint8Array.from(input)
153
154
  : undefined;
154
155
  this.#pending.set(id, {
155
156
  id,
@@ -202,17 +203,17 @@ export class TaskPool {
202
203
  }
203
204
  return this.#finish(pending, reply, waitMs);
204
205
  }
205
- /** Submits every job, then joins them in submission order. */
206
- async run(jobs) {
207
- const handles = jobs.map(([name, input]) => this.submit(name, input));
206
+ /** Submits every job, then joins them in submission order. `options` applies to every job. */
207
+ async run(jobs, options) {
208
+ const handles = jobs.map(([name, input]) => this.submit(name, input, options));
208
209
  const results = [];
209
210
  for (const handle of handles)
210
211
  results.push(await this.joinAsync(handle));
211
212
  return results;
212
213
  }
213
214
  /** Blocking form of `run`. */
214
- runSync(jobs) {
215
- const handles = jobs.map(([name, input]) => this.submit(name, input));
215
+ runSync(jobs, options) {
216
+ const handles = jobs.map(([name, input]) => this.submit(name, input, options));
216
217
  return handles.map((handle) => this.join(handle));
217
218
  }
218
219
  /** Returns the records of tasks joined since the last call and clears them. */
@@ -4,9 +4,19 @@ export interface TransactionResult {
4
4
  value?: unknown;
5
5
  reads: number[];
6
6
  writes: [number, number][];
7
+ /** Run encoding: read runs as flat start, length pairs; `reads` is then empty. See `runs.ts`. */
8
+ readRuns?: Uint32Array;
9
+ /** Run encoding: write runs as flat start, length pairs; `writes` is then empty. */
10
+ writeRuns?: Uint32Array;
11
+ /** Run encoding: the bytes of every write run, back to back. */
12
+ writeData?: Uint8Array;
7
13
  trap?: string;
8
14
  errorKind?: string;
9
15
  exhausted?: boolean;
16
+ /** Ranges mode: reads of bytes that were not shipped. Informational; owners recompute it. */
17
+ escapes?: [number, number][];
18
+ /** Ranges mode: a trap or exhaustion that unshipped zeros may have caused. */
19
+ inconclusive?: boolean;
10
20
  timing?: {
11
21
  wallMs: number;
12
22
  cpuMs: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gmitch215/folio",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "Shared WASM memory and ordered speculative execution across isolates",
5
5
  "keywords": [
6
6
  "webassembly",
@@ -58,10 +58,46 @@
58
58
  "types": "./dist/tasks.d.ts",
59
59
  "import": "./dist/tasks.js"
60
60
  },
61
+ "./slices": {
62
+ "types": "./dist/slices.d.ts",
63
+ "import": "./dist/slices.js"
64
+ },
65
+ "./fold": {
66
+ "types": "./dist/fold.d.ts",
67
+ "import": "./dist/fold.js"
68
+ },
61
69
  "./context": {
62
70
  "types": "./dist/context.d.ts",
63
71
  "import": "./dist/context.js"
64
72
  },
73
+ "./affine": {
74
+ "types": "./dist/affine.d.ts",
75
+ "import": "./dist/affine.js"
76
+ },
77
+ "./certify": {
78
+ "types": "./dist/certify.d.ts",
79
+ "import": "./dist/certify.js"
80
+ },
81
+ "./ownership": {
82
+ "types": "./dist/ownership.d.ts",
83
+ "import": "./dist/ownership.js"
84
+ },
85
+ "./ownership-redirect": {
86
+ "types": "./dist/ownership-redirect.d.ts",
87
+ "import": "./dist/ownership-redirect.js"
88
+ },
89
+ "./ownership-slices": {
90
+ "types": "./dist/ownership-slices.d.ts",
91
+ "import": "./dist/ownership-slices.js"
92
+ },
93
+ "./router": {
94
+ "types": "./dist/router.d.ts",
95
+ "import": "./dist/router.js"
96
+ },
97
+ "./certified": {
98
+ "types": "./dist/certified.d.ts",
99
+ "import": "./dist/certified.js"
100
+ },
65
101
  "./package.json": "./package.json"
66
102
  },
67
103
  "files": [
@@ -76,8 +112,8 @@
76
112
  "build": "tsc -p tsconfig.build.json",
77
113
  "build:c": "bun scripts/build/fixtures.ts",
78
114
  "build:prepared": "bun scripts/build/prepare.ts",
79
- "build:experiments": "node experiments/managed/prepare.ts && node experiments/browser/prepare.ts && node experiments/browser/extraction/prepare.ts && node experiments/consumer/prepare.ts kernel-control",
80
- "typecheck": "bun run build:c && bun run build:experiments && tsc --noEmit -p tsconfig.json && tsc --noEmit -p experiments/cloud/tsconfig.json && tsc --noEmit -p experiments/managed/tsconfig.json && tsc --noEmit -p experiments/browser/tsconfig.json && tsc --noEmit -p experiments/consumer/tsconfig.json && tsc --noEmit -p experiments/rpc/tsconfig.json",
115
+ "build:experiments": "node experiments/managed/prepare.ts && node experiments/browser/prepare.ts && node experiments/browser/extraction/prepare.ts && node experiments/consumer/prepare.ts kernel-control && node experiments/ranges/prepare.ts && node experiments/elastic-ladder/prepare.ts",
116
+ "typecheck": "bun run build:c && bun run build:experiments && tsc --noEmit -p tsconfig.json && tsc --noEmit -p experiments/cloud/tsconfig.json && tsc --noEmit -p experiments/managed/tsconfig.json && tsc --noEmit -p experiments/elastic/tsconfig.json && tsc --noEmit -p experiments/elastic-limits/tsconfig.json && tsc --noEmit -p experiments/elastic-ladder/tsconfig.json && tsc --noEmit -p experiments/browser/tsconfig.json && tsc --noEmit -p experiments/consumer/tsconfig.json && tsc --noEmit -p experiments/rpc/tsconfig.json && tsc --noEmit -p experiments/ranges/tsconfig.json && tsc --noEmit -p experiments/concurrency/tsconfig.json && tsc --noEmit -p experiments/sqlite-lanes/tsconfig.json",
81
117
  "typecheck:php": "node experiments/consumer/php/prepare.ts && tsc --noEmit -p experiments/consumer/php/tsconfig.json",
82
118
  "typecheck:bootimage": "node experiments/bootimage/prepare.ts && tsc --noEmit -p experiments/bootimage/tsconfig.json",
83
119
  "test": "vitest run --project unit",
@@ -99,7 +135,7 @@
99
135
  "binaryen": "132.0.0"
100
136
  },
101
137
  "devDependencies": {
102
- "@cloudflare/playwright": "1.3.6",
138
+ "@cloudflare/playwright": "1.4.0",
103
139
  "@cloudflare/workers-types": "^5.20260925.1",
104
140
  "@types/node": "^26.0.0",
105
141
  "@vitest/coverage-v8": "^5.0.1",