@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/managed.js CHANGED
@@ -1,8 +1,40 @@
1
1
  import { Coordinator } from "./coordinator.js";
2
- import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, snapshotLength, 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
+ };
4
19
  // workers rpc rejects serialized arguments over 32 MiB; the margin covers the other arguments and serializer tags
5
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
+ }
6
38
  function integer(value, minimum, maximum, label) {
7
39
  if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
8
40
  throw new RangeError(`invalid ${label}`);
@@ -18,11 +50,26 @@ export class FolioLane {
18
50
  #maximum;
19
51
  #maximumFrameBytes;
20
52
  #maximumMemoryBytes;
53
+ #inline;
21
54
  #memory;
22
55
  #instance;
56
+ #marks;
23
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';
24
64
  constructor(module, options) {
25
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);
26
73
  this.#initial = integer(options.initial, 0, 65536, 'initial memory');
27
74
  this.#maximum = integer(options.maximum, this.#initial, 65536, 'maximum memory');
28
75
  this.#maximumMemoryBytes = options.maximumMemoryBytes ?? 32 * 1048576;
@@ -45,23 +92,42 @@ export class FolioLane {
45
92
  call.args.some((value) => typeof value !== 'number' && typeof value !== 'bigint'))
46
93
  throw new TypeError('invalid lane call');
47
94
  }
48
- const memoryBytes = snapshotLength(header.snapshot, payload);
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);
49
102
  const pages = memoryBytes / 65536;
50
103
  if (!Number.isInteger(pages) ||
51
104
  pages < this.#initial ||
52
105
  pages > this.#maximum ||
53
106
  memoryBytes > this.#maximumMemoryBytes)
54
107
  throw new RangeError('invalid lane snapshot');
55
- if (!this.#memory || !this.#instance || this.#memory.buffer.byteLength !== memoryBytes) {
56
- const binding = WebAssembly.Module.imports(this.#module).filter((item) => item.kind === 'memory');
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');
57
111
  if (binding.length !== 1)
58
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;
59
125
  this.#memory = new WebAssembly.Memory({
60
- initial: pages,
61
- maximum: this.#maximum,
126
+ initial: total,
127
+ maximum: Math.max(this.#maximum, total),
62
128
  shared: true
63
129
  });
64
- this.#instance = new WebAssembly.Instance(this.#module, {
130
+ this.#instance = new WebAssembly.Instance(module, {
65
131
  [binding[0].module]: { [binding[0].name]: this.#memory },
66
132
  folio: {
67
133
  load: (...args) => this.#active.load(...args),
@@ -75,8 +141,35 @@ export class FolioLane {
75
141
  }
76
142
  }
77
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);
78
172
  }
79
- restoreSnapshot(new Uint8Array(this.#memory.buffer), payload, header.snapshot);
80
173
  let remaining = header.maxBytes;
81
174
  const results = [];
82
175
  for (const call of header.calls) {
@@ -84,6 +177,12 @@ export class FolioLane {
84
177
  results.push({ reads: [], writes: [], exhausted: true });
85
178
  continue;
86
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
+ }
87
186
  this.#active = transaction(this.#memory, remaining);
88
187
  let error, value;
89
188
  try {
@@ -97,19 +196,165 @@ export class FolioLane {
97
196
  error = caught;
98
197
  }
99
198
  if (error instanceof RangeError) {
100
- 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));
101
202
  continue;
102
203
  }
103
204
  const result = this.#active.result(value, error);
104
205
  remaining -= result.reads.length + result.writes.length;
105
- results.push(result);
206
+ results.push(this.#annotate(result, ranged));
106
207
  }
107
208
  this.#active = undefined;
108
- 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
+ };
109
352
  }
110
353
  /** Drops the instance and its memory; a later frame builds them again. */
111
354
  close() {
112
- 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;
113
358
  }
114
359
  }
115
360
  /**
@@ -133,6 +378,10 @@ export class ManagedFolio {
133
378
  #fuel;
134
379
  #maxBytes;
135
380
  #snapshotEncoding;
381
+ #ranges;
382
+ #memo;
383
+ #memoModule = '';
384
+ #runs;
136
385
  #session = crypto.randomUUID();
137
386
  #memory;
138
387
  #scheduler;
@@ -143,10 +392,22 @@ export class ManagedFolio {
143
392
  #pending;
144
393
  #closing;
145
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
+ }
146
402
  this.#artifact = artifact;
147
403
  this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
148
404
  if (!['auto', 'dense'].includes(this.#snapshotEncoding))
149
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
+ };
150
411
  this.#lanes = options.lanes;
151
412
  integer(this.#lanes.length, 1, 64, 'lane count');
152
413
  this.#maximumSnapshotBytes = integer(options.maximumSnapshotBytes ?? 31 * 1048576, 65536, 0x100000000, 'snapshot limit');
@@ -294,14 +555,26 @@ export class ManagedFolio {
294
555
  }
295
556
  async #execute(name, entry, args, width, serial) {
296
557
  const bytes = { sent: 0, received: 0 };
558
+ const memoBefore = this.#memo?.stats;
297
559
  let snapshotBytes = 0;
298
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 };
299
569
  const finish = (report) => ({
300
570
  ...report,
301
571
  backend: 'managed-coherent',
302
572
  memoryMode: 'copied',
303
573
  transportBytes: bytes,
304
- transportFallbacks
574
+ transportFallbacks,
575
+ ...(this.#ranges ? tally : {}),
576
+ ...(this.#runs ? { runReplies } : {}),
577
+ ...(this.#memo ? memoTally(this.#memo.stats, memoBefore) : {})
305
578
  });
306
579
  const controlled = this.#controlled.get(name);
307
580
  if (serial ||
@@ -338,11 +611,31 @@ export class ManagedFolio {
338
611
  this.#serial.value = previous;
339
612
  }
340
613
  },
341
- dispatch: async (lane, calls, generation) => {
342
- try {
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) => {
622
+ bytes.sent += frame.length;
623
+ const response = await this.#lanes[lane].execute(frame);
624
+ bytes.received += response.length;
625
+ const decoded = decodeResults(response, identity, {
626
+ maximumFrameBytes: this.#maximumFrameBytes,
627
+ memoryBytes: this.memory.buffer.byteLength,
628
+ maxBytes: this.#maxBytes,
629
+ calls: calls.length,
630
+ runs: this.#runs
631
+ });
632
+ if (this.#runs)
633
+ runReplies[decoded[0]?.readRuns ? 'runs' : 'addresses']++;
634
+ return decoded;
635
+ };
636
+ const snapshotFrame = (identity) => {
343
637
  if (this.memory.buffer.byteLength > this.#maximumSnapshotBytes)
344
638
  throw new RangeError(`snapshot of ${this.memory.buffer.byteLength} bytes exceeds the limit of ${this.#maximumSnapshotBytes} bytes`);
345
- const identity = { session: this.#session, epoch, sequence: ++this.#sequence };
346
639
  if (snapshotGeneration !== generation) {
347
640
  const memory = new Uint8Array(this.memory.buffer);
348
641
  snapshot =
@@ -356,25 +649,98 @@ export class ManagedFolio {
356
649
  calls,
357
650
  fuel: this.#fuel,
358
651
  maxBytes: this.#maxBytes,
652
+ ...(this.#runs ? { runs: runsVersion } : {}),
359
653
  ...(snapshot.snapshot ? { snapshot: snapshot.snapshot } : {})
360
654
  }, snapshot.payload, this.#maximumFrameBytes);
361
655
  snapshotBytes += this.memory.buffer.byteLength;
362
- bytes.sent += frame.length;
363
- const response = await this.#lanes[lane].execute(frame);
364
- bytes.received += response.length;
365
- return decodeResults(response, identity, {
366
- maximumFrameBytes: this.#maximumFrameBytes,
367
- memoryBytes: this.memory.buffer.byteLength,
368
- maxBytes: this.#maxBytes,
369
- calls: calls.length
370
- });
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);
371
737
  }
372
738
  catch (error) {
373
739
  transportFallbacks++;
374
740
  this.diagnostics.push(`lane unavailable; native fallback: ${error instanceof Error ? error.message : String(error)}`);
375
- return calls.map(() => ({ reads: [], writes: [], exhausted: true }));
741
+ return exhausted();
376
742
  }
377
- }
743
+ })
378
744
  });
379
745
  this.#scheduler = scheduler;
380
746
  this.#serial.value = 0;
@@ -400,6 +766,38 @@ export class ManagedFolio {
400
766
  this.#scheduler = undefined;
401
767
  }
402
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
+ }
403
801
  /** Waits for the active run, then closes every lane. A failed disposer does not skip the rest. */
404
802
  close() {
405
803
  if (this.#closing)
package/dist/memo.d.ts ADDED
@@ -0,0 +1,99 @@
1
+ import type { TransactionResult } from './transaction.ts';
2
+ /**
3
+ * Recorded region results, reused when the bytes a region read have not changed.
4
+ *
5
+ * A tracked region's result is a function of its module, its export, its integer arguments, the
6
+ * memory size and the bytes it read from memory before writing them. After an exact tracked
7
+ * execution the memo keeps the read ranges, a SHA-256 of their bytes as they were read, the read
8
+ * addresses, the write set, the return value and the time the execution took. A lookup hashes the
9
+ * current bytes of each recorded entry's ranges and returns the recorded result on equality.
10
+ * Equal module, arguments and bytes give the same execution, so the same writes and value.
11
+ *
12
+ * Host contract, for a host that tracks its own regions:
13
+ *
14
+ * - The module string passed to `keyOf` must identify the module bytes and their instrumentation.
15
+ * Two calls with the same module string are assumed to execute identically. `ManagedFolio`
16
+ * assigns a process-local identity per artifact; a host that shares a memo across processes or
17
+ * restarts must use a content hash of the tracked module instead.
18
+ * - The host supplies the region export, its arguments, the memory at the start of the call and
19
+ * the call's tracked read and write sets. `record` takes the memory before any write of the
20
+ * call, because it hashes the read bytes itself. The read set holds only the bytes the region
21
+ * read before it wrote them, which is what the execution depends on.
22
+ * - The region must be deterministic in its read bytes, arguments and module. It may not read a
23
+ * clock, randomness, a host import or any mutable global. The compiler refuses global access in
24
+ * a region span (`summarizeSpan` in `src/extract.ts`); the lane resets its fuel counter before
25
+ * every call (`FolioLane.execute` in `src/managed.ts`), so the counter carries no state between
26
+ * calls.
27
+ * - A trap, fuel or budget exhaustion, an inconclusive result or a read the shipped ranges missed
28
+ * is refused by `record`.
29
+ *
30
+ * `RegionMemo.probe` measures repetition without recording writes, so a host can see the reuse
31
+ * rate on its own traffic before it enables a memo. The probe is an upper bound on hit rate: it
32
+ * keeps no entry limit and no byte budget.
33
+ */
34
+ export interface MemoStats {
35
+ lookups: number;
36
+ hits: number;
37
+ misses: number;
38
+ /** Bytes hashed by lookups, summed over each candidate entry. */
39
+ hashedBytes: number;
40
+ /** Estimated cost of every entry recorded; see `RegionMemo` for the estimate. */
41
+ recordedBytes: number;
42
+ /** Estimated cost of the entries currently held. */
43
+ storedBytes: number;
44
+ recorded: number;
45
+ evictions: number;
46
+ /** Recorded execution time of every hit, summed. An estimate of lane time avoided. */
47
+ savedMs: number;
48
+ }
49
+ export interface MemoOptions {
50
+ /** Budget for stored entries, estimated in bytes. Default 8 MiB. */
51
+ bytes?: number;
52
+ /** Entries kept per key. Default 4. */
53
+ entries?: number;
54
+ }
55
+ export interface MemoProbe {
56
+ observations: number;
57
+ distinct: number;
58
+ repeats: number;
59
+ /** Repeats divided by observations; an upper bound on the hit rate of a memo with no limits. */
60
+ repeatRate: number;
61
+ }
62
+ export interface MemoHit {
63
+ result: TransactionResult;
64
+ ms: number;
65
+ }
66
+ export declare class RegionMemo {
67
+ #private;
68
+ constructor(options?: MemoOptions);
69
+ /**
70
+ * The key for a call in a module, or undefined when an argument is not an exact integer. The
71
+ * module string is the host's identity for the tracked module; see the contract above.
72
+ */
73
+ static keyOf(module: string, name: string, args: readonly unknown[]): string | undefined;
74
+ get stats(): MemoStats;
75
+ /**
76
+ * Returns the recorded result whose read bytes equal the current bytes, or undefined. With
77
+ * `runs`, the write set comes as `writeRuns` and `writeData`, which the owner commits as
78
+ * intervals; otherwise as `[address, value]` tuples.
79
+ */
80
+ lookup(key: string, memory: Uint8Array, options?: {
81
+ runs?: boolean;
82
+ }): Promise<MemoHit | undefined>;
83
+ /**
84
+ * Records a clean result of an execution that started from `memory`. Returns false when the
85
+ * result is refused or already held. Throws on a read or write that the memory cannot hold.
86
+ *
87
+ * The cost estimate counts 8 bytes per read address and 40 per write (a two-element array and
88
+ * its slot), plus the hashed span table and the 32-byte digest.
89
+ */
90
+ record(key: string, memory: Uint8Array, result: TransactionResult, ms?: number): Promise<boolean>;
91
+ /** Drops every entry and resets the counters. */
92
+ clear(): void;
93
+ /** Counts how often (key, read bytes) pairs repeat. Nothing is recorded. */
94
+ static probe(observations: Iterable<{
95
+ key: string;
96
+ memory: Uint8Array;
97
+ reads: readonly number[];
98
+ }>): Promise<MemoProbe>;
99
+ }