@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/inline.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import binaryen from 'binaryen';
2
2
  import { stackRoute } from "./extract.js";
3
+ import { importedMemory, shareMemory } from "./iteration-owner.js";
3
4
  const info = (expression) => {
4
5
  const id = binaryen.getExpressionId(expression);
5
6
  if (id === binaryen.UnreachableId || id === binaryen.NopId) {
@@ -19,11 +20,32 @@ export const inlineGlobals = {
19
20
  stackPointer: '__folio_sp',
20
21
  frameLow: '__folio_fl',
21
22
  frameSize: '__folio_fn',
22
- frameShadow: '__folio_fs'
23
+ frameShadow: '__folio_fs',
24
+ exemptLow: '__folio_xl',
25
+ exemptEnd: '__folio_xe',
26
+ slotLow: '__folio_sl',
27
+ slotEnd: '__folio_se',
28
+ arenaLow: '__folio_al',
29
+ arenaEnd: '__folio_ae',
30
+ violation: '__folio_xv',
31
+ windowLow: '__folio_wl',
32
+ windowEnd: '__folio_we',
33
+ windowDelta: '__folio_wd',
34
+ readWindow0Low: '__folio_r0l',
35
+ readWindow0Span: '__folio_r0m',
36
+ readWindow1Low: '__folio_r1l',
37
+ readWindow1Span: '__folio_r1m',
38
+ readSummary: '__folio_rs',
39
+ readHits: '__folio_ch',
40
+ readMisses: '__folio_cm',
41
+ readExempt: '__folio_ce'
23
42
  };
24
43
  /** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
25
44
  export const inlineEntryBytes = (writeGranule = 32) => 8 + writeGranule;
26
45
  const inlineHelpers = [
46
+ '__folio_x_trap',
47
+ '__folio_x_r_range',
48
+ '__folio_x_w_range',
27
49
  '__folio_r_mark',
28
50
  '__folio_w_mark',
29
51
  '__folio_w_set',
@@ -33,7 +55,8 @@ const inlineHelpers = [
33
55
  '__folio_f_r',
34
56
  '__folio_f_w',
35
57
  '__folio_f_rr',
36
- '__folio_f_rw'
58
+ '__folio_f_rw',
59
+ '__folio_w_rebase'
37
60
  ];
38
61
  const inlineLeaves = new Set([
39
62
  binaryen.ConstId,
@@ -195,6 +218,49 @@ function memoryCount(bytes, native) {
195
218
  * zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
196
219
  * the region is not tracked.
197
220
  *
221
+ * With `slot: true` and a stack global, the owner also sets three address windows before a region:
222
+ * the exempt window `[__folio_xl, __folio_xe)`, the whole private slot `[__folio_sl, __folio_se)`
223
+ * and the arena of all slots `[__folio_al, __folio_ae)`. An access inside the exempt window sets no
224
+ * mark and logs no undo entry. An access that overlaps the arena but does not lie inside the own
225
+ * slot stores its address in `__folio_xv` and traps with `unreachable`, because another iteration
226
+ * owns those bytes. Every other access is tracked as before, so the exempt window must not contain
227
+ * the tracked frame; an access that crosses the window edge is tracked. `memory.copy`,
228
+ * `memory.fill` and `memory.init` apply the same tests to the whole range, and a range counts as
229
+ * inside only when every byte is. The exempt bytes are not restored by a rollback, so the owner
230
+ * must treat the window as dead after the region.
231
+ *
232
+ * With `readWindows: n` the owner also sets, per window `i` below `n`, `__folio_r<i>l` (first byte)
233
+ * and `__folio_r<i>m` (window size minus 7, or 0 for no window) before a region, and marks every
234
+ * read granule that the window touches in the read bitmap itself. A plain, non-atomic load or SIMD
235
+ * load of at most 8 bytes whose address `a` satisfies `a - low < size - 7` lies wholly inside the
236
+ * window, so its read mark is already set: it sets no mark and skips the slot, arena and frame
237
+ * checks. Every other access, a store, an atomic, a wider load, a load that crosses a window edge
238
+ * and every bulk operation, is tracked as before. The window must lie outside the arena of all
239
+ * slots and the owner frame region, which is what those checks would have found; a false conflict
240
+ * is possible only for a granule of the window that another iteration writes and this one does
241
+ * not read. The exempt window is tested first, so an exempt load executes what it does without
242
+ * windows; the guards of the windows run only for a load outside it. With `readCount` the lowering
243
+ * also counts those loads by where they land (`__folio_ch`, `__folio_cm`, `__folio_ce`).
244
+ *
245
+ * With `readSummary: n` every read mark also sets one byte of the summary at `__folio_rs`, before
246
+ * the bit it summarizes. The byte is `(a >> (log2(readGranule) + 11)) & (n - 1)` for address `a`,
247
+ * one byte per 64 words of the read bitmap. A bitmap word is never non-zero while its summary byte
248
+ * is zero, so a scan may skip the blocks whose byte is zero. The owner sets the bytes of any
249
+ * granule it marks itself, a read window for one, and clears a byte only when it clears the words
250
+ * of its block. An address past the memory wraps to a byte that covers other words, which only
251
+ * adds blocks to scan. The owner must also set `n` large enough that every address of the memory
252
+ * has its own byte, or the scan visits blocks it need not.
253
+ *
254
+ * With `window: true` (which implies `frame`, and `slot` when there is a stack global) the owner also sets `__folio_wl` and
255
+ * `__folio_we`, a window of the address space, and `__folio_wd`, the distance from it to a private
256
+ * copy that lies inside the tracked frame region. A load, store, atomic or SIMD access that lies in
257
+ * the window runs on the copy (`address + __folio_wd`), a bulk operation does the same when its
258
+ * whole range is inside, and an access or range that crosses the window edge traps with
259
+ * `unreachable`. Accesses in the tracked frame region, the copy included, set no bitmap mark and
260
+ * log no undo entry: their only record is the frame shadow, whose exposed bits the owner
261
+ * validates, and the copy is discarded or committed byte by byte from the written bits. With the
262
+ * window empty (`__folio_we` at 0) nothing is rebased.
263
+ *
198
264
  * Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
199
265
  * `requireShared` is set, a start function that calls, a reserved name or an expression it does
200
266
  * not know. An imported host function that touches memory is not seen.
@@ -203,6 +269,12 @@ export function lowerInline(bytes, options = {}) {
203
269
  const rg = granuleShift(options.readGranule, 64, 16, 4096);
204
270
  const wg = granuleShift(options.writeGranule, 32, 16, 256);
205
271
  const entry = inlineEntryBytes(1 << wg);
272
+ const readWindows = options.readWindows ?? 0;
273
+ if (!Number.isInteger(readWindows) || readWindows < 0 || readWindows > 2)
274
+ throw new RangeError('read windows must be 0, 1 or 2');
275
+ const summary = options.readSummary ?? 0;
276
+ if (!Number.isInteger(summary) || summary < 0 || summary > 32768 || summary & (summary - 1))
277
+ throw new RangeError('read summary must be 0 or a power of two up to 32768');
206
278
  const original = Uint8Array.from(bytes);
207
279
  const native = new WebAssembly.Module(original);
208
280
  if (memoryCount(original, native) !== 1)
@@ -218,7 +290,12 @@ export function lowerInline(bytes, options = {}) {
218
290
  throw new Error('memory64 is not supported');
219
291
  if ((options.requireShared ?? true) && !memory.shared)
220
292
  throw new Error('shared memory required; pass requireShared: false for one thread');
221
- const reserved = [...Object.values(inlineGlobals), ...inlineHelpers];
293
+ const fuel = Boolean(options.fuel);
294
+ const reserved = [
295
+ ...Object.values(inlineGlobals),
296
+ ...inlineHelpers,
297
+ ...(fuel ? ['__folio_fuel', '__folio_exhausted', '__folio_set_fuel'] : [])
298
+ ];
222
299
  if (reserved.some((name) => m.getGlobal(name) || m.getFunction(name) || m.getExport(name)))
223
300
  throw new Error('reserved function name');
224
301
  if (stack !== undefined) {
@@ -227,7 +304,17 @@ export function lowerInline(bytes, options = {}) {
227
304
  if (!shape || !shape.mutable || shape.type !== binaryen.i32 || shape.module)
228
305
  throw new Error(`stack global ${stack} is not a defined mutable i32`);
229
306
  }
230
- const frame = Boolean(options.frame);
307
+ const window = Boolean(options.window);
308
+ const frame = Boolean(options.frame) || window;
309
+ const slot = ((Boolean(options.slot) || window) && stack !== undefined) || Boolean(options.guard);
310
+ const { exemptLow: xl, exemptEnd: xe, slotLow: sl, slotEnd: se } = inlineGlobals;
311
+ const { arenaLow: al, arenaEnd: ae, violation: xv } = inlineGlobals;
312
+ const { windowLow: wl, windowEnd: we, windowDelta: wd } = inlineGlobals;
313
+ const { readWindow0Low: r0l, readWindow0Span: r0m } = inlineGlobals;
314
+ const { readWindow1Low: r1l, readWindow1Span: r1m } = inlineGlobals;
315
+ const rs = inlineGlobals.readSummary;
316
+ const { readHits: ch, readMisses: cm, readExempt: ce } = inlineGlobals;
317
+ const counting = Boolean(options.readCount) && readWindows > 0;
231
318
  const rb = inlineGlobals.readBitmap, wb = inlineGlobals.writeBitmap, lp = inlineGlobals.logPointer, ll = inlineGlobals.logLimit, sa = inlineGlobals.stampAddress, fl = inlineGlobals.frameLow, fn = inlineGlobals.frameSize, fs = inlineGlobals.frameShadow;
232
319
  const i32 = binaryen.i32, none = binaryen.none;
233
320
  const c = (value) => m.i32.const(value | 0);
@@ -237,13 +324,32 @@ export function lowerInline(bytes, options = {}) {
237
324
  const bitOf = (address, shift) => m.i32.shl(c(1), m.i32.and(m.i32.shr_u(address(), c(shift)), c(7)));
238
325
  const byteOf = (base, address, shift) => m.i32.add(g(base), m.i32.shr_u(address(), c(shift + 3)));
239
326
  const setBit = (base, address, shift) => m.i32.store8(0, 1, byteOf(base, address, shift), m.i32.or(m.i32.load8_u(0, 1, byteOf(base, address, shift)), bitOf(address, shift)));
327
+ // the summary byte goes first, so the bit is never set without it
328
+ const markRead = (address) => summary
329
+ ? m.block(null, [
330
+ m.i32.store8(0, 1, m.i32.add(g(rs), m.i32.and(m.i32.shr_u(address(), c(rg + 11)), c(summary - 1))), c(1)),
331
+ setBit(rb, address, rg)
332
+ ], none)
333
+ : setBit(rb, address, rg);
240
334
  const unmarked = (address) => m.i32.eqz(m.i32.and(m.i32.load8_u(0, 1, byteOf(wb, address, wg)), bitOf(address, wg)));
241
335
  // does an access of `width` bytes at the address overlap the frame region
242
336
  const inFrame = (address, width) => width === 1
243
337
  ? m.i32.lt_u(m.i32.sub(address(), g(fl)), g(fn))
244
338
  : m.i32.lt_u(m.i32.add(m.i32.sub(address(), g(fl)), c(width - 1)), m.i32.add(g(fn), c(width - 1)));
245
339
  const frameCall = (name, address, width) => m.if(inFrame(address, width), call(name, address(), c(width)));
340
+ // does [address, address + width) lie inside the window named by two globals
341
+ const within = (low, end, address, width) => m.i32.and(m.i32.ge_u(address(), g(low)), m.i32.le_u(m.i32.add(address(), width), g(end)));
342
+ // does [address, address + width) overlap the arena of all slots
343
+ const overlapsArena = (address, width) => m.i32.and(m.i32.lt_u(address(), g(ae)), m.i32.gt_u(m.i32.add(address(), width), g(al)));
344
+ // does [address, address + width) lie inside the tracked frame region
345
+ const inRegion = (address, width) => m.i32.and(m.i32.ge_u(address(), g(fl)), m.i32.le_u(m.i32.add(address(), typeof width === 'number' ? c(width) : width()), m.i32.add(g(fl), g(fn))));
246
346
  const hold = (local, value) => m.block(null, [m.local.set(local, value), l(local)], i32);
347
+ const tick = () => m.block(null, [
348
+ m.global.set('__folio_fuel', m.i32.sub(g('__folio_fuel'), c(1))),
349
+ m.if(m.i32.le_s(g('__folio_fuel'), c(0)), m.call('__folio_exhausted', [], none))
350
+ ], none);
351
+ const stop = Boolean(options.stop);
352
+ const poll = () => m.if(m.i32.atomic.load(4, g(sa)), m.unreachable());
247
353
  const startRef = m.getStart();
248
354
  const start = startRef ? binaryen.getFunctionInfo(startRef).name : undefined;
249
355
  const callsOut = (expression) => {
@@ -288,19 +394,60 @@ export function lowerInline(bytes, options = {}) {
288
394
  m.local.set(t, ptr),
289
395
  m.local.set(u, offset ? m.i32.add(l(t), c(offset)) : l(t))
290
396
  ];
397
+ const tracked = [];
291
398
  const crosses = (shift, mark) => m.if(m.i32.gt_u(m.i32.and(l(u), c((1 << shift) - 1)), c((1 << shift) - width)), call(mark, m.i32.add(l(u), c(width - 1))));
292
399
  if (read) {
293
- steps.push(setBit(rb, () => l(u), rg));
400
+ tracked.push(markRead(() => l(u)));
294
401
  if (width > 1)
295
- steps.push(crosses(rg, '__folio_r_mark'));
402
+ tracked.push(crosses(rg, '__folio_r_mark'));
296
403
  }
297
404
  if (write) {
298
- steps.push(m.if(unmarked(() => l(u)), call('__folio_w_set', l(u))));
405
+ tracked.push(m.if(unmarked(() => l(u)), call('__folio_w_set', l(u))));
299
406
  if (width > 1)
300
- steps.push(crosses(wg, '__folio_w_mark'));
407
+ tracked.push(crosses(wg, '__folio_w_mark'));
301
408
  }
409
+ const marks = tracked.splice(0);
410
+ if (window)
411
+ tracked.push(m.if(m.i32.eqz(inRegion(() => l(u), width)), m.block(null, marks, none)));
412
+ else
413
+ tracked.push(...marks);
302
414
  if (frame && checks)
303
- steps.push(frameCall('__folio_f_r', () => l(u), width));
415
+ tracked.push(frameCall('__folio_f_r', () => l(u), width));
416
+ if (window)
417
+ steps.push(m.if(m.i32.and(m.i32.lt_u(l(u), g(we)), m.i32.gt_u(m.i32.add(l(u), c(width)), g(wl))), m.if(within(wl, we, () => l(u), c(width)), m.block(null, [
418
+ m.local.set(t, m.i32.add(l(t), g(wd))),
419
+ m.local.set(u, m.i32.add(l(u), g(wd)))
420
+ ], none), m.unreachable())));
421
+ const windowed = readWindows > 0 && read && !write && width <= 8;
422
+ const bump = (name) => m.global.set(name, m.i32.add(g(name), c(1)));
423
+ // a load that misses every window is tracked, and counted as a miss when counting
424
+ const miss = (inner) => m.block(null, counting ? [bump(cm), ...inner] : inner, none);
425
+ // a hit inside a window the owner marked in full skips every other step
426
+ const chained = (tail) => {
427
+ let chain = tail;
428
+ for (let w = readWindows - 1; w >= 0; w--) {
429
+ const [low, span] = w === 0 ? [r0l, r0m] : [r1l, r1m];
430
+ chain = m.if(m.i32.lt_u(m.i32.sub(l(u), g(low)), g(span)), counting ? bump(ch) : m.nop(), chain);
431
+ }
432
+ return chain;
433
+ };
434
+ if (slot) {
435
+ const inner = [
436
+ m.if(overlapsArena(() => l(u), c(width)), m.if(m.i32.eqz(within(sl, se, () => l(u), c(width))), call('__folio_x_trap', l(u)))),
437
+ ...tracked
438
+ ];
439
+ const exempt = (tail) => m.if(within(xl, xe, () => l(u), c(width)), windowed && counting ? bump(ce) : m.nop(), tail);
440
+ // the exempt window first, or the windows first: a hit then skips the exempt check
441
+ // and an exempt load pays the guards
442
+ if (!windowed)
443
+ steps.push(exempt(m.block(null, inner, none)));
444
+ else if (options.exemptFirst)
445
+ steps.push(exempt(chained(miss(inner))));
446
+ else
447
+ steps.push(chained(exempt(miss(inner))));
448
+ }
449
+ else
450
+ steps.push(...(windowed ? [chained(miss(tracked))] : tracked));
304
451
  if (saved !== undefined)
305
452
  steps.push(m.local.set(saved, l(u)));
306
453
  steps.push(l(t));
@@ -310,7 +457,43 @@ export function lowerInline(bytes, options = {}) {
310
457
  const v = info(e);
311
458
  for (const child of inlineChildren(v))
312
459
  visit(child);
460
+ if (window &&
461
+ (v.id === binaryen.MemoryCopyId ||
462
+ v.id === binaryen.MemoryFillId ||
463
+ v.id === binaryen.MemoryInitId)) {
464
+ // the destination operand evaluates all three, rebases the ranges and marks them;
465
+ // the other operands then read the locals back
466
+ const [td, tm, tn] = vars(3);
467
+ const copy = v.id === binaryen.MemoryCopyId;
468
+ const kind = copy ? 'Copy' : v.id === binaryen.MemoryFillId ? 'Fill' : 'Init';
469
+ const middle = copy ? v.source : kind === 'Fill' ? v.value : v.offset;
470
+ const rebase = (local) => m.local.set(local, m.call('__folio_w_rebase', [l(local), l(tn)], i32));
471
+ const api = capi;
472
+ api[`_BinaryenMemory${kind}SetDest`](e, m.block(null, [
473
+ m.local.set(td, v.dest),
474
+ m.local.set(tm, middle),
475
+ m.local.set(tn, v.size),
476
+ rebase(td),
477
+ ...(copy
478
+ ? [
479
+ rebase(tm),
480
+ call('__folio_x_r_range', l(tm), l(tn)),
481
+ call('__folio_f_rr', l(tm), l(tn))
482
+ ]
483
+ : []),
484
+ call('__folio_x_w_range', l(td), l(tn)),
485
+ call('__folio_f_rw', l(td), l(tn)),
486
+ l(td)
487
+ ], i32));
488
+ api[`_BinaryenMemory${kind}Set${copy ? 'Source' : kind === 'Fill' ? 'Value' : 'Offset'}`](e, l(tm));
489
+ api[`_BinaryenMemory${kind}SetSize`](e, l(tn));
490
+ return;
491
+ }
313
492
  switch (v.id) {
493
+ case binaryen.LoopId:
494
+ if (fuel || stop)
495
+ capi._BinaryenLoopSetBody(e, m.block(null, [...(fuel ? [tick()] : []), ...(stop ? [poll()] : []), v.body], binaryen.getExpressionType(v.body)));
496
+ break;
314
497
  case binaryen.LoadId:
315
498
  capi._BinaryenLoadSetPtr(e, access(v.ptr, v.offset, v.bytes, true, Boolean(v.isAtomic), true));
316
499
  break;
@@ -358,8 +541,8 @@ export function lowerInline(bytes, options = {}) {
358
541
  capi._BinaryenMemoryCopySetSource(e, hold(ts, v.source));
359
542
  capi._BinaryenMemoryCopySetSize(e, m.block(null, [
360
543
  m.local.set(tn, v.size),
361
- call('__folio_r_range', l(ts), l(tn)),
362
- call('__folio_w_range', l(td), l(tn)),
544
+ call(slot ? '__folio_x_r_range' : '__folio_r_range', l(ts), l(tn)),
545
+ call(slot ? '__folio_x_w_range' : '__folio_w_range', l(td), l(tn)),
363
546
  ...(frame
364
547
  ? [
365
548
  call('__folio_f_rr', l(ts), l(tn)),
@@ -377,7 +560,7 @@ export function lowerInline(bytes, options = {}) {
377
560
  capi[fill ? '_BinaryenMemoryFillSetDest' : '_BinaryenMemoryInitSetDest'](e, hold(td, v.dest));
378
561
  capi[fill ? '_BinaryenMemoryFillSetSize' : '_BinaryenMemoryInitSetSize'](e, m.block(null, [
379
562
  m.local.set(tn, v.size),
380
- call('__folio_w_range', l(td), l(tn)),
563
+ call(slot ? '__folio_x_w_range' : '__folio_w_range', l(td), l(tn)),
381
564
  ...(frame ? [call('__folio_f_rw', l(td), l(tn))] : []),
382
565
  l(tn)
383
566
  ], i32));
@@ -386,6 +569,14 @@ export function lowerInline(bytes, options = {}) {
386
569
  }
387
570
  };
388
571
  visit(body);
572
+ if (fuel)
573
+ capi._BinaryenFunctionSetBody(f, m.block(null, [tick(), body], binaryen.getExpressionType(body)));
574
+ }
575
+ if (fuel) {
576
+ m.addGlobal('__folio_fuel', i32, true, c(0));
577
+ m.addFunctionImport('__folio_exhausted', 'folio', 'exhausted', none, none);
578
+ m.addFunction('__folio_set_fuel', i32, none, [], m.global.set('__folio_fuel', l(0)));
579
+ m.addFunctionExport('__folio_set_fuel', '__folio_set_fuel');
389
580
  }
390
581
  for (const name of [rb, wb, lp, ll, sa]) {
391
582
  m.addGlobal(name, i32, true, c(0));
@@ -396,6 +587,34 @@ export function lowerInline(bytes, options = {}) {
396
587
  m.addGlobal(name, i32, true, c(0));
397
588
  m.addGlobalExport(name, name);
398
589
  }
590
+ if (slot || window)
591
+ for (const name of [xl, xe, sl, se, al, ae, xv]) {
592
+ m.addGlobal(name, i32, true, c(0));
593
+ m.addGlobalExport(name, name);
594
+ }
595
+ if (window)
596
+ for (const name of [wl, we, wd]) {
597
+ m.addGlobal(name, i32, true, c(0));
598
+ m.addGlobalExport(name, name);
599
+ }
600
+ for (const [index, pair] of [
601
+ [r0l, r0m],
602
+ [r1l, r1m]
603
+ ].entries())
604
+ if (index < readWindows)
605
+ for (const name of pair) {
606
+ m.addGlobal(name, i32, true, c(0));
607
+ m.addGlobalExport(name, name);
608
+ }
609
+ if (summary) {
610
+ m.addGlobal(rs, i32, true, c(0));
611
+ m.addGlobalExport(rs, rs);
612
+ }
613
+ if (counting)
614
+ for (const name of [ch, cm, ce]) {
615
+ m.addGlobal(name, i32, true, c(0));
616
+ m.addGlobalExport(name, name);
617
+ }
399
618
  if (stack !== undefined)
400
619
  m.addGlobalExport(stack, inlineGlobals.stackPointer);
401
620
  const pair = binaryen.createType([i32, i32]);
@@ -467,7 +686,7 @@ export function lowerInline(bytes, options = {}) {
467
686
  bulk('__folio_f_rr', true);
468
687
  bulk('__folio_f_rw', false);
469
688
  };
470
- m.addFunction('__folio_r_mark', i32, none, [], setBit(rb, () => l(0), rg));
689
+ m.addFunction('__folio_r_mark', i32, none, [], markRead(() => l(0)));
471
690
  m.addFunction('__folio_undo', i32, none, [i32], m.block(null, [
472
691
  m.if(m.i32.gt_u(m.i32.add(g(lp), c(entry)), g(ll)), m.unreachable()),
473
692
  m.local.set(1, g(lp)),
@@ -492,6 +711,35 @@ export function lowerInline(bytes, options = {}) {
492
711
  range('__folio_w_range', wg, '__folio_w_mark');
493
712
  if (frame)
494
713
  addFrameHelpers();
714
+ if (slot || window) {
715
+ m.addFunction('__folio_x_trap', i32, none, [], m.block(null, [m.global.set(xv, l(0)), m.unreachable()], none));
716
+ // params a, n; the range is tracked unless it lies in the exempt window
717
+ const exempt = (name, tracked) => m.addFunction(name, pair, none, [i32], m.if(l(1), m.block(null, [
718
+ m.local.set(2, m.i32.add(l(0), l(1))),
719
+ m.if(m.i32.eqz(m.i32.and(m.i32.ge_u(l(0), g(xl)), m.i32.le_u(l(2), g(xe)))), m.block(null, [
720
+ m.if(m.i32.and(m.i32.lt_u(l(0), g(ae)), m.i32.gt_u(l(2), g(al))), m.if(m.i32.eqz(m.i32.and(m.i32.ge_u(l(0), g(sl)), m.i32.le_u(l(2), g(se)))), call('__folio_x_trap', l(0)))),
721
+ window
722
+ ? m.if(m.i32.eqz(inRegion(() => l(0), () => l(1))), call(tracked, l(0), l(1)))
723
+ : call(tracked, l(0), l(1))
724
+ ], none))
725
+ ], none)));
726
+ exempt('__folio_x_r_range', '__folio_r_range');
727
+ exempt('__folio_x_w_range', '__folio_w_range');
728
+ }
729
+ if (window) {
730
+ // params a, n, result the address a bulk range runs at: inside the window it moves to the
731
+ // copy, across its edge it traps
732
+ m.addFunction('__folio_w_rebase', pair, i32, [i32], m.block(null, [
733
+ m.if(m.i32.eqz(l(1)), m.return(l(0))),
734
+ m.local.set(2, m.i32.add(l(0), l(1))),
735
+ m.if(m.i32.lt_u(l(2), l(0)), m.return(l(0))),
736
+ m.if(m.i32.and(m.i32.lt_u(l(0), g(we)), m.i32.gt_u(l(2), g(wl))), m.block(null, [
737
+ m.if(m.i32.and(m.i32.ge_u(l(0), g(wl)), m.i32.le_u(l(2), g(we))), m.return(m.i32.add(l(0), g(wd)))),
738
+ m.unreachable()
739
+ ], none)),
740
+ l(0)
741
+ ], i32));
742
+ }
495
743
  if (!m.validate())
496
744
  throw new Error('invalid inline lowering');
497
745
  return m.emitBinary();
@@ -501,3 +749,18 @@ export function lowerInline(bytes, options = {}) {
501
749
  }
502
750
  }
503
751
  // #endregion
752
+ // #region lane module
753
+ /**
754
+ * The module a managed lane runs with inline tracking: `lowerInline` with fuel and the arena
755
+ * guard on, and the memory import widened to the largest maximum so a lane can place the marks
756
+ * and the undo log above the program memory. Build time only; the input is the control plan's
757
+ * `workerOriginal`.
758
+ */
759
+ export function inlineLane(workerOriginal) {
760
+ const lowered = lowerInline(workerOriginal, { fuel: true, guard: true });
761
+ const memories = importedMemory(lowered);
762
+ if (memories.length !== 1)
763
+ throw new Error('exactly one imported memory required');
764
+ return shareMemory(lowered, memories[0]);
765
+ }
766
+ // #endregion
@@ -1,5 +1,5 @@
1
1
  /** Why the rest of a loop ran serially after the pooled path was tried or refused. */
2
- export type IterationStop = 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'dependency';
2
+ export type IterationStop = 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'dependency' | 'stalled';
3
3
  /** What the admission decision saw and chose for one owner call's loop. */
4
4
  export interface IterationAdmission {
5
5
  /** Time of iteration 0 on the owner thread, on a plain instance and the real frame. */
@@ -12,8 +12,29 @@ export interface IterationAdmission {
12
12
  admitted: boolean;
13
13
  /** Wall of the last batch, dispatch to the end of its replays. */
14
14
  batchWallMs?: number;
15
- /** The same iterations at `plainIterationMs` each. */
15
+ /** The serial time of the iterations of that batch, from the online estimate. */
16
16
  batchSerialMs?: number;
17
+ /** The latest estimate of serial time per iteration, from iteration 0, replays or workers. */
18
+ estimateMs?: number;
19
+ /** Set when a refused loop was admitted after timed serial iterations; the iteration index. */
20
+ readmittedAt?: number;
21
+ /** Admitted as a probe: under the floor, over `probeFraction` of it, one timed batch decides. */
22
+ probe?: boolean;
23
+ /** The probe batch did not beat the serial time of its iterations, and the dispatch ended. */
24
+ probeLost?: boolean;
25
+ /** One entry per batch, only under `admissionSeam.trace`. */
26
+ trace?: AdmissionStep[];
27
+ }
28
+ /** What the estimate and the batch rule saw after one batch. @internal */
29
+ export interface AdmissionStep {
30
+ first: number;
31
+ count: number;
32
+ windows: boolean;
33
+ trackedMeanMs: number;
34
+ kappa?: number;
35
+ estimateMs: number;
36
+ wallMs: number;
37
+ serialMs: number;
17
38
  }
18
39
  /** The constants of the decision. A re-calibration changes these and nothing else. */
19
40
  export interface IterationAdmissionConstants {
@@ -37,18 +58,26 @@ export interface IterationAdmissionConstants {
37
58
  * does one batch whose wall passes `batchCollapse` times that serial time.
38
59
  */
39
60
  export declare const iterationAdmissionConstants: IterationAdmissionConstants;
61
+ /**
62
+ * With the second chance on, a loop whose remaining serial time is under the floor but over this
63
+ * fraction of it is admitted as a probe: its first timed batch has to beat the serial time of its
64
+ * iterations by the margin, or the dispatch ends there. The floor was fitted on a build with the
65
+ * full read scan and no read windows, so it is the least certain number in the decision.
66
+ */
67
+ export declare const probeFraction = 0.5;
40
68
  export interface AdmitInput {
41
69
  plainIterationMs: number;
42
70
  trip: number;
43
71
  width: number;
44
72
  constants?: IterationAdmissionConstants;
73
+ secondChance?: boolean;
45
74
  }
46
75
  /**
47
76
  * Decides before the first dispatch from the measured serial time of iteration 0, which has
48
77
  * already run. Admits when at least two iterations are left for at least two workers and their
49
78
  * serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
50
79
  */
51
- export declare function admitIteration({ plainIterationMs: t0, trip, width, constants }: AdmitInput): IterationAdmission;
80
+ export declare function admitIteration({ plainIterationMs: t0, trip, width, constants, secondChance }: AdmitInput): IterationAdmission;
52
81
  /** True when a batch did not beat the serial time of its iterations by the margin. */
53
82
  export declare function batchLoses(batchWallMs: number, batchSerialMs: number, constants?: IterationAdmissionConstants): boolean;
54
83
  /** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
@@ -58,19 +87,99 @@ export declare function batchCollapses(batchWallMs: number, batchSerialMs: numbe
58
87
  /**
59
88
  * Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
60
89
  * iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
61
- * rule; `force` admits any loop with an iteration left after iteration 0 and never stops on the
62
- * batch rule. The structural stops (`log-exhausted`, `frame-carried dependence`, `dependency`)
63
- * are not affected.
90
+ * rule, and divides the bound of a batch; `force` admits any loop with an iteration left after
91
+ * iteration 0 and never stops on the batch rule or the bound. The structural stops
92
+ * (`log-exhausted`, `frame-carried dependence`, `dependency`) are not affected. `trace` records
93
+ * one entry per batch in the admission report. `gate` false keeps read windows armed whatever the
94
+ * counted batch says, so a sweep can compare the two.
64
95
  * @internal
65
96
  */
66
97
  export declare const admissionSeam: {
67
98
  scale: number;
68
99
  batchScale: number;
69
100
  force: boolean;
101
+ trace: boolean;
102
+ gate: boolean;
103
+ estimator: "min" | "median" | "mean" | "q75";
70
104
  };
105
+ /**
106
+ * The serial estimate the probe holds after a block: the lower of the last two block means, the
107
+ * median of every block mean so far, or the mean of every probed iteration.
108
+ * @internal
109
+ */
110
+ export declare function probeEstimate(kind: 'min' | 'median' | 'mean' | 'q75', last: number, per: number, means: number[], mean: number): number;
71
111
  /** `admitIteration` through the seam; what the host function calls. */
72
- export declare function decideAdmission(plainIterationMs: number, trip: number, width: number): IterationAdmission;
112
+ export declare function decideAdmission(plainIterationMs: number, trip: number, width: number, secondChance?: boolean): IterationAdmission;
113
+ /** The serial time per iteration as far as the run knows it, and the scale from tracked time. */
114
+ export interface IterationEstimate {
115
+ /** Serial milliseconds per iteration. */
116
+ estimateMs: number;
117
+ /** Serial time over tracked time, fixed by the first batch; undefined before it. */
118
+ kappa?: number;
119
+ /** The same scale for batches that run on read windows; fixed by the first of them. */
120
+ kappaWindows?: number;
121
+ /** The serial time both scales are fitted to: the estimate before the first batch. */
122
+ referenceMs?: number;
123
+ }
124
+ /**
125
+ * Updates the estimate from the worker-side times of the iterations a batch completed, with no
126
+ * host call per iteration. The first batch fixes `kappa` as the serial estimate over the least
127
+ * tracked time, at most 1 because a tracked iteration is never faster than a plain one. The least
128
+ * time, not the median, because the iteration that the estimate came from may be the smallest of
129
+ * a batch that is mostly large, and the median would then read its size as the tracking cost. The
130
+ * estimate is then the mean tracked time times `kappa`: a batch of iterations dearer than the
131
+ * earlier estimate raises it, and a batch of cheaper ones lowers it. When the first iteration was
132
+ * larger than every iteration of the batch, `kappa` is capped and the estimate is the tracked
133
+ * mean, an upper bound on the serial time. Times of zero or less are ignored. A batch on read
134
+ * windows is cheaper to track than the first, so it has its own scale, fitted the same way to the
135
+ * same reference the first time one runs; the unwindowed scale would read its time as serial time.
136
+ */
137
+ export declare function refineEstimate(before: IterationEstimate, trackedMs: readonly number[], windows?: boolean): IterationEstimate;
138
+ /**
139
+ * Whether `remaining` more iterations at `perIterationMs` each are worth dispatching, through the
140
+ * seam. The pool asks it with the online estimate before each batch after the first and after the
141
+ * timed serial blocks of a refused loop.
142
+ *
143
+ * With `last`, the wall and size of the last timed batch, a loop under the floor still goes on
144
+ * when the batches it has seen say so: the pooled cost of what is left is the batch wall times the
145
+ * batches that cover it, and that times the margin has to be under their serial time. The floor
146
+ * prices the wake-up and the learning batch, which a loop that is running has already paid.
147
+ */
148
+ export declare function decideRemaining(perIterationMs: number, remaining: number, width: number, last?: {
149
+ wallMs: number;
150
+ count: number;
151
+ }): boolean;
73
152
  /** `batchLoses` through the seam; what the host function passes the pool. */
74
153
  export declare function decideBatch(batchWallMs: number, batchSerialMs: number): boolean;
75
154
  /** `batchCollapses` through the seam; what the host function passes the pool. */
76
155
  export declare function decideCollapse(batchWallMs: number, batchSerialMs: number): boolean;
156
+ /** Speedup below which a batch cannot pay even with free dispatch, validation and joins. */
157
+ export declare const boundFloor = 1;
158
+ /**
159
+ * The best speedup a batch could reach: the serial time of the iterations it completed over the
160
+ * time `width` workers need for them at the tracked time they showed. Wake, join and validation
161
+ * only add to the wall, so a bound under one means the loop cannot win at this tracking cost.
162
+ */
163
+ export declare function batchBound(perIterationMs: number, trackedMs: readonly number[], width: number): number;
164
+ /**
165
+ * A loop whose first batch bounds the speedup above this has tracking cost to spare: realized
166
+ * speedups ran at about half the bound (aes-ctr 1.2 of 2.3, lz4-compress 1.2 of 2.4,
167
+ * aes-cbc-decrypt 1.2 of 2.0 on the Mac sweep), so such a loop goes on to full batches on its
168
+ * read windows. A loop under it gets one short batch on them first.
169
+ */
170
+ export declare const proofBound = 2;
171
+ /** True when the bound of a batch is under `boundFloor`, through the seam; what the host passes. */
172
+ export declare function decideBound(bound: number): boolean;
173
+ /**
174
+ * The wall and the serial time of the next batch of `next` iterations, from a batch that ran. Its
175
+ * wall minus the time its workers needed for the iterations it completed is the cost that does
176
+ * not shrink with the batch: wake, join and validation. The next batch pays that plus the
177
+ * workers' share of its own iterations. Validation grows with the batch, so the wall comes out
178
+ * low and a projected loss is a loss.
179
+ */
180
+ export declare function projectBatch(wallMs: number, trackedMs: readonly number[], perIterationMs: number, next: number, width: number): {
181
+ wallMs: number;
182
+ serialMs: number;
183
+ } | undefined;
184
+ /** True when a bound is low enough that the first batch on read windows should be a short one. */
185
+ export declare function decideProof(bound: number): boolean;