@gmitch215/folio 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +455 -26
  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/bake.d.ts +8 -3
  7. package/dist/bake.js +5 -2
  8. package/dist/boundaries.d.ts +59 -0
  9. package/dist/boundaries.js +127 -0
  10. package/dist/certified.d.ts +66 -0
  11. package/dist/certified.js +192 -0
  12. package/dist/certify.d.ts +98 -0
  13. package/dist/certify.js +2628 -0
  14. package/dist/compiler.d.ts +37 -1
  15. package/dist/compiler.js +116 -1
  16. package/dist/context.d.ts +47 -0
  17. package/dist/context.js +139 -0
  18. package/dist/coordinator.d.ts +1 -1
  19. package/dist/coordinator.js +54 -5
  20. package/dist/extract.d.ts +114 -1
  21. package/dist/extract.js +1011 -242
  22. package/dist/fold.d.ts +32 -0
  23. package/dist/fold.js +105 -0
  24. package/dist/frames.d.ts +20 -2
  25. package/dist/frames.js +205 -10
  26. package/dist/inline.d.ts +182 -0
  27. package/dist/inline.js +766 -0
  28. package/dist/iteration-admission.d.ts +185 -0
  29. package/dist/iteration-admission.js +201 -0
  30. package/dist/iteration-layout.d.ts +135 -0
  31. package/dist/iteration-layout.js +169 -0
  32. package/dist/iteration-owner.d.ts +45 -0
  33. package/dist/iteration-owner.js +223 -0
  34. package/dist/iteration-worker.d.ts +1 -0
  35. package/dist/iteration-worker.js +216 -0
  36. package/dist/iteration.d.ts +329 -0
  37. package/dist/iteration.js +1210 -0
  38. package/dist/lease.d.ts +45 -0
  39. package/dist/lease.js +274 -0
  40. package/dist/managed.d.ts +78 -0
  41. package/dist/managed.js +448 -27
  42. package/dist/memo.d.ts +99 -0
  43. package/dist/memo.js +250 -0
  44. package/dist/node.d.ts +61 -5
  45. package/dist/node.js +421 -23
  46. package/dist/ownership-redirect.d.ts +30 -0
  47. package/dist/ownership-redirect.js +179 -0
  48. package/dist/ownership-slices.d.ts +44 -0
  49. package/dist/ownership-slices.js +72 -0
  50. package/dist/ownership.d.ts +161 -0
  51. package/dist/ownership.js +6568 -0
  52. package/dist/ranges.d.ts +78 -0
  53. package/dist/ranges.js +263 -0
  54. package/dist/read-scan.d.ts +18 -0
  55. package/dist/read-scan.js +94 -0
  56. package/dist/read-windows.d.ts +103 -0
  57. package/dist/read-windows.js +244 -0
  58. package/dist/router-worker.d.ts +1 -0
  59. package/dist/router-worker.js +4 -0
  60. package/dist/router.d.ts +203 -0
  61. package/dist/router.js +667 -0
  62. package/dist/runs.d.ts +44 -0
  63. package/dist/runs.js +182 -0
  64. package/dist/slices-worker.d.ts +1 -0
  65. package/dist/slices-worker.js +38 -0
  66. package/dist/slices.d.ts +126 -0
  67. package/dist/slices.js +441 -0
  68. package/dist/tasks.d.ts +14 -4
  69. package/dist/tasks.js +23 -9
  70. package/dist/transaction.d.ts +10 -0
  71. package/package.json +44 -4
package/dist/managed.js CHANGED
@@ -1,6 +1,40 @@
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, runsVersion, snapshotLength, validateIdentity } from "./frames.js";
3
+ import { iterationArena, iterationEntryBytes, iterationFit } from "./iteration-layout.js";
4
+ import { RegionMemo } from "./memo.js";
5
+ import { clearRanges, decodeRanges, encodeRangesFrame, escapes, FootprintCache, rangePage, RangeSet, restoreRanges, resultEscapes } from "./ranges.js";
6
+ import { capRuns, packWrites } from "./runs.js";
3
7
  import { SpeculationLimit, transaction } from "./transaction.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
+ }
4
38
  function integer(value, minimum, maximum, label) {
5
39
  if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
6
40
  throw new RangeError(`invalid ${label}`);
@@ -16,11 +50,26 @@ export class FolioLane {
16
50
  #maximum;
17
51
  #maximumFrameBytes;
18
52
  #maximumMemoryBytes;
53
+ #inline;
19
54
  #memory;
20
55
  #instance;
56
+ #marks;
21
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';
22
64
  constructor(module, options) {
23
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);
24
73
  this.#initial = integer(options.initial, 0, 65536, 'initial memory');
25
74
  this.#maximum = integer(options.maximum, this.#initial, 65536, 'maximum memory');
26
75
  this.#maximumMemoryBytes = options.maximumMemoryBytes ?? 32 * 1048576;
@@ -43,22 +92,42 @@ export class FolioLane {
43
92
  call.args.some((value) => typeof value !== 'number' && typeof value !== 'bigint'))
44
93
  throw new TypeError('invalid lane call');
45
94
  }
46
- const pages = payload.length / 65536;
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;
47
103
  if (!Number.isInteger(pages) ||
48
104
  pages < this.#initial ||
49
105
  pages > this.#maximum ||
50
- payload.length > this.#maximumMemoryBytes)
106
+ memoryBytes > this.#maximumMemoryBytes)
51
107
  throw new RangeError('invalid lane snapshot');
52
- if (!this.#memory || !this.#instance || this.#memory.buffer.byteLength !== payload.length) {
53
- const binding = WebAssembly.Module.imports(this.#module).filter((item) => item.kind === 'memory');
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');
54
111
  if (binding.length !== 1)
55
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;
56
125
  this.#memory = new WebAssembly.Memory({
57
- initial: pages,
58
- maximum: this.#maximum,
126
+ initial: total,
127
+ maximum: Math.max(this.#maximum, total),
59
128
  shared: true
60
129
  });
61
- this.#instance = new WebAssembly.Instance(this.#module, {
130
+ this.#instance = new WebAssembly.Instance(module, {
62
131
  [binding[0].module]: { [binding[0].name]: this.#memory },
63
132
  folio: {
64
133
  load: (...args) => this.#active.load(...args),
@@ -72,8 +141,35 @@ export class FolioLane {
72
141
  }
73
142
  }
74
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);
75
172
  }
76
- new Uint8Array(this.#memory.buffer).set(payload);
77
173
  let remaining = header.maxBytes;
78
174
  const results = [];
79
175
  for (const call of header.calls) {
@@ -81,6 +177,12 @@ export class FolioLane {
81
177
  results.push({ reads: [], writes: [], exhausted: true });
82
178
  continue;
83
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
+ }
84
186
  this.#active = transaction(this.#memory, remaining);
85
187
  let error, value;
86
188
  try {
@@ -94,19 +196,165 @@ export class FolioLane {
94
196
  error = caught;
95
197
  }
96
198
  if (error instanceof RangeError) {
97
- results.push({ reads: [], writes: [], exhausted: true });
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));
98
202
  continue;
99
203
  }
100
204
  const result = this.#active.result(value, error);
101
205
  remaining -= result.reads.length + result.writes.length;
102
- results.push(result);
206
+ results.push(this.#annotate(result, ranged));
103
207
  }
104
208
  this.#active = undefined;
105
- return encodeResults(header, results, this.#maximumFrameBytes);
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
+ };
106
352
  }
107
353
  /** Drops the instance and its memory; a later frame builds them again. */
108
354
  close() {
109
- this.#active = this.#instance = this.#memory = undefined;
355
+ this.#dirty = 'all';
356
+ this.#active = this.#instance = this.#memory = this.#marks = undefined;
357
+ this.#owned = 0;
110
358
  }
111
359
  }
112
360
  /**
@@ -129,6 +377,11 @@ export class ManagedFolio {
129
377
  #maximumFrameBytes;
130
378
  #fuel;
131
379
  #maxBytes;
380
+ #snapshotEncoding;
381
+ #ranges;
382
+ #memo;
383
+ #memoModule = '';
384
+ #runs;
132
385
  #session = crypto.randomUUID();
133
386
  #memory;
134
387
  #scheduler;
@@ -139,11 +392,27 @@ export class ManagedFolio {
139
392
  #pending;
140
393
  #closing;
141
394
  constructor(artifact, options) {
395
+ if (options.runs !== undefined && typeof options.runs !== 'boolean')
396
+ throw new TypeError('invalid runs option');
397
+ this.#runs = options.runs === true;
398
+ if (options.memo) {
399
+ this.#memo = new RegionMemo(options.memo);
400
+ this.#memoModule = moduleIdentity(artifact.transactional ?? artifact.original);
401
+ }
142
402
  this.#artifact = artifact;
403
+ this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
404
+ if (!['auto', 'dense'].includes(this.#snapshotEncoding))
405
+ throw new TypeError('invalid snapshot encoding');
406
+ if (options.ranges)
407
+ this.#ranges = {
408
+ maxRounds: integer(options.ranges.maxRounds ?? 3, 1, 8, 'range rounds'),
409
+ cache: new FootprintCache(integer(options.ranges.cacheEntries ?? 1024, 1, 65536, 'footprint cache size'))
410
+ };
143
411
  this.#lanes = options.lanes;
144
412
  integer(this.#lanes.length, 1, 64, 'lane count');
145
- this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ?? 32 * 1048576, 65536, 0x100000000, 'snapshot limit');
146
- this.#maximumFrameBytes = integer(options.maximumFrameBytes ?? this.#maximumSnapshotBytes + 1048576, 65536, 0x100100000, 'frame limit');
413
+ this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ?? 31 * 1048576, 65536, 0x100000000, 'snapshot limit');
414
+ this.#maximumFrameBytes = integer(options.maximumFrameBytes ??
415
+ Math.min(this.#maximumSnapshotBytes + 1048576, rpcFrameLimit), 65536, 0x100100000, 'frame limit');
147
416
  this.#fuel = integer(options.fuel ?? 100000000, 1, 1000000000, 'fuel');
148
417
  this.#maxBytes = integer(options.maxTransactionBytes ?? 262144, 8, 1048576, 'tracking budget');
149
418
  const runtime = WebAssembly;
@@ -286,14 +555,26 @@ export class ManagedFolio {
286
555
  }
287
556
  async #execute(name, entry, args, width, serial) {
288
557
  const bytes = { sent: 0, received: 0 };
558
+ const memoBefore = this.#memo?.stats;
289
559
  let snapshotBytes = 0;
290
560
  let transportFallbacks = 0;
561
+ const tally = {
562
+ rangeBytes: 0,
563
+ rounds: { batches: 0, total: 0, max: 0 },
564
+ escapeRounds: 0,
565
+ rangeFallbacks: { snapshot: 0, serial: 0 },
566
+ footprintHits: 0
567
+ };
568
+ const runReplies = { runs: 0, addresses: 0 };
291
569
  const finish = (report) => ({
292
570
  ...report,
293
571
  backend: 'managed-coherent',
294
572
  memoryMode: 'copied',
295
573
  transportBytes: bytes,
296
- transportFallbacks
574
+ transportFallbacks,
575
+ ...(this.#ranges ? tally : {}),
576
+ ...(this.#runs ? { runReplies } : {}),
577
+ ...(this.#memo ? memoTally(this.#memo.stats, memoBefore) : {})
297
578
  });
298
579
  const controlled = this.#controlled.get(name);
299
580
  if (serial ||
@@ -313,6 +594,7 @@ export class ManagedFolio {
313
594
  });
314
595
  }
315
596
  const epoch = ++this.#epoch;
597
+ let snapshotGeneration = -1, snapshot;
316
598
  const scheduler = new Coordinator({
317
599
  memory: this.memory,
318
600
  workerMemory: this.memory,
@@ -329,29 +611,136 @@ export class ManagedFolio {
329
611
  this.#serial.value = previous;
330
612
  }
331
613
  },
332
- dispatch: async (lane, calls) => {
333
- try {
334
- if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
335
- throw new RangeError('snapshot exceeds limit');
336
- const identity = { session: this.#session, epoch, sequence: ++this.#sequence };
337
- const frame = encodeFrame({ ...identity, calls, fuel: this.#fuel, maxBytes: this.#maxBytes }, new Uint8Array(this.memory.buffer), this.#maximumFrameBytes);
338
- snapshotBytes += this.memory.buffer.byteLength;
614
+ dispatch: (lane, calls, generation) => this.#memoized(lane, calls, generation, async (lane, calls, generation) => {
615
+ const exhausted = () => calls.map(() => ({ reads: [], writes: [], exhausted: true }));
616
+ const identify = () => ({
617
+ session: this.#session,
618
+ epoch,
619
+ sequence: ++this.#sequence
620
+ });
621
+ const exchange = async (frame, identity) => {
339
622
  bytes.sent += frame.length;
340
623
  const response = await this.#lanes[lane].execute(frame);
341
624
  bytes.received += response.length;
342
- return decodeResults(response, identity, {
625
+ const decoded = decodeResults(response, identity, {
343
626
  maximumFrameBytes: this.#maximumFrameBytes,
344
627
  memoryBytes: this.memory.buffer.byteLength,
345
628
  maxBytes: this.#maxBytes,
346
- calls: calls.length
629
+ calls: calls.length,
630
+ runs: this.#runs
347
631
  });
632
+ if (this.#runs)
633
+ runReplies[decoded[0]?.readRuns ? 'runs' : 'addresses']++;
634
+ return decoded;
635
+ };
636
+ const snapshotFrame = (identity) => {
637
+ if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
638
+ throw new RangeError(`snapshot of ${this.memory.buffer.byteLength} bytes exceeds the limit of ${this.#maximumSnapshotBytes} bytes`);
639
+ if (snapshotGeneration !== generation) {
640
+ const memory = new Uint8Array(this.memory.buffer);
641
+ snapshot =
642
+ this.#snapshotEncoding === 'dense'
643
+ ? { payload: memory }
644
+ : encodeSnapshot(memory);
645
+ snapshotGeneration = generation;
646
+ }
647
+ const frame = encodeFrame({
648
+ ...identity,
649
+ calls,
650
+ fuel: this.#fuel,
651
+ maxBytes: this.#maxBytes,
652
+ ...(this.#runs ? { runs: runsVersion } : {}),
653
+ ...(snapshot.snapshot ? { snapshot: snapshot.snapshot } : {})
654
+ }, snapshot.payload, this.#maximumFrameBytes);
655
+ snapshotBytes += this.memory.buffer.byteLength;
656
+ return frame;
657
+ };
658
+ // a round with escapes only teaches the footprint; its results are never returned
659
+ const learn = async () => {
660
+ const ranges = this.#ranges;
661
+ const keys = calls.map((call) => FootprintCache.key(call.export, call.args));
662
+ let footprint = RangeSet.empty;
663
+ for (const key of keys) {
664
+ const known = ranges.cache.get(key);
665
+ if (!known)
666
+ continue;
667
+ tally.footprintHits++;
668
+ footprint = footprint.union(known);
669
+ }
670
+ tally.rounds.batches++;
671
+ let rounds = 0;
672
+ try {
673
+ while (rounds < ranges.maxRounds) {
674
+ const identity = identify();
675
+ const memory = new Uint8Array(this.memory.buffer);
676
+ let sent;
677
+ try {
678
+ sent = encodeRangesFrame({
679
+ ...identity,
680
+ calls,
681
+ fuel: this.#fuel,
682
+ maxBytes: this.#maxBytes,
683
+ ...(this.#runs ? { runs: runsVersion } : {})
684
+ }, memory, footprint, this.#maximumFrameBytes);
685
+ }
686
+ catch (error) {
687
+ if (!(error instanceof RangeError))
688
+ throw error;
689
+ this.diagnostics.push(`ranges frame not sent: ${error.message}`);
690
+ return undefined;
691
+ }
692
+ rounds++;
693
+ tally.rounds.total++;
694
+ tally.rangeBytes += sent.shipped.length;
695
+ const results = await exchange(sent.frame, identity);
696
+ // the lane's own escape list is not trusted; the read set decides
697
+ const lost = results.map((result) => resultEscapes(result, sent.shipped));
698
+ if (lost.every((set) => !set.count))
699
+ return results;
700
+ tally.escapeRounds++;
701
+ lost.forEach((set, index) => {
702
+ if (!set.count)
703
+ return;
704
+ const grown = set.round(rangePage, memory.length);
705
+ ranges.cache.learn(keys[index], grown);
706
+ footprint = footprint.union(grown);
707
+ });
708
+ }
709
+ return undefined;
710
+ }
711
+ finally {
712
+ tally.rounds.max = Math.max(tally.rounds.max, rounds);
713
+ }
714
+ };
715
+ try {
716
+ if (this.#ranges) {
717
+ const done = await learn();
718
+ if (done)
719
+ return done;
720
+ const identity = identify();
721
+ let frame;
722
+ try {
723
+ frame = snapshotFrame(identity);
724
+ }
725
+ catch (error) {
726
+ if (!(error instanceof RangeError))
727
+ throw error;
728
+ tally.rangeFallbacks.serial++;
729
+ this.diagnostics.push(`ranges exhausted; native fallback: ${error.message}`);
730
+ return exhausted();
731
+ }
732
+ tally.rangeFallbacks.snapshot++;
733
+ return await exchange(frame, identity);
734
+ }
735
+ const identity = identify();
736
+ return await exchange(snapshotFrame(identity), identity);
348
737
  }
349
738
  catch (error) {
350
739
  transportFallbacks++;
351
740
  this.diagnostics.push(`lane unavailable; native fallback: ${error instanceof Error ? error.message : String(error)}`);
352
- return calls.map(() => ({ reads: [], writes: [], exhausted: true }));
741
+ return exhausted();
353
742
  }
354
- }
743
+ })
355
744
  });
356
745
  this.#scheduler = scheduler;
357
746
  this.#serial.value = 0;
@@ -377,6 +766,38 @@ export class ManagedFolio {
377
766
  this.#scheduler = undefined;
378
767
  }
379
768
  }
769
+ /**
770
+ * Answers calls from the memo where it can, sends the rest to `execute`, and records their clean
771
+ * results. Lookups and records read canonical memory, which no commit changes until every lane
772
+ * of the batch has returned.
773
+ */
774
+ async #memoized(lane, calls, generation, execute) {
775
+ const memo = this.#memo;
776
+ if (!memo)
777
+ return execute(lane, calls, generation);
778
+ const memory = new Uint8Array(this.memory.buffer);
779
+ const keys = calls.map((call) => RegionMemo.keyOf(this.#memoModule, call.export, call.args));
780
+ const hits = await Promise.all(keys.map((key) => key === undefined ? undefined : memo.lookup(key, memory, { runs: this.#runs })));
781
+ const missing = calls.filter((_, index) => !hits[index]);
782
+ const started = performance.now();
783
+ const fresh = missing.length ? await execute(lane, missing, generation) : [];
784
+ const ms = missing.length ? (performance.now() - started) / missing.length : 0;
785
+ const results = [];
786
+ let next = 0;
787
+ for (let index = 0; index < calls.length; index++) {
788
+ const hit = hits[index];
789
+ if (hit) {
790
+ results.push(hit.result);
791
+ continue;
792
+ }
793
+ const result = fresh[next++];
794
+ results.push(result);
795
+ const key = keys[index];
796
+ if (key !== undefined)
797
+ await memo.record(key, memory, result, ms);
798
+ }
799
+ return results;
800
+ }
380
801
  /** Waits for the active run, then closes every lane. A failed disposer does not skip the rest. */
381
802
  close() {
382
803
  if (this.#closing)