@gmitch215/folio 1.0.1 → 1.2.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 (130) hide show
  1. package/README.md +98 -460
  2. package/dist/boot.d.ts +1 -0
  3. package/dist/boot.js +1 -0
  4. package/dist/browser/index.d.ts +73 -0
  5. package/dist/browser/index.js +277 -0
  6. package/dist/browser.d.ts +1 -68
  7. package/dist/browser.js +1 -274
  8. package/dist/continuation.d.ts +1 -0
  9. package/dist/continuation.js +1 -0
  10. package/dist/{compiler.d.ts → execution/compiler.d.ts} +1 -1
  11. package/dist/{compiler.js → execution/compiler.js} +5 -12
  12. package/dist/{coordinator.d.ts → execution/coordinator.d.ts} +1 -1
  13. package/dist/{coordinator.js → execution/coordinator.js} +55 -8
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +22 -13
  15. package/dist/{extract.js → execution/extract.js} +137 -10
  16. package/dist/execution/fold.d.ts +44 -0
  17. package/dist/execution/fold.js +105 -0
  18. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  19. package/dist/execution/runs.d.ts +44 -0
  20. package/dist/execution/runs.js +182 -0
  21. package/dist/{transaction.d.ts → execution/transaction.d.ts} +10 -0
  22. package/dist/execution/types.d.ts +221 -0
  23. package/dist/folds/affine-state.d.ts +142 -0
  24. package/dist/folds/affine-state.js +737 -0
  25. package/dist/folds/affine.d.ts +148 -0
  26. package/dist/folds/affine.js +562 -0
  27. package/dist/folds/boundaries.d.ts +48 -0
  28. package/dist/folds/boundaries.js +119 -0
  29. package/dist/folds/certified.d.ts +55 -0
  30. package/dist/folds/certified.js +178 -0
  31. package/dist/folds/certify.d.ts +87 -0
  32. package/dist/folds/certify.js +2611 -0
  33. package/dist/footprints/memo.d.ts +74 -0
  34. package/dist/footprints/memo.js +256 -0
  35. package/dist/footprints/ranges.d.ts +78 -0
  36. package/dist/footprints/ranges.js +263 -0
  37. package/dist/footprints/read-scan.d.ts +18 -0
  38. package/dist/footprints/read-scan.js +94 -0
  39. package/dist/footprints/read-windows.d.ts +77 -0
  40. package/dist/footprints/read-windows.js +245 -0
  41. package/dist/index.d.ts +16 -4
  42. package/dist/index.js +14 -2
  43. package/dist/iteration/admission.d.ts +149 -0
  44. package/dist/iteration/admission.js +201 -0
  45. package/dist/iteration/index.d.ts +239 -0
  46. package/dist/iteration/index.js +1210 -0
  47. package/dist/iteration/inline.d.ts +182 -0
  48. package/dist/{inline.js → iteration/inline.js} +277 -21
  49. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +16 -3
  50. package/dist/{iteration-owner.js → iteration/owner.js} +6 -5
  51. package/dist/iteration/worker.js +216 -0
  52. package/dist/{managed.d.ts → managed/index.d.ts} +75 -3
  53. package/dist/managed/index.js +817 -0
  54. package/dist/managed/outbox.d.ts +128 -0
  55. package/dist/managed/outbox.js +156 -0
  56. package/dist/managed/pool.d.ts +221 -0
  57. package/dist/managed/pool.js +310 -0
  58. package/dist/managed/tasks.d.ts +154 -0
  59. package/dist/managed/tasks.js +183 -0
  60. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  61. package/dist/{bake.js → memory/bake.js} +9 -7
  62. package/dist/memory/continuation.d.ts +141 -0
  63. package/dist/memory/continuation.js +495 -0
  64. package/dist/memory/elastic-peer.d.ts +20 -0
  65. package/dist/memory/elastic-peer.js +39 -0
  66. package/dist/memory/elastic-sql.d.ts +11 -0
  67. package/dist/memory/elastic-sql.js +35 -0
  68. package/dist/memory/elastic.d.ts +130 -0
  69. package/dist/memory/elastic.js +475 -0
  70. package/dist/memory/growth-governor.d.ts +16 -0
  71. package/dist/memory/growth-governor.js +42 -0
  72. package/dist/memory/imports.d.ts +10 -0
  73. package/dist/memory/imports.js +89 -0
  74. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +61 -1
  75. package/dist/{iteration-layout.js → memory/iteration-layout.js} +54 -3
  76. package/dist/memory/lease.d.ts +45 -0
  77. package/dist/memory/lease.js +274 -0
  78. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  79. package/dist/memory.d.ts +5 -10
  80. package/dist/memory.js +5 -89
  81. package/dist/{context.d.ts → node/context.d.ts} +17 -3
  82. package/dist/{context.js → node/context.js} +60 -14
  83. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  84. package/dist/{host.js → node/host.js} +2 -2
  85. package/dist/{node.d.ts → node/index.d.ts} +46 -49
  86. package/dist/{node.js → node/index.js} +101 -26
  87. package/dist/{tasks.d.ts → node/tasks.d.ts} +16 -17
  88. package/dist/{tasks.js → node/tasks.js} +12 -11
  89. package/dist/node/worker.d.ts +1 -0
  90. package/dist/{worker.js → node/worker.js} +2 -2
  91. package/dist/ownership/index.d.ts +161 -0
  92. package/dist/ownership/index.js +6565 -0
  93. package/dist/ownership/redirect.d.ts +30 -0
  94. package/dist/ownership/redirect.js +179 -0
  95. package/dist/ownership/slices.d.ts +44 -0
  96. package/dist/ownership/slices.js +72 -0
  97. package/dist/{frames.d.ts → remote/frames.d.ts} +6 -2
  98. package/dist/remote/frames.js +306 -0
  99. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  100. package/dist/{remote.js → remote/index.js} +7 -2
  101. package/dist/routing/index.d.ts +203 -0
  102. package/dist/routing/index.js +671 -0
  103. package/dist/routing/worker.d.ts +1 -0
  104. package/dist/routing/worker.js +4 -0
  105. package/dist/slices/index.d.ts +126 -0
  106. package/dist/slices/index.js +441 -0
  107. package/dist/slices/worker.d.ts +1 -0
  108. package/dist/slices/worker.js +38 -0
  109. package/dist/workers.d.ts +5 -0
  110. package/dist/workers.js +5 -0
  111. package/package.json +32 -46
  112. package/dist/frames.js +0 -159
  113. package/dist/inline.d.ts +0 -68
  114. package/dist/iteration-admission.d.ts +0 -76
  115. package/dist/iteration-admission.js +0 -72
  116. package/dist/iteration-worker.js +0 -150
  117. package/dist/iteration.d.ts +0 -163
  118. package/dist/iteration.js +0 -435
  119. package/dist/managed.js +0 -421
  120. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  121. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  122. /package/dist/{guards.js → execution/guards.js} +0 -0
  123. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  124. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  125. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  126. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  127. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  128. /package/dist/{pages.js → memory/pages.js} +0 -0
  129. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  130. /package/dist/{values.js → remote/values.js} +0 -0
@@ -0,0 +1,817 @@
1
+ import { Coordinator } from "../execution/coordinator.js";
2
+ import { capRuns, packWrites } from "../execution/runs.js";
3
+ import { SpeculationLimit, transaction } from "../execution/transaction.js";
4
+ import { RegionMemo } from "../footprints/memo.js";
5
+ import { clearRanges, decodeRanges, encodeRangesFrame, escapes, FootprintCache, rangePage, RangeSet, restoreRanges, resultEscapes } from "../footprints/ranges.js";
6
+ import { iterationArena, iterationEntryBytes, iterationFit } from "../memory/iteration-layout.js";
7
+ import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, runsVersion, snapshotLength, validateIdentity } from "../remote/frames.js";
8
+ // the exported globals of the inline lowering, as named by `inlineGlobals` in inline.ts
9
+ const markGlobals = {
10
+ readBitmap: '__folio_rb',
11
+ writeBitmap: '__folio_wb',
12
+ logPointer: '__folio_lp',
13
+ logLimit: '__folio_ll',
14
+ stampAddress: '__folio_sa',
15
+ arenaLow: '__folio_al',
16
+ arenaEnd: '__folio_ae',
17
+ violation: '__folio_xv'
18
+ };
19
+ // workers rpc rejects serialized arguments over 32 MiB; the margin covers the other arguments and serializer tags
20
+ const rpcFrameLimit = 32 * 1048576 - 4096;
21
+ // process-local identity of a tracked module; a memo shared across artifacts keys on it
22
+ const moduleIdentities = new WeakMap();
23
+ let moduleCount = 0;
24
+ function moduleIdentity(module) {
25
+ let id = moduleIdentities.get(module);
26
+ if (!id)
27
+ moduleIdentities.set(module, (id = `module-${++moduleCount}`));
28
+ return id;
29
+ }
30
+ function memoTally(now, before) {
31
+ return {
32
+ memoHits: now.hits - before.hits,
33
+ memoSavedMs: now.savedMs - before.savedMs,
34
+ memoHashedBytes: now.hashedBytes - before.hashedBytes,
35
+ memoRecords: now.recorded - before.recorded
36
+ };
37
+ }
38
+ function integer(value, minimum, maximum, label) {
39
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
40
+ throw new RangeError(`invalid ${label}`);
41
+ return value;
42
+ }
43
+ /**
44
+ * The lane runtime: runs tracked regions from a binary frame against a private copy of the
45
+ * frozen snapshot and returns byte read and write sets. Holds no state between frames.
46
+ */
47
+ export class FolioLane {
48
+ #module;
49
+ #initial;
50
+ #maximum;
51
+ #maximumFrameBytes;
52
+ #maximumMemoryBytes;
53
+ #inline;
54
+ #memory;
55
+ #instance;
56
+ #marks;
57
+ #active;
58
+ // bytes that may be nonzero; a fresh instance can hold data segments, so it starts as everything
59
+ #dirty = 'all';
60
+ // bytes of program memory the instance was built for
61
+ #owned = 0;
62
+ // what instantiation writes into a fresh memory; unknown unless the caller names the segments
63
+ #data = 'all';
64
+ constructor(module, options) {
65
+ this.#module = module;
66
+ if (options.inline)
67
+ this.#inline = {
68
+ module: options.inline.module,
69
+ logEntries: integer(options.inline.logEntries ?? 8192, 1, 1048576, 'log entries')
70
+ };
71
+ if (options.dataSegments)
72
+ this.#data = RangeSet.of(options.dataSegments);
73
+ this.#initial = integer(options.initial, 0, 65536, 'initial memory');
74
+ this.#maximum = integer(options.maximum, this.#initial, 65536, 'maximum memory');
75
+ this.#maximumMemoryBytes = options.maximumMemoryBytes ?? 32 * 1048576;
76
+ this.#maximumFrameBytes = options.maximumFrameBytes ?? this.#maximumMemoryBytes + 1048576;
77
+ integer(this.#maximumMemoryBytes, 65536, 0x100000000, 'lane memory limit');
78
+ integer(this.#maximumFrameBytes, 65536, 0x100100000, 'lane frame limit');
79
+ }
80
+ /** Validates the frame, runs its calls in order and returns the encoded results. */
81
+ execute(frame) {
82
+ const { header, payload } = decodeFrame(frame, this.#maximumFrameBytes);
83
+ validateIdentity(header);
84
+ integer(header.fuel, 1, 1000000000, 'fuel');
85
+ integer(header.maxBytes, 8, 1048576, 'tracking budget');
86
+ if (!Array.isArray(header.calls) || !header.calls.length || header.calls.length > 16)
87
+ throw new RangeError('invalid lane call count');
88
+ for (const call of header.calls) {
89
+ if (typeof call?.export !== 'string' ||
90
+ !Array.isArray(call.args) ||
91
+ call.args.length > 256 ||
92
+ call.args.some((value) => typeof value !== 'number' && typeof value !== 'bigint'))
93
+ throw new TypeError('invalid lane call');
94
+ }
95
+ if (header.ranges !== undefined && header.snapshot !== undefined)
96
+ throw new TypeError('a frame carries a snapshot or ranges, not both');
97
+ if (header.runs !== undefined && header.runs !== runsVersion)
98
+ throw new TypeError('unsupported results encoding');
99
+ const runs = header.runs === runsVersion;
100
+ const ranged = header.ranges === undefined ? undefined : decodeRanges(header.ranges, payload);
101
+ const memoryBytes = ranged ? ranged.memoryBytes : snapshotLength(header.snapshot, payload);
102
+ const pages = memoryBytes / 65536;
103
+ if (!Number.isInteger(pages) ||
104
+ pages < this.#initial ||
105
+ pages > this.#maximum ||
106
+ memoryBytes > this.#maximumMemoryBytes)
107
+ throw new RangeError('invalid lane snapshot');
108
+ if (!this.#memory || !this.#instance || this.#owned !== memoryBytes) {
109
+ const module = this.#inline?.module ?? this.#module;
110
+ const binding = WebAssembly.Module.imports(module).filter((item) => item.kind === 'memory');
111
+ if (binding.length !== 1)
112
+ throw new TypeError('one lane memory required');
113
+ this.#dirty = this.#data;
114
+ this.#owned = memoryBytes;
115
+ this.#marks = undefined;
116
+ let arena;
117
+ if (this.#inline) {
118
+ const options = { batch: 1, logCapacity: this.#inline.logEntries, slotBytes: 64 };
119
+ const fit = iterationFit(memoryBytes, options);
120
+ if (!fit)
121
+ throw new RangeError('lane arena does not fit');
122
+ arena = iterationArena(fit.base, fit.memoryBytes, options);
123
+ }
124
+ const total = arena ? arena.memoryBytes / 65536 : pages;
125
+ this.#memory = new WebAssembly.Memory({
126
+ initial: total,
127
+ maximum: Math.max(this.#maximum, total),
128
+ shared: true
129
+ });
130
+ this.#instance = new WebAssembly.Instance(module, {
131
+ [binding[0].module]: { [binding[0].name]: this.#memory },
132
+ folio: {
133
+ load: (...args) => this.#active.load(...args),
134
+ store: (...args) => this.#active.store(...args),
135
+ load64: (...args) => this.#active.load64(...args),
136
+ store64: (...args) => this.#active.store64(...args),
137
+ copy: (...args) => this.#active.copy(...args),
138
+ fill: (...args) => this.#active.fill(...args),
139
+ exhausted: () => {
140
+ throw new SpeculationLimit('speculative instruction budget');
141
+ }
142
+ }
143
+ });
144
+ if (arena) {
145
+ const exported = this.#instance.exports;
146
+ const globals = {};
147
+ for (const [key, name] of Object.entries(markGlobals))
148
+ globals[key] = exported[name];
149
+ globals.readBitmap.value = arena.rmaps;
150
+ globals.writeBitmap.value = arena.wmaps;
151
+ globals.logLimit.value =
152
+ arena.logs + this.#inline.logEntries * iterationEntryBytes;
153
+ globals.stampAddress.value = arena.stamp;
154
+ globals.arenaLow.value = memoryBytes;
155
+ globals.arenaEnd.value = arena.memoryBytes;
156
+ this.#marks = { arena, ownerBytes: memoryBytes, globals };
157
+ }
158
+ }
159
+ const bytes = new Uint8Array(this.#memory.buffer, 0, memoryBytes);
160
+ if (ranged) {
161
+ // tracked stores are buffered, so only the previous frame's ranges can be nonzero
162
+ if (this.#dirty === 'all')
163
+ bytes.fill(0);
164
+ else
165
+ clearRanges(bytes, this.#dirty);
166
+ this.#dirty = ranged.shipped;
167
+ restoreRanges(bytes, payload, ranged.shipped);
168
+ }
169
+ else {
170
+ this.#dirty = 'all';
171
+ restoreSnapshot(bytes, payload, header.snapshot);
172
+ }
173
+ let remaining = header.maxBytes;
174
+ const results = [];
175
+ for (const call of header.calls) {
176
+ if (remaining <= 0) {
177
+ results.push({ reads: [], writes: [], exhausted: true });
178
+ continue;
179
+ }
180
+ if (this.#marks) {
181
+ const done = this.#inlineCall(call, header.fuel, remaining, ranged?.shipped, runs);
182
+ remaining -= done.charged;
183
+ results.push(this.#annotate(done.result, ranged, done.lost));
184
+ continue;
185
+ }
186
+ this.#active = transaction(this.#memory, remaining);
187
+ let error, value;
188
+ try {
189
+ this.#instance.exports.__folio_set_fuel(header.fuel);
190
+ const entry = this.#instance.exports[call.export];
191
+ if (typeof entry !== 'function')
192
+ throw new TypeError('unknown lane export');
193
+ value = entry(...call.args);
194
+ }
195
+ catch (caught) {
196
+ error = caught;
197
+ }
198
+ if (error instanceof RangeError) {
199
+ // ranges mode keeps the reads so escapes before the overflow still reach the owner
200
+ const seen = ranged ? this.#active.result().reads : [];
201
+ results.push(this.#annotate({ reads: seen, writes: [], exhausted: true }, ranged));
202
+ continue;
203
+ }
204
+ const result = this.#active.result(value, error);
205
+ remaining -= result.reads.length + result.writes.length;
206
+ results.push(this.#annotate(result, ranged));
207
+ }
208
+ this.#active = undefined;
209
+ return encodeResults(header, results, this.#maximumFrameBytes, runs);
210
+ }
211
+ // runs one call on the inline-tracked module, reads its marks and log back, and rolls it all back
212
+ #inlineCall(call, fuel, remaining, shipped, runs = false) {
213
+ const { arena, ownerBytes, globals } = this.#marks;
214
+ const entryBytes = iterationEntryBytes;
215
+ const buffer = this.#memory.buffer;
216
+ const u8 = new Uint8Array(buffer);
217
+ const u32 = new Uint32Array(buffer);
218
+ const exports = this.#instance.exports;
219
+ globals.logPointer.value = arena.logs;
220
+ globals.violation.value = 0;
221
+ let error, value;
222
+ try {
223
+ exports.__folio_set_fuel(fuel);
224
+ const entry = exports[call.export];
225
+ if (typeof entry !== 'function')
226
+ throw new TypeError('unknown lane export');
227
+ value = entry(...call.args);
228
+ }
229
+ catch (caught) {
230
+ error = caught;
231
+ }
232
+ const end = globals.logPointer.value >>> 0;
233
+ const limit = globals.logLimit.value >>> 0;
234
+ if (globals.violation.value >>> 0)
235
+ error = new WebAssembly.RuntimeError('memory access out of bounds');
236
+ const logFull = error instanceof WebAssembly.RuntimeError &&
237
+ /unreachable/.test(error.message) &&
238
+ limit - end < entryBytes;
239
+ // a write granule stores its prior bytes, so only bytes that changed are writes
240
+ const entries = (end - arena.logs) / entryBytes;
241
+ const writes = [];
242
+ const pieces = [];
243
+ const written = [];
244
+ for (let e = 0; e < entries; e++) {
245
+ const at = arena.logs + e * entryBytes;
246
+ const granule = u32[at >> 2];
247
+ written.push([granule, 32]);
248
+ if (runs)
249
+ for (let i = 0; i < 32;) {
250
+ if (u8[granule + i] === u8[at + 8 + i]) {
251
+ i++;
252
+ continue;
253
+ }
254
+ let j = i + 1;
255
+ while (j < 32 && u8[granule + j] !== u8[at + 8 + j])
256
+ j++;
257
+ pieces.push([granule + i, u8.slice(granule + i, granule + j)]);
258
+ i = j;
259
+ }
260
+ else
261
+ for (let i = 0; i < 32; i++) {
262
+ const now = u8[granule + i];
263
+ if (now !== u8[at + 8 + i])
264
+ writes.push([granule + i, now]);
265
+ }
266
+ u8.copyWithin(granule, at + 8, at + entryBytes);
267
+ u8[arena.wmaps + (granule >>> 8)] = 0;
268
+ }
269
+ // a failed call may have set a write bit before its entry was logged
270
+ if (error)
271
+ u8.fill(0, arena.wmaps, arena.wmaps + arena.wsize);
272
+ const spans = [];
273
+ const words = new Uint32Array(buffer, arena.rmaps, arena.rsize / 4);
274
+ for (let k = 0; k < words.length; k++) {
275
+ const word = words[k];
276
+ if (!word)
277
+ continue;
278
+ words[k] = 0;
279
+ for (let b = 0; b < 32; b++)
280
+ if ((word >>> b) & 1)
281
+ spans.push([(k * 32 + b) * 64, 64]);
282
+ }
283
+ let reads = RangeSet.of(spans);
284
+ // bytes of a written granule that were not shipped read as zero here, so the owner must ship them
285
+ if (shipped)
286
+ reads = reads.union(RangeSet.of(written).subtract(shipped));
287
+ const lost = shipped ? reads.subtract(shipped) : undefined;
288
+ const packed = runs ? packWrites(pieces) : undefined;
289
+ const charged = reads.length + (packed ? packed.data.length : writes.length);
290
+ const addresses = (set, cap) => {
291
+ const out = [];
292
+ for (const [start, length] of set.spans())
293
+ for (let i = 0; i < length && out.length < cap; i++)
294
+ out.push(start + i);
295
+ return out;
296
+ };
297
+ const failure = error instanceof SpeculationLimit || logFull
298
+ ? { exhausted: true }
299
+ : error
300
+ ? {
301
+ trap: error instanceof Error ? error.message : String(error),
302
+ errorKind: error instanceof Error ? error.name : 'Error'
303
+ }
304
+ : {};
305
+ if (charged > remaining)
306
+ return {
307
+ charged,
308
+ lost,
309
+ result: runs
310
+ ? {
311
+ reads: [],
312
+ writes: [],
313
+ readRuns: capRuns((lost ?? RangeSet.empty).runs(), remaining),
314
+ writeRuns: new Uint32Array(),
315
+ writeData: new Uint8Array(),
316
+ exhausted: true
317
+ }
318
+ : { reads: lost ? addresses(lost, remaining) : [], writes: [], exhausted: true }
319
+ };
320
+ return {
321
+ charged,
322
+ lost,
323
+ result: packed
324
+ ? {
325
+ value,
326
+ reads: [],
327
+ writes: [],
328
+ readRuns: capRuns(reads.clip(ownerBytes).runs(), remaining),
329
+ writeRuns: packed.runs,
330
+ writeData: packed.data,
331
+ ...failure
332
+ }
333
+ : {
334
+ value,
335
+ reads: addresses(reads.clip(ownerBytes), remaining),
336
+ writes,
337
+ ...failure
338
+ }
339
+ };
340
+ }
341
+ #annotate(result, ranged, known) {
342
+ if (!ranged)
343
+ return result;
344
+ const lost = known ?? escapes(result.reads, ranged.shipped);
345
+ if (!lost.count)
346
+ return result;
347
+ return {
348
+ ...result,
349
+ escapes: lost.spans(),
350
+ inconclusive: Boolean(result.trap || result.exhausted)
351
+ };
352
+ }
353
+ /** Drops the instance and its memory; a later frame builds them again. */
354
+ close() {
355
+ this.#dirty = 'all';
356
+ this.#active = this.#instance = this.#memory = this.#marks = undefined;
357
+ this.#owned = 0;
358
+ }
359
+ }
360
+ /**
361
+ * The owner side of the managed backend. The original Wasm stack keeps control flow and host
362
+ * effects, and JSPI joins regions that lanes execute over copied snapshots.
363
+ */
364
+ export class ManagedFolio {
365
+ /** The original native exports. */
366
+ exports;
367
+ /** Optimization refusals and fallbacks seen so far. */
368
+ diagnostics = [];
369
+ #lanes;
370
+ #instance;
371
+ #serial = new WebAssembly.Global({ value: 'i32', mutable: true }, 1);
372
+ #pendingGlobal = new WebAssembly.Global({ value: 'i32', mutable: true }, 0);
373
+ #controlled = new Map();
374
+ #promising = new Map();
375
+ #maximumSnapshotBytes;
376
+ #maximumFrameBytes;
377
+ #fuel;
378
+ #maxBytes;
379
+ #snapshotEncoding;
380
+ #ranges;
381
+ #memo;
382
+ #memoModule = '';
383
+ #runs;
384
+ #session = crypto.randomUUID();
385
+ #memory;
386
+ #scheduler;
387
+ #epoch = 0;
388
+ #sequence = 0;
389
+ #busy = false;
390
+ #closed = false;
391
+ #pending;
392
+ #closing;
393
+ constructor(artifact, options) {
394
+ if (options.runs !== undefined && typeof options.runs !== 'boolean')
395
+ throw new TypeError('invalid runs option');
396
+ this.#runs = options.runs === true;
397
+ if (options.memo) {
398
+ this.#memo = new RegionMemo(options.memo);
399
+ this.#memoModule = moduleIdentity(artifact.transactional ?? artifact.original);
400
+ }
401
+ this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
402
+ if (!['auto', 'dense'].includes(this.#snapshotEncoding))
403
+ throw new TypeError('invalid snapshot encoding');
404
+ if (options.ranges)
405
+ this.#ranges = {
406
+ maxRounds: integer(options.ranges.maxRounds ?? 3, 1, 8, 'range rounds'),
407
+ cache: new FootprintCache(integer(options.ranges.cacheEntries ?? 1024, 1, 65536, 'footprint cache size'))
408
+ };
409
+ this.#lanes = options.lanes;
410
+ integer(this.#lanes.length, 1, 64, 'lane count');
411
+ this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ?? 31 * 1048576, 65536, 0x100000000, 'snapshot limit');
412
+ this.#maximumFrameBytes = integer(options.maximumFrameBytes ??
413
+ Math.min(this.#maximumSnapshotBytes + 1048576, rpcFrameLimit), 65536, 0x100100000, 'frame limit');
414
+ this.#fuel = integer(options.fuel ?? 100000000, 1, 1000000000, 'fuel');
415
+ this.#maxBytes = integer(options.maxTransactionBytes ?? 262144, 8, 1048576, 'tracking budget');
416
+ const runtime = WebAssembly;
417
+ const control = artifact.control;
418
+ let module = artifact.original, enabled = false;
419
+ if (control &&
420
+ artifact.coordinator &&
421
+ runtime.Suspending &&
422
+ runtime.promising &&
423
+ this.#lanes.length > 1) {
424
+ const original = WebAssembly.Module.imports(artifact.original);
425
+ const retained = WebAssembly.Module.imports(artifact.coordinator).filter((item) => item.module !== control.namespace);
426
+ if (JSON.stringify(original) === JSON.stringify(retained)) {
427
+ module = artifact.coordinator;
428
+ enabled = true;
429
+ }
430
+ else
431
+ this.diagnostics.push('rewritten import sequence differs; using native execution');
432
+ }
433
+ else
434
+ this.diagnostics.push('no active coordinator; using native execution');
435
+ const supplied = options.imports ?? Object.create(null);
436
+ const memories = WebAssembly.Module.imports(artifact.original).filter((item) => item.kind === 'memory');
437
+ if (memories.length > 1 && options.memory)
438
+ throw new TypeError('bind multiple memories by name in imports');
439
+ const automatic = new Map();
440
+ const imports = new Proxy(Object.create(null), {
441
+ get: (_, namespace) => {
442
+ if (enabled && namespace === control.namespace) {
443
+ const bindings = {
444
+ [control.serialGlobal]: this.#serial,
445
+ [control.pendingGlobal]: this.#pendingGlobal,
446
+ barrier: new runtime.Suspending(() => this.#scheduler?.flush()),
447
+ poll: new runtime.Suspending(() => this.#scheduler?.poll())
448
+ };
449
+ for (const region of control.regions)
450
+ bindings[region.importName] = new runtime.Suspending((...args) => {
451
+ if (this.#scheduler && this.#serial.value === 0)
452
+ return this.#scheduler.enqueue({
453
+ export: region.exportName,
454
+ args
455
+ });
456
+ this.#instance.exports[region.exportName](...args);
457
+ });
458
+ return bindings;
459
+ }
460
+ const bound = Reflect.get(supplied, namespace, supplied);
461
+ if (!memories.some((item) => item.module === namespace))
462
+ return bound;
463
+ if (bound !== undefined &&
464
+ (bound === null || !['object', 'function'].includes(typeof bound)))
465
+ return bound;
466
+ return new Proxy(Object.create(null), {
467
+ get: (_, name) => {
468
+ if (!memories.some((item) => item.module === namespace && item.name === name))
469
+ return bound === undefined
470
+ ? undefined
471
+ : Reflect.get(bound, name, bound);
472
+ let memory = (memories.length === 1 ? options.memory : undefined) ??
473
+ (bound === undefined ? undefined : Reflect.get(bound, name, bound));
474
+ if (memory === undefined) {
475
+ const key = JSON.stringify([namespace, name]);
476
+ memory = automatic.get(key);
477
+ if (!memory) {
478
+ const limits = artifact.memories?.find((item) => item.module === namespace && item.name === name);
479
+ if (!limits || limits.memory64)
480
+ throw new TypeError(`provide imported memory ${namespace}.${name}`);
481
+ memory = new WebAssembly.Memory({
482
+ initial: limits.initial,
483
+ ...(limits.maximum === undefined
484
+ ? {}
485
+ : { maximum: limits.maximum }),
486
+ shared: limits.shared
487
+ });
488
+ automatic.set(key, memory);
489
+ }
490
+ }
491
+ if (memories.length === 1)
492
+ this.#memory = memory;
493
+ return memory;
494
+ }
495
+ });
496
+ }
497
+ });
498
+ this.#instance = new WebAssembly.Instance(module, imports);
499
+ this.exports = Object.create(null);
500
+ for (const item of WebAssembly.Module.exports(artifact.original))
501
+ Object.defineProperty(this.exports, item.name, {
502
+ value: this.#instance.exports[item.name],
503
+ enumerable: true
504
+ });
505
+ Object.freeze(this.exports);
506
+ if (enabled) {
507
+ this.#memory = this.#instance.exports[control.memoryExport];
508
+ for (const name of control.entries)
509
+ this.#controlled.set(name, runtime.promising(this.#instance.exports[name]));
510
+ }
511
+ else if (!this.#memory) {
512
+ const own = Object.values(this.exports).filter((item) => item instanceof WebAssembly.Memory);
513
+ if (own.length === 1)
514
+ this.#memory = own[0];
515
+ }
516
+ for (const name of options.promising ?? []) {
517
+ if (!runtime.promising || typeof this.exports[name] !== 'function')
518
+ throw new TypeError('invalid promising export');
519
+ this.#promising.set(name, runtime.promising(this.exports[name]));
520
+ }
521
+ }
522
+ /** The canonical memory, which must fit the owner runtime. Throws when there is no unique one. */
523
+ get memory() {
524
+ if (!this.#memory)
525
+ throw new TypeError('no unique accessible memory');
526
+ return this.#memory;
527
+ }
528
+ /** Runs one entry; regions go to lanes and results commit in order. One run at a time. */
529
+ run(name, args = [], options = {}) {
530
+ if (this.#closed)
531
+ return Promise.reject(new Error('folio is closed'));
532
+ if (this.#busy)
533
+ return Promise.reject(new Error('memory already has an active run'));
534
+ const entry = this.exports[name];
535
+ if (typeof entry !== 'function')
536
+ return Promise.reject(new TypeError('unknown function export'));
537
+ const width = Math.min(this.#lanes.length, integer(options.maximumWorkers ?? this.#lanes.length, 1, 64, 'maximumWorkers'));
538
+ this.#busy = true;
539
+ let resolve, reject;
540
+ const pending = new Promise((success, failure) => {
541
+ resolve = success;
542
+ reject = failure;
543
+ });
544
+ this.#pending = pending;
545
+ void pending
546
+ .finally(() => {
547
+ this.#busy = false;
548
+ this.#pending = undefined;
549
+ })
550
+ .catch(() => { });
551
+ void this.#execute(name, entry, args, width, options.parallel === 'off').then(resolve, reject);
552
+ return pending;
553
+ }
554
+ async #execute(name, entry, args, width, serial) {
555
+ const bytes = { sent: 0, received: 0 };
556
+ const memoBefore = this.#memo?.stats;
557
+ let snapshotBytes = 0;
558
+ let transportFallbacks = 0;
559
+ const tally = {
560
+ rangeBytes: 0,
561
+ rounds: { batches: 0, total: 0, max: 0 },
562
+ escapeRounds: 0,
563
+ rangeFallbacks: { snapshot: 0, serial: 0 },
564
+ footprintHits: 0
565
+ };
566
+ const runReplies = { runs: 0, addresses: 0 };
567
+ const finish = (report) => ({
568
+ ...report,
569
+ backend: 'managed-coherent',
570
+ memoryMode: 'copied',
571
+ transportBytes: bytes,
572
+ transportFallbacks,
573
+ ...(this.#ranges ? tally : {}),
574
+ ...(this.#runs ? { runReplies } : {}),
575
+ ...(this.#memo ? memoTally(this.#memo.stats, memoBefore) : {})
576
+ });
577
+ const controlled = this.#controlled.get(name);
578
+ if (serial ||
579
+ !controlled ||
580
+ width < 2 ||
581
+ args.some((value) => typeof value !== 'number' && typeof value !== 'bigint')) {
582
+ const value = this.#promising.has(name)
583
+ ? await this.#promising.get(name)(...args)
584
+ : entry(...args);
585
+ return finish({
586
+ values: [value],
587
+ workers: 0,
588
+ regions: 1,
589
+ replayed: 0,
590
+ fallbacks: 0,
591
+ mode: 'serial'
592
+ });
593
+ }
594
+ const epoch = ++this.#epoch;
595
+ let snapshotGeneration = -1, snapshot;
596
+ const scheduler = new Coordinator({
597
+ memory: this.memory,
598
+ workerMemory: this.memory,
599
+ width,
600
+ profile: false,
601
+ pending: this.#pendingGlobal,
602
+ native: (call) => {
603
+ const previous = this.#serial.value;
604
+ this.#serial.value = 1;
605
+ try {
606
+ this.#instance.exports[call.export](...call.args);
607
+ }
608
+ finally {
609
+ this.#serial.value = previous;
610
+ }
611
+ },
612
+ dispatch: (lane, calls, generation) => this.#memoized(lane, calls, generation, async (lane, calls, generation) => {
613
+ const exhausted = () => calls.map(() => ({ reads: [], writes: [], exhausted: true }));
614
+ const identify = () => ({
615
+ session: this.#session,
616
+ epoch,
617
+ sequence: ++this.#sequence
618
+ });
619
+ const exchange = async (frame, identity) => {
620
+ bytes.sent += frame.length;
621
+ const response = await this.#lanes[lane].execute(frame);
622
+ bytes.received += response.length;
623
+ const decoded = decodeResults(response, identity, {
624
+ maximumFrameBytes: this.#maximumFrameBytes,
625
+ memoryBytes: this.memory.buffer.byteLength,
626
+ maxBytes: this.#maxBytes,
627
+ calls: calls.length,
628
+ runs: this.#runs
629
+ });
630
+ if (this.#runs)
631
+ runReplies[decoded[0]?.readRuns ? 'runs' : 'addresses']++;
632
+ return decoded;
633
+ };
634
+ const snapshotFrame = (identity) => {
635
+ if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
636
+ throw new RangeError(`snapshot of ${this.memory.buffer.byteLength} bytes exceeds the limit of ${this.#maximumSnapshotBytes} bytes`);
637
+ if (snapshotGeneration !== generation) {
638
+ const memory = new Uint8Array(this.memory.buffer);
639
+ snapshot =
640
+ this.#snapshotEncoding === 'dense'
641
+ ? { payload: memory }
642
+ : encodeSnapshot(memory);
643
+ snapshotGeneration = generation;
644
+ }
645
+ const frame = encodeFrame({
646
+ ...identity,
647
+ calls,
648
+ fuel: this.#fuel,
649
+ maxBytes: this.#maxBytes,
650
+ ...(this.#runs ? { runs: runsVersion } : {}),
651
+ ...(snapshot.snapshot ? { snapshot: snapshot.snapshot } : {})
652
+ }, snapshot.payload, this.#maximumFrameBytes);
653
+ snapshotBytes += this.memory.buffer.byteLength;
654
+ return frame;
655
+ };
656
+ // a round with escapes only teaches the footprint; its results are never returned
657
+ const learn = async () => {
658
+ const ranges = this.#ranges;
659
+ const keys = calls.map((call) => FootprintCache.key(call.export, call.args));
660
+ let footprint = RangeSet.empty;
661
+ for (const key of keys) {
662
+ const known = ranges.cache.get(key);
663
+ if (!known)
664
+ continue;
665
+ tally.footprintHits++;
666
+ footprint = footprint.union(known);
667
+ }
668
+ tally.rounds.batches++;
669
+ let rounds = 0;
670
+ try {
671
+ while (rounds < ranges.maxRounds) {
672
+ const identity = identify();
673
+ const memory = new Uint8Array(this.memory.buffer);
674
+ let sent;
675
+ try {
676
+ sent = encodeRangesFrame({
677
+ ...identity,
678
+ calls,
679
+ fuel: this.#fuel,
680
+ maxBytes: this.#maxBytes,
681
+ ...(this.#runs ? { runs: runsVersion } : {})
682
+ }, memory, footprint, this.#maximumFrameBytes);
683
+ }
684
+ catch (error) {
685
+ if (!(error instanceof RangeError))
686
+ throw error;
687
+ this.diagnostics.push(`ranges frame not sent: ${error.message}`);
688
+ return undefined;
689
+ }
690
+ rounds++;
691
+ tally.rounds.total++;
692
+ tally.rangeBytes += sent.shipped.length;
693
+ const results = await exchange(sent.frame, identity);
694
+ // the lane's own escape list is not trusted; the read set decides
695
+ const lost = results.map((result) => resultEscapes(result, sent.shipped));
696
+ if (lost.every((set) => !set.count))
697
+ return results;
698
+ tally.escapeRounds++;
699
+ lost.forEach((set, index) => {
700
+ if (!set.count)
701
+ return;
702
+ const grown = set.round(rangePage, memory.length);
703
+ ranges.cache.learn(keys[index], grown);
704
+ footprint = footprint.union(grown);
705
+ });
706
+ }
707
+ return undefined;
708
+ }
709
+ finally {
710
+ tally.rounds.max = Math.max(tally.rounds.max, rounds);
711
+ }
712
+ };
713
+ try {
714
+ if (this.#ranges) {
715
+ const done = await learn();
716
+ if (done)
717
+ return done;
718
+ const identity = identify();
719
+ let frame;
720
+ try {
721
+ frame = snapshotFrame(identity);
722
+ }
723
+ catch (error) {
724
+ if (!(error instanceof RangeError))
725
+ throw error;
726
+ tally.rangeFallbacks.serial++;
727
+ this.diagnostics.push(`ranges exhausted; native fallback: ${error.message}`);
728
+ return exhausted();
729
+ }
730
+ tally.rangeFallbacks.snapshot++;
731
+ return await exchange(frame, identity);
732
+ }
733
+ const identity = identify();
734
+ return await exchange(snapshotFrame(identity), identity);
735
+ }
736
+ catch (error) {
737
+ transportFallbacks++;
738
+ this.diagnostics.push(`lane unavailable; native fallback: ${error instanceof Error ? error.message : String(error)}`);
739
+ return exhausted();
740
+ }
741
+ })
742
+ });
743
+ this.#scheduler = scheduler;
744
+ this.#serial.value = 0;
745
+ try {
746
+ let value, failure, failed = false;
747
+ try {
748
+ value = await controlled(...args);
749
+ }
750
+ catch (error) {
751
+ failed = true;
752
+ failure = error;
753
+ }
754
+ await scheduler.flush();
755
+ if (failed)
756
+ throw failure;
757
+ scheduler.report.values = [value];
758
+ scheduler.report.snapshotBytes = snapshotBytes;
759
+ return finish(scheduler.report);
760
+ }
761
+ finally {
762
+ this.#serial.value = 1;
763
+ this.#pendingGlobal.value = 0;
764
+ this.#scheduler = undefined;
765
+ }
766
+ }
767
+ /**
768
+ * Answers calls from the memo where it can, sends the rest to `execute`, and records their clean
769
+ * results. Lookups and records read canonical memory, which no commit changes until every lane
770
+ * of the batch has returned.
771
+ */
772
+ async #memoized(lane, calls, generation, execute) {
773
+ const memo = this.#memo;
774
+ if (!memo)
775
+ return execute(lane, calls, generation);
776
+ const memory = new Uint8Array(this.memory.buffer);
777
+ const keys = calls.map((call) => RegionMemo.keyOf(this.#memoModule, call.export, call.args));
778
+ const hits = await Promise.all(keys.map((key) => key === undefined ? undefined : memo.lookup(key, memory, { runs: this.#runs })));
779
+ const missing = calls.filter((_, index) => !hits[index]);
780
+ const started = performance.now();
781
+ const fresh = missing.length ? await execute(lane, missing, generation) : [];
782
+ const ms = missing.length ? (performance.now() - started) / missing.length : 0;
783
+ const results = [];
784
+ let next = 0;
785
+ for (let index = 0; index < calls.length; index++) {
786
+ const hit = hits[index];
787
+ if (hit) {
788
+ results.push(hit.result);
789
+ continue;
790
+ }
791
+ const result = fresh[next++];
792
+ results.push(result);
793
+ const key = keys[index];
794
+ if (key !== undefined)
795
+ await memo.record(key, memory, result, ms);
796
+ }
797
+ return results;
798
+ }
799
+ /** Waits for the active run, then closes every lane. A failed disposer does not skip the rest. */
800
+ close() {
801
+ if (this.#closing)
802
+ return this.#closing;
803
+ this.#closed = true;
804
+ this.#closing = (async () => {
805
+ await this.#pending?.catch(() => { });
806
+ const outcomes = await Promise.allSettled(this.#lanes.map(async (lane) => lane.close?.()));
807
+ const failed = outcomes.find((result) => result.status === 'rejected');
808
+ if (failed?.status === 'rejected')
809
+ throw failed.reason;
810
+ })();
811
+ return this.#closing;
812
+ }
813
+ /** `await using` support; equivalent to `close()`. */
814
+ [Symbol.asyncDispose]() {
815
+ return this.close();
816
+ }
817
+ }