@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/iteration.js CHANGED
@@ -2,8 +2,10 @@ import { availableParallelism } from 'node:os';
2
2
  import { isSharedArrayBuffer } from 'node:util/types';
3
3
  import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
4
4
  import { inlineGlobals, lowerInline } from "./inline.js";
5
- import { iterationArena, iterationEntryBytes, iterationGranules } from "./iteration-layout.js";
6
- export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules } from "./iteration-layout.js";
5
+ import { admissionSeam, batchBound, probeEstimate, projectBatch, refineEstimate } from "./iteration-admission.js";
6
+ import { iterationArena, iterationEntryBytes, iterationGranules, iterationShadowCopies, iterationWindowCopy } from "./iteration-layout.js";
7
+ import { learnReadWindows, readWindowsClear, readWindowsPay } from "./read-windows.js";
8
+ export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from "./iteration-layout.js";
7
9
  const newReport = (workers) => ({
8
10
  workers,
9
11
  regions: 0,
@@ -12,9 +14,15 @@ const newReport = (workers) => ({
12
14
  fallbacks: 0,
13
15
  traps: 0,
14
16
  exhausted: 0,
17
+ violations: 0,
18
+ stalls: 0,
19
+ stalledIterations: 0,
15
20
  batches: 0,
16
21
  failedBatches: 0,
17
22
  undoEntries: 0,
23
+ maxLogEntries: 0,
24
+ logGrowths: 0,
25
+ retried: 0,
18
26
  conflicts: { raw: 0, war: 0, waw: 0, frame: 0 },
19
27
  dispatchMs: 0,
20
28
  validationMs: 0,
@@ -22,7 +30,11 @@ const newReport = (workers) => ({
22
30
  replayMs: 0,
23
31
  workerRunMs: 0,
24
32
  workerScanMs: 0,
25
- serial: 0
33
+ workerMarkMs: 0,
34
+ workerScanWords: 0,
35
+ workerScanSet: 0,
36
+ serial: 0,
37
+ windowConflicts: 0
26
38
  });
27
39
  const shift = Math.log2(iterationGranules.read / iterationGranules.write);
28
40
  // sorted write granules against sorted read runs
@@ -52,15 +64,165 @@ function hitsWrites(a, b) {
52
64
  }
53
65
  return false;
54
66
  }
67
+ /** The pairwise form: every ordered pair against every other. Any batch size; the reference. @internal */
68
+ export function pairwiseConflicts(outcomes, skip) {
69
+ const found = { raw: 0, war: 0, waw: 0, first: outcomes.length };
70
+ for (let j = 0; j < outcomes.length; j++) {
71
+ for (let k = j + 1; k < outcomes.length; k++) {
72
+ const a = outcomes[j];
73
+ const b = outcomes[k];
74
+ if (!skip.includes('raw') && hitsReads(a.written, b.reads)) {
75
+ found.raw++;
76
+ found.first = Math.min(found.first, k);
77
+ }
78
+ if (!skip.includes('war') && hitsReads(b.written, a.reads)) {
79
+ found.war++;
80
+ found.first = Math.min(found.first, j);
81
+ }
82
+ if (!skip.includes('waw') && hitsWrites(a.written, b.written)) {
83
+ found.waw++;
84
+ found.first = Math.min(found.first, j);
85
+ }
86
+ }
87
+ }
88
+ return found;
89
+ }
90
+ const bitsBelow = (k) => (k >= 32 ? 0xffffffff : k <= 0 ? 0 : 0xffffffff >>> (32 - k));
91
+ const popcount = (value) => {
92
+ value -= (value >>> 1) & 0x55555555;
93
+ value = (value & 0x33333333) + ((value >>> 2) & 0x33333333);
94
+ return (Math.imul((value + (value >>> 4)) & 0x0f0f0f0f, 0x01010101) >>> 24) | 0;
95
+ };
96
+ const lowestBit = (value) => 31 - Math.clz32(value & -value);
97
+ // open-addressing table from a write granule to the set of iterations that wrote it, reused
98
+ const writers = { keys: new Int32Array(0), masks: new Uint32Array(0), used: new Int32Array(0) };
99
+ /**
100
+ * `pairwiseConflicts` in time linear in the sizes of the sets, for at most 32 outcomes: one table
101
+ * from write granule to the bit set of the iterations that wrote it, then each read granule looks
102
+ * its two write granules up. A pair counts once however many granules it shares, so the counts
103
+ * equal the pairwise form's. @internal
104
+ */
105
+ export function tabledConflicts(outcomes, skip) {
106
+ const n = outcomes.length;
107
+ if (n > 32)
108
+ throw new RangeError('at most 32 outcomes');
109
+ const found = { raw: 0, war: 0, waw: 0, first: n };
110
+ let total = 0;
111
+ for (const o of outcomes)
112
+ total += o.written.length;
113
+ if (!total || n < 2)
114
+ return found;
115
+ const size = 1 << Math.max(4, 32 - Math.clz32(2 * total));
116
+ if (writers.keys.length < size) {
117
+ writers.keys = new Int32Array(size);
118
+ writers.masks = new Uint32Array(size);
119
+ writers.used = new Int32Array(size >> 1);
120
+ }
121
+ const { keys, masks, used } = writers;
122
+ keys.fill(0, 0, size);
123
+ masks.fill(0, 0, size);
124
+ const wrap = size - 1;
125
+ const shiftBits = 32 - Math.log2(size);
126
+ const find = (granule, insert) => {
127
+ const key = granule + 1;
128
+ let at = Math.imul(key, 0x9e3779b1) >>> shiftBits;
129
+ for (;;) {
130
+ const have = keys[at];
131
+ if (have === key)
132
+ return at;
133
+ if (have === 0) {
134
+ if (!insert)
135
+ return -1;
136
+ keys[at] = key;
137
+ return at;
138
+ }
139
+ at = (at + 1) & wrap;
140
+ }
141
+ };
142
+ let count = 0;
143
+ for (let k = 0; k < n; k++) {
144
+ const bit = (1 << k) >>> 0;
145
+ for (const granule of outcomes[k].written) {
146
+ const at = find(granule, true);
147
+ if (!masks[at])
148
+ used[count++] = at;
149
+ masks[at] = (masks[at] | bit) >>> 0;
150
+ }
151
+ }
152
+ if (!skip.includes('waw')) {
153
+ const rows = new Uint32Array(n);
154
+ for (let u = 0; u < count; u++) {
155
+ const mask = masks[used[u]];
156
+ if (mask & (mask - 1))
157
+ for (let m = mask; m; m &= m - 1) {
158
+ const k = lowestBit(m);
159
+ rows[k] = (rows[k] | (mask & bitsBelow(k))) >>> 0;
160
+ }
161
+ }
162
+ let any = 0;
163
+ for (const row of rows) {
164
+ found.waw += popcount(row);
165
+ any |= row;
166
+ }
167
+ if (any)
168
+ found.first = Math.min(found.first, lowestBit(any));
169
+ }
170
+ if (skip.includes('raw') && skip.includes('war'))
171
+ return found;
172
+ const raw = new Uint32Array(n);
173
+ const war = new Uint32Array(n);
174
+ const take = (reader, mask) => {
175
+ raw[reader] = (raw[reader] | (mask & bitsBelow(reader))) >>> 0;
176
+ war[reader] = (war[reader] | (mask & ~bitsBelow(reader + 1))) >>> 0;
177
+ };
178
+ for (let k = 0; k < n; k++) {
179
+ const runs = outcomes[k].reads;
180
+ for (let r = 0; r < runs.length; r += 2) {
181
+ const start = runs[r];
182
+ const length = runs[r + 1];
183
+ if (length > count) {
184
+ // a run longer than the table: ask each written granule whether the run covers it
185
+ for (let u = 0; u < count; u++) {
186
+ const at = used[u];
187
+ const read = (keys[at] - 1) >> 1;
188
+ if (read >= start && read < start + length)
189
+ take(k, masks[at]);
190
+ }
191
+ continue;
192
+ }
193
+ for (let g = start; g < start + length; g++) {
194
+ const a = find(2 * g, false);
195
+ const b = find(2 * g + 1, false);
196
+ const mask = ((a < 0 ? 0 : masks[a]) | (b < 0 ? 0 : masks[b])) >>> 0;
197
+ if (mask)
198
+ take(k, mask);
199
+ }
200
+ }
201
+ }
202
+ for (let k = 0; k < n; k++) {
203
+ if (!skip.includes('raw') && raw[k]) {
204
+ found.raw += popcount(raw[k]);
205
+ found.first = Math.min(found.first, k);
206
+ }
207
+ if (!skip.includes('war') && war[k]) {
208
+ found.war += popcount(war[k]);
209
+ found.first = Math.min(found.first, k);
210
+ }
211
+ }
212
+ return found;
213
+ }
55
214
  /**
56
215
  * Index of the first outcome that cannot keep its writes, or -1. Writes land in place, so every
57
216
  * ordered pair is checked three ways: RAW marks the reader, WAR the earlier reader, WAW the earlier
58
217
  * writer. A fourth check covers the frame, which each iteration owns as a private copy: an
59
218
  * iteration fails when it read a frame byte before writing it that an earlier iteration wrote, and
60
- * counts once. Works on the returned lists, never on dense bitmaps.
219
+ * counts once. Works on the returned lists, never on dense bitmaps. A batch of at most 32 goes
220
+ * through `tabledConflicts`, a larger one through the pairwise form.
221
+ *
222
+ * `windowWords` is the number of leading frame words that belong to slot-private windows; the
223
+ * result then also counts, as `window`, the frame conflicts that fall in them.
61
224
  */
62
- export function iterationVerdict(outcomes, skip = []) {
63
- const conflicts = { raw: 0, war: 0, waw: 0, frame: 0 };
225
+ export function iterationVerdict(outcomes, skip = [], windowWords = 0) {
64
226
  let frameFirst = outcomes.length;
65
227
  let firstFailure = outcomes.length;
66
228
  outcomes.forEach((o, k) => {
@@ -68,24 +230,15 @@ export function iterationVerdict(outcomes, skip = []) {
68
230
  firstFailure = Math.min(firstFailure, k);
69
231
  });
70
232
  let first = firstFailure;
71
- for (let j = 0; j < outcomes.length; j++) {
72
- for (let k = j + 1; k < outcomes.length; k++) {
73
- const a = outcomes[j];
74
- const b = outcomes[k];
75
- if (!skip.includes('raw') && hitsReads(a.written, b.reads)) {
76
- conflicts.raw++;
77
- first = Math.min(first, k);
78
- }
79
- if (!skip.includes('war') && hitsReads(b.written, a.reads)) {
80
- conflicts.war++;
81
- first = Math.min(first, j);
82
- }
83
- if (!skip.includes('waw') && hitsWrites(a.written, b.written)) {
84
- conflicts.waw++;
85
- first = Math.min(first, j);
86
- }
87
- }
88
- }
233
+ // an iteration that reached into another slot may have changed what the owner of it saw
234
+ outcomes.forEach((o) => {
235
+ if (o.status && o.touched !== undefined && o.touched >= 0 && o.touched < first)
236
+ first = o.touched;
237
+ });
238
+ const memory = outcomes.length <= 32 ? tabledConflicts(outcomes, skip) : pairwiseConflicts(outcomes, skip);
239
+ const conflicts = { raw: memory.raw, war: memory.war, waw: memory.waw, frame: 0 };
240
+ first = Math.min(first, memory.first);
241
+ let windowed = 0;
89
242
  if (!skip.includes('frame')) {
90
243
  // the frame bytes written by the iterations before k, against the bytes k read unwritten
91
244
  let union;
@@ -95,6 +248,9 @@ export function iterationVerdict(outcomes, skip = []) {
95
248
  conflicts.frame++;
96
249
  first = Math.min(first, k);
97
250
  frameFirst = Math.min(frameFirst, k);
251
+ if (windowWords &&
252
+ exposed.some((word, w) => w < windowWords && word & (union[w] ?? 0)))
253
+ windowed++;
98
254
  }
99
255
  const written = o.frameWritten;
100
256
  if (!written?.length)
@@ -108,9 +264,58 @@ export function iterationVerdict(outcomes, skip = []) {
108
264
  first: first === none ? -1 : first,
109
265
  firstFailure: firstFailure === none ? -1 : firstFailure,
110
266
  frameFirst: frameFirst === none ? -1 : frameFirst,
111
- conflicts
267
+ conflicts,
268
+ ...(windowWords ? { window: windowed } : {})
112
269
  };
113
270
  }
271
+ /**
272
+ * The window a failed batch suggests: the span of the write granules that at least half of its
273
+ * iterations wrote, rounded out to 64 bytes. That is where iterations share a location they write
274
+ * every time, a scratch buffer, a context or an allocator's cursor, and `cap` bytes is the most a
275
+ * pool holds. Half and not two, because iterations that race on a shared context also write wild
276
+ * granules (a length read mid-update indexes anywhere), and those are rarely written twice. Whether
277
+ * the iterations write the window before they read it is not asked here: a window that is wrong
278
+ * only fails validation on the next batch.
279
+ */
280
+ export function discoverWindow(outcomes, cap) {
281
+ const seen = new Map();
282
+ for (const o of outcomes)
283
+ for (const g of o.written)
284
+ seen.set(g, (seen.get(g) ?? 0) + 1);
285
+ const need = Math.max(2, Math.ceil(outcomes.length / 2));
286
+ const shared = [...seen]
287
+ .filter(([, n]) => n >= need)
288
+ .map(([g]) => g)
289
+ .sort((x, y) => x - y);
290
+ const granules = shared.length;
291
+ if (!granules)
292
+ return {
293
+ reason: `no write granule is shared by ${need} of ${outcomes.length} iterations`,
294
+ granules
295
+ };
296
+ const from = Math.floor((shared[0] * 32) / 64) * 64;
297
+ const end = Math.ceil(((shared[granules - 1] + 1) * 32) / 64) * 64;
298
+ if (end - from > cap) {
299
+ // the clusters, split at gaps over 4 KiB, name what the span is made of
300
+ const clusters = [];
301
+ let at = 0;
302
+ for (let i = 1; i <= granules; i++)
303
+ if (i === granules || shared[i] - shared[i - 1] > 128) {
304
+ clusters.push(`0x${(shared[at] * 32).toString(16)}+${(i - at) * 32}`);
305
+ at = i;
306
+ }
307
+ return {
308
+ reason: `the shared writes span ${end - from} bytes, over ${cap}: ${clusters.slice(0, 6).join(' ')}`,
309
+ granules
310
+ };
311
+ }
312
+ return { window: { low: from, end }, granules };
313
+ }
314
+ const PAGE = 65536;
315
+ /** Iterations in the first batch of a loop that learns read windows. */
316
+ const readWindowLearnBatch = 8;
317
+ // callee stack a slot keeps below a window copy and the frame
318
+ const windowStackBytes = 4096;
114
319
  /**
115
320
  * Runs the loop of one owner call on worker threads. Each iteration gets a private stack slot and
116
321
  * tracks its reads and writes inline. The owner validates a batch in order, rolls back the first
@@ -131,6 +336,12 @@ export function iterationVerdict(outcomes, skip = []) {
131
336
  * them) is not tracked, and imported host functions that touch memory are not seen. The shadow
132
337
  * is byte-exact for scalar accesses and ranges; a conservative read would only add reports.
133
338
  *
339
+ * The callee stack of an iteration, the part of its slot below the frame copy, sets no marks and
340
+ * logs no undo entries, and a rollback does not restore it. An access that reaches another slot
341
+ * of the arena traps; the iteration fails with the owner of that slot, so both and every later one
342
+ * replay (`violations` counts them). A program that reads callee stack before writing it sees
343
+ * what an earlier iteration in that slot left, a rolled back one included.
344
+ *
134
345
  * With `admit`, iteration 0 runs first on the owner and the batches cover the rest. Dispatch
135
346
  * stops after a batch that exhausted an undo log, had a frame conflict, replayed more than half of
136
347
  * its iterations, or (with `loses` and `collapses`) two batches in a row did not beat the serial
@@ -148,14 +359,38 @@ export class IterationPool {
148
359
  #u8;
149
360
  #u32;
150
361
  #closed = false;
151
- constructor(memory, arena, width) {
362
+ #memoryBytes;
363
+ #ceiling;
364
+ #readWindows;
365
+ #stall;
366
+ #stalled = false;
367
+ #broken;
368
+ // the batch rules stopped the last call that dispatched, so the first batch of the next is short
369
+ #cold = false;
370
+ // the grown log, taken from pages added above the arena at the first exhaustion and kept
371
+ #grown;
372
+ #route;
373
+ // lowerings besides the open-time one, by key: w the write window, r read windows with the windows
374
+ // tested first and x with the exempt window first, c counting; each is built at its first batch
375
+ // and sent to every worker
376
+ #variants = new Map();
377
+ constructor(route, memory, arena, width, ceiling, readWindows, stall) {
378
+ this.#route = route;
379
+ this.#readWindows = readWindows;
380
+ this.#stall = stall;
152
381
  this.#memory = memory;
153
382
  this.arena = arena;
154
383
  this.width = width;
384
+ this.#ceiling = ceiling;
385
+ this.#memoryBytes = arena.memoryBytes;
155
386
  this.#report = newReport(0);
156
387
  this.#u8 = new Uint8Array(memory.buffer);
157
388
  this.#u32 = new Uint32Array(memory.buffer);
158
389
  }
390
+ /** Bytes of memory the pool expects: the arena's memory plus any pages its grown log added. */
391
+ get memoryBytes() {
392
+ return this.#memoryBytes;
393
+ }
159
394
  /** The report of the last run, also after a run that threw. */
160
395
  get report() {
161
396
  return this.#report;
@@ -170,6 +405,17 @@ export class IterationPool {
170
405
  const width = options.width ?? Math.min(4, availableParallelism());
171
406
  if (!Number.isInteger(width) || width < 1 || width > 64)
172
407
  throw new RangeError('invalid worker count');
408
+ if (options.logCeiling !== undefined &&
409
+ (!Number.isSafeInteger(options.logCeiling) || options.logCeiling < 1))
410
+ throw new RangeError('invalid log ceiling');
411
+ const stall = options.stall
412
+ ? {
413
+ factor: (options.stall === true ? undefined : options.stall.factor) ?? 50,
414
+ floorMs: (options.stall === true ? undefined : options.stall.floorMs) ?? 2000
415
+ }
416
+ : undefined;
417
+ if (stall && !(stall.factor >= 0 && stall.floorMs > 0))
418
+ throw new RangeError('invalid stall limits');
173
419
  const frameSize = route.frame?.size ?? 0;
174
420
  const arena = iterationArena(options.arenaBase, memoryBytes, {
175
421
  ...options,
@@ -179,15 +425,25 @@ export class IterationPool {
179
425
  throw new RangeError('arena does not fit in memory');
180
426
  if (frameSize >= arena.slotBytes)
181
427
  throw new RangeError('slot is smaller than the frame');
428
+ if (route.ownership) {
429
+ const shadow = route.ownership.windows.reduce((n, w) => n + w.end - w.low + 64, 0);
430
+ if (arena.slotBytes - frameSize - shadow < windowStackBytes)
431
+ throw new RangeError('the slot cannot hold the certified windows and a stack');
432
+ }
182
433
  const lowered = lowerInline(route.module, {
183
434
  readGranule: iterationGranules.read,
184
435
  writeGranule: iterationGranules.write,
185
- frame: frameSize > 0
436
+ frame: frameSize > 0,
437
+ slot: true,
438
+ stop: Boolean(stall),
439
+ readSummary: arena.ssize
186
440
  });
187
441
  const module = new WebAssembly.Module(Uint8Array.from(lowered));
188
- const pool = new IterationPool(memory, arena, width);
442
+ const pool = new IterationPool(route, memory, arena, width, options.logCeiling ?? arena.logCapacity, Boolean(options.readWindows), stall);
189
443
  pool.#u8.fill(0, arena.stamp, arena.stamp + 64);
190
444
  pool.#u8.fill(0, arena.rmaps, arena.wmaps + arena.batch * arena.wsize);
445
+ if (arena.ssize)
446
+ pool.#u8.fill(0, arena.smaps, arena.smaps + arena.batch * arena.ssize);
191
447
  const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
192
448
  try {
193
449
  await Promise.all(Array.from({ length: width }, () => {
@@ -202,6 +458,7 @@ export class IterationPool {
202
458
  iterate: route.iterate,
203
459
  locals: route.locals,
204
460
  frameSize,
461
+ ownership: route.ownership,
205
462
  port: channel.port2,
206
463
  signal,
207
464
  control: pool.#control.buffer
@@ -225,49 +482,136 @@ export class IterationPool {
225
482
  }
226
483
  return pool;
227
484
  }
228
- // blocks the owner thread until the worker replies, the idiom of TaskPool.join
229
- #join(link) {
485
+ // blocks the owner thread until the worker replies, the idiom of TaskPool.join; undefined when
486
+ // the clock passes `deadline` first
487
+ #join(link, deadline = Infinity) {
230
488
  for (;;) {
231
489
  const seen = Atomics.load(link.signal, 0);
232
490
  const message = receiveMessageOnPort(link.port);
233
491
  if (message)
234
492
  return message.message;
235
- Atomics.wait(link.signal, 0, seen);
493
+ const wait = deadline - performance.now();
494
+ if (wait <= 0)
495
+ return;
496
+ Atomics.wait(link.signal, 0, seen, wait);
236
497
  }
237
498
  }
238
499
  /** Runs the loop to completion with ordered validation. Blocks the calling thread. */
239
500
  run(job) {
240
501
  if (this.#closed)
241
502
  throw new Error('iteration pool is closed');
242
- if (this.#memory.buffer.byteLength !== this.arena.memoryBytes)
503
+ if (this.#broken)
504
+ throw new Error(this.#broken);
505
+ if (this.#memory.buffer.byteLength !== this.#memoryBytes)
243
506
  throw new Error('memory changed size while the iteration pool was open');
244
507
  if (!Number.isSafeInteger(job.trip) || job.trip < 0)
245
508
  throw new RangeError('invalid trip count');
246
509
  const A = this.arena;
247
510
  const report = (this.#report = newReport(Math.min(this.width, Math.max(job.trip, 0))));
248
- let plainMs = 0;
511
+ const owned = this.#route.ownership;
512
+ const why = owned && this.#refuseOwnership(owned, job.frameBase);
513
+ if (why) {
514
+ // the certified windows cannot be privatized here, so the program runs as written
515
+ report.windowRefused = why;
516
+ report.stopped = 'no-admission';
517
+ for (let k = 0; k < job.trip; k++) {
518
+ report.serial++;
519
+ job.replay(k);
520
+ }
521
+ return report;
522
+ }
523
+ // serial time per iteration as far as it is known: iteration 0, then timed serial blocks, then
524
+ // the workers' own times scaled by `kappa`, the ratio of serial to tracked time
525
+ let estimate = { estimateMs: 0 };
249
526
  let from = 0;
250
527
  if (job.admit && job.trip > 0) {
251
528
  // iteration 0 is the serial program's own first iteration, so its writes stay
252
529
  const t = performance.now();
253
530
  report.serial = 1;
254
531
  job.replay(0);
255
- plainMs = performance.now() - t;
532
+ const plainMs = performance.now() - t;
533
+ estimate = { estimateMs: plainMs };
256
534
  from = 1;
257
535
  report.admission = job.admit(plainMs);
536
+ report.admission.estimateMs = plainMs;
537
+ if (report.admission.probe && job.trip > 3) {
538
+ // iteration 0 runs cold, and a probe is judged on the estimate, so time one more
539
+ const t = performance.now();
540
+ report.serial++;
541
+ job.replay(1);
542
+ estimate = { estimateMs: Math.min(plainMs, performance.now() - t) };
543
+ from = 2;
544
+ report.admission.estimateMs = estimate.estimateMs;
545
+ }
258
546
  if (!report.admission.admitted) {
259
- report.stopped = 'no-admission';
260
- for (let k = 1; k < job.trip; k++) {
261
- report.serial++;
262
- job.replay(k);
547
+ const probed = this.#probe(job, report, plainMs);
548
+ if (probed.at >= job.trip) {
549
+ report.stopped = 'no-admission';
550
+ return report;
263
551
  }
264
- return report;
552
+ from = probed.at;
553
+ estimate = { estimateMs: probed.estimate };
554
+ report.admission.admitted = true;
555
+ report.admission.readmittedAt = from;
265
556
  }
266
557
  }
267
558
  let stopped = false;
268
559
  let slow = 0;
269
- for (let first = from; first < job.trip; first += A.batch) {
270
- const count = Math.min(A.batch, job.trip - first);
560
+ // wall and size of the last batch that was timed against the serial estimate
561
+ let lastTimed;
562
+ // the estimate runs high when iteration 0 was the fastest; a probe is a gamble on the
563
+ // estimate, so it is judged on iteration 0's own time when that is lower
564
+ const perMs = () => report.admission?.probe
565
+ ? Math.min(estimate.estimateMs, estimate.referenceMs ?? Infinity)
566
+ : estimate.estimateMs;
567
+ let window;
568
+ let tried = job.discover === false || !A.windowBytes;
569
+ let probeLeft = 0;
570
+ let rw;
571
+ let rwTried = !this.#readWindows;
572
+ // the first batch on newly learned read windows is one iteration per worker: its tracked
573
+ // cost is not known until it ran, and a loop it cannot pay for should not run a full batch.
574
+ // So is the first batch after a call the batch rules stopped: the code may still be at its
575
+ // baseline tier, where a full batch runs several slow iterations per worker
576
+ let prove = Boolean(job.admit && job.hopeless) && rwTried && this.#cold;
577
+ // learned windows are armed after one counted batch on them says they pay
578
+ let rwCounted = false;
579
+ let rwOrder = 'window';
580
+ // iterations of the short learning batch, so the next batch realigns to the grid of full ones
581
+ let offGrid = 0;
582
+ const probes = [];
583
+ let pendingStop;
584
+ if (job.window) {
585
+ tried = true;
586
+ const why = this.#refuseWindow(job.window, job.frameBase);
587
+ if (why)
588
+ report.windowRefused = why;
589
+ else {
590
+ window = { low: job.window.low, end: job.window.end };
591
+ report.window = { ...window, source: 'given', batches: 0 };
592
+ }
593
+ }
594
+ let logs = {
595
+ base: A.logs,
596
+ capacity: A.logCapacity,
597
+ bytes: A.logBytes,
598
+ inFlight: A.batch
599
+ };
600
+ let grown = false;
601
+ // the batch rules ended the dispatch, as against the floor on the serial time that is left
602
+ let costStop = false;
603
+ for (let first = from; first < job.trip;) {
604
+ // the first batch of a loop that may learn read windows is short, so little runs fully tracked
605
+ const small = !rwTried && !rw && report.batches === 0;
606
+ const counting = Boolean(rw) && !rwCounted;
607
+ // short batches shift the grid of full ones, and a tail the floor then refuses runs
608
+ // serially; the batch after them is cut so that the ones after that end where they would
609
+ const full = logs.inFlight - (offGrid % logs.inFlight);
610
+ const count = Math.min(probeLeft ? 1 : small ? readWindowLearnBatch : prove ? this.width : full, job.trip - first);
611
+ if (small || prove)
612
+ offGrid += count;
613
+ else if (!probeLeft)
614
+ offGrid = 0;
271
615
  if (stopped) {
272
616
  const t = performance.now();
273
617
  try {
@@ -279,39 +623,196 @@ export class IterationPool {
279
623
  finally {
280
624
  report.replayMs += performance.now() - t;
281
625
  }
626
+ first += count;
627
+ continue;
628
+ }
629
+ // the estimate has been updated by the batches before; what is left may no longer pay
630
+ // a probe has no timed batch to go on until its first one is done
631
+ const waiting = report.admission?.probe && !lastTimed;
632
+ if (report.batches &&
633
+ job.admit &&
634
+ !waiting &&
635
+ job.reconsider?.(perMs(), job.trip - first, lastTimed) === false) {
636
+ report.stopped ??= 'no-admission';
637
+ stopped = true;
282
638
  continue;
283
639
  }
284
640
  report.batches++;
641
+ const short = prove;
642
+ prove = false;
643
+ const ran = window;
644
+ if (report.window && ran)
645
+ report.window.batches++;
646
+ let usedRw;
647
+ if (rw) {
648
+ if (readWindowsClear(rw, first, count, this.#memoryBytes, this.#forbidden())) {
649
+ usedRw = rw;
650
+ report.readWindows.batches++;
651
+ }
652
+ else
653
+ report.readWindowRefused ??=
654
+ 'a window of a batch leaves memory or meets the arena';
655
+ }
656
+ const counted = Boolean(usedRw) && counting;
657
+ // lowering a variant happens before the batch is timed
658
+ const variant = this.#variant(Boolean(ran), usedRw ? rwOrder : undefined, counted);
285
659
  const t0 = performance.now();
286
- const outcomes = this.#dispatch(first, count, job, report);
287
- report.regions += outcomes.length;
660
+ const outcomes = this.#dispatch(first, count, job, report, logs, estimate.estimateMs, ran, usedRw, variant);
661
+ const stalled = this.#stalled;
662
+ if (stalled)
663
+ report.stalls++;
288
664
  const t1 = performance.now();
289
665
  report.dispatchMs += t1 - t0;
290
666
  for (const o of outcomes) {
291
667
  report.undoEntries += o.entries;
668
+ if (o.status === 3)
669
+ report.stalledIterations++;
670
+ if (o.status === 0)
671
+ report.maxLogEntries = Math.max(report.maxLogEntries, o.entries);
292
672
  if (o.status === 1)
293
673
  report.traps++;
294
674
  if (o.status === 2)
295
675
  report.exhausted++;
676
+ if (o.touched !== undefined && o.touched >= 0)
677
+ report.violations++;
296
678
  }
297
- const v = iterationVerdict(outcomes, job.skip);
679
+ const v = iterationVerdict(outcomes, job.skip, ran ? Math.ceil((ran.end - ran.low) / 32) : 0);
680
+ report.windowConflicts += v.window ?? 0;
298
681
  report.conflicts.raw += v.conflicts.raw;
299
682
  report.conflicts.war += v.conflicts.war;
300
683
  report.conflicts.waw += v.conflicts.waw;
301
684
  report.conflicts.frame += v.conflicts.frame;
302
685
  const t2 = performance.now();
303
686
  report.validationMs += t2 - t1;
687
+ // an exhausted log is retried once from the first failing iteration with the grown log;
688
+ // the iterations before it stay, and the rest are rolled back and dispatched again. A
689
+ // hazard already found among the iterations that ran is no retry: their sets only grow, so
690
+ // the dependence would be there again and the dispatch would end after a wasted batch
691
+ const hazards = v.conflicts.raw + v.conflicts.war + v.conflicts.waw + v.conflicts.frame;
692
+ // read windows are learned from the first batch that completed clean; a batch on them that
693
+ // conflicts drops them and is not held against the loop, because the window may be the cause
694
+ let rwExempt = false;
695
+ if (usedRw && hazards) {
696
+ rw = undefined;
697
+ rwExempt = true;
698
+ report.readWindowRefused = 'a batch on the read windows conflicted';
699
+ }
700
+ else if (counted) {
701
+ // the first batch on the windows counts its loads, and the windows stay only if they pay;
702
+ // it is a full batch, so counting costs the loop no extra dispatch
703
+ rwCounted = true;
704
+ rwExempt = !short;
705
+ const done = outcomes.filter((o) => o.status === 0 && o.counts);
706
+ const counts = { hits: 0, misses: 0, exempt: 0 };
707
+ for (const o of done) {
708
+ counts.hits += o.counts.hits;
709
+ counts.misses += o.counts.misses;
710
+ counts.exempt += o.counts.exempt;
711
+ }
712
+ const verdict = readWindowsPay(counts, rw, Boolean(A.frameBytes), done.length);
713
+ const armed = verdict.pay || !admissionSeam.gate;
714
+ rwOrder = verdict.order;
715
+ report.readWindowGate = {
716
+ iterations: done.length,
717
+ counts,
718
+ saved: verdict.saved,
719
+ spent: verdict.spent,
720
+ order: verdict.order,
721
+ armed
722
+ };
723
+ if (!armed) {
724
+ rw = undefined;
725
+ report.readWindowRefused = 'the windows would not pay for the loop';
726
+ }
727
+ }
728
+ else if (!rwTried && !rw) {
729
+ const completed = outcomes.filter((o) => o.status === 0).length;
730
+ if (hazards) {
731
+ rwTried = true;
732
+ report.readWindowRefused = 'the batch to learn from conflicted';
733
+ }
734
+ else if (completed >= 3) {
735
+ rwTried = true;
736
+ const found = learnReadWindows(outcomes);
737
+ if (found.windows) {
738
+ rw = found.windows;
739
+ report.readWindows = { ...rw, batches: 0, learnedFrom: completed };
740
+ }
741
+ else
742
+ report.readWindowRefused = found.reason;
743
+ }
744
+ }
745
+ // a batch that conflicts is the price of learning that iterations share a scratch location.
746
+ // Two single-iteration batches follow it; they race with nothing, so the granules both
747
+ // wrote are the shared ones, and the loop goes on with a window over them
748
+ if (stalled)
749
+ probeLeft = 0;
750
+ const probing = probeLeft > 0;
751
+ let learning = false;
752
+ const exhausted = outcomes.some((o) => o.status === 2);
753
+ // at least half the iterations wrote some granule: a scratch location could be a window
754
+ const shared = !tried && hazards && !stalled
755
+ ? discoverWindow(outcomes, Infinity).granules > 0
756
+ : false;
757
+ if (!tried && hazards && !shared && !stalled) {
758
+ tried = true;
759
+ report.windowRefused = 'no write granule is shared by half of the iterations';
760
+ }
761
+ // an exhausted log is grown first, the batch is dispatched again, and a window follows
762
+ const area = !stalled && !grown && (!hazards || shared) && exhausted && v.first >= 0
763
+ ? this.#growLog()
764
+ : undefined;
765
+ // iterations that race on a shared location can run far past their log while the others of
766
+ // the batch finish, and one that ran away says nothing about the capacity. So when some
767
+ // iteration finished and there is no log to grow, the exhaustion is not the loop's
768
+ // verdict: the window is probed first, and the stop stands only if there is none. If every
769
+ // iteration ran past its log the loop needs more than the log holds, and the stop stands
770
+ const fits = !exhausted || outcomes.some((o) => o.status === 0);
771
+ if (shared && !area && fits) {
772
+ tried = true;
773
+ if (first + count < job.trip) {
774
+ probeLeft = 2;
775
+ learning = true;
776
+ }
777
+ else {
778
+ // no iteration is left to probe with: the cell half the batch wrote is the window
779
+ // for the next call, and validation checks it there like any given window
780
+ const found = discoverWindow(outcomes, A.windowBytes);
781
+ const why = found.window
782
+ ? this.#refuseWindow(found.window, job.frameBase)
783
+ : found.reason;
784
+ if (why || !found.window)
785
+ report.windowRefused = why;
786
+ else {
787
+ window = found.window;
788
+ report.window = { ...window, source: 'discovered', batches: 0 };
789
+ }
790
+ }
791
+ }
792
+ if (area) {
793
+ this.#rollback(logs, first, outcomes, v.first);
794
+ this.#commitFrame(job, outcomes, v.first, ran);
795
+ grown = true;
796
+ logs = area;
797
+ report.regions += v.first;
798
+ report.retried += outcomes.length - v.first;
799
+ report.logGrowths++;
800
+ report.rollbackMs += performance.now() - t2;
801
+ first += v.first;
802
+ continue;
803
+ }
804
+ report.regions += outcomes.length;
304
805
  let replays = 0;
305
806
  if (v.first < 0)
306
- this.#commitFrame(job, outcomes, count);
807
+ this.#commitFrame(job, outcomes, count, ran);
307
808
  else {
308
809
  replays = count - v.first;
309
810
  report.failedBatches++;
310
811
  if (v.firstFailure === v.first)
311
812
  report.fallbacks++;
312
- this.#rollback(first, outcomes, v.first);
813
+ this.#rollback(logs, first, outcomes, v.first);
313
814
  report.rolledBack += outcomes.length - v.first;
314
- this.#commitFrame(job, outcomes, v.first);
815
+ this.#commitFrame(job, outcomes, v.first, ran);
315
816
  const t3 = performance.now();
316
817
  report.rollbackMs += t3 - t2;
317
818
  try {
@@ -328,85 +829,359 @@ export class IterationPool {
328
829
  }
329
830
  }
330
831
  const wallMs = performance.now() - t0;
331
- const serialMs = count * plainMs;
832
+ if (job.admit) {
833
+ // the workers' own time per completed iteration, scaled to serial time
834
+ estimate = refineEstimate(estimate, outcomes.filter((o) => o.status === 0).map((o) => o.runMs), Boolean(usedRw));
835
+ }
836
+ const serialMs = count * perMs();
837
+ if (report.admission && admissionSeam.trace) {
838
+ const ran = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
839
+ (report.admission.trace ??= []).push({
840
+ first,
841
+ count,
842
+ windows: Boolean(usedRw),
843
+ trackedMeanMs: ran.reduce((a, b) => a + b, 0) / (ran.length || 1),
844
+ kappa: usedRw ? estimate.kappaWindows : estimate.kappa,
845
+ estimateMs: estimate.estimateMs,
846
+ wallMs,
847
+ serialMs
848
+ });
849
+ }
332
850
  if (report.admission) {
333
851
  report.admission.batchWallMs = wallMs;
334
852
  report.admission.batchSerialMs = serialMs;
853
+ report.admission.estimateMs = estimate.estimateMs;
335
854
  }
336
855
  // the first batch also pays for waking the workers, so a batch that is merely slow is not a
337
856
  // verdict until a second one confirms it
338
- slow = job.admit && job.loses?.(wallMs, serialMs) ? slow + 1 : 0;
339
- const collapsed = job.admit && job.collapses?.(wallMs, serialMs);
340
- const stop = outcomes.some((o) => o.status === 2)
341
- ? 'log-exhausted'
342
- : v.frameFirst >= 0
343
- ? 'frame-carried dependence'
344
- : replays * 2 > count
345
- ? 'dependency'
346
- : (slow >= 2 || collapsed) && first + count < job.trip
347
- ? 'no-admission'
348
- : undefined;
857
+ const exempt = learning || probing || rwExempt;
858
+ // a short batch that only learns pays for waking the workers and says nothing about the loop
859
+ const timed = !exempt && !small && !short;
860
+ // tracking cost bounds the speedup whatever the dispatch costs; read windows learned by
861
+ // this batch will change that cost, so their first batch decides
862
+ const windowsNext = Boolean(rw) && report.readWindows?.batches === 0;
863
+ const tracked = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
864
+ if (windowsNext &&
865
+ job.admit &&
866
+ job.hopeless &&
867
+ job.unproven?.(batchBound(perMs(), tracked, this.width)))
868
+ prove = true;
869
+ let hopeless = !exempt &&
870
+ !stalled &&
871
+ !windowsNext &&
872
+ Boolean(job.admit) &&
873
+ job.hopeless?.(batchBound(perMs(), tracked, this.width)) === true;
874
+ // the short batch on new read windows prices the next full one before it runs
875
+ if (short && !hopeless && !exempt && !stalled && job.admit && job.loses) {
876
+ const next = projectBatch(wallMs, tracked, perMs(), Math.min(logs.inFlight, job.trip - first - count), this.width);
877
+ hopeless = next !== undefined && job.loses(next.wallMs, next.serialMs);
878
+ }
879
+ slow = timed && job.admit && job.loses?.(wallMs, serialMs) ? slow + 1 : 0;
880
+ if (timed)
881
+ lastTimed = { wallMs, count };
882
+ const confirm = report.admission?.probe ? 1 : 2;
883
+ const collapsed = timed && job.admit && job.collapses?.(wallMs, serialMs);
884
+ const named = stalled
885
+ ? 'stalled'
886
+ : outcomes.some((o) => o.status === 2)
887
+ ? 'log-exhausted'
888
+ : v.frameFirst >= 0
889
+ ? 'frame-carried dependence'
890
+ : replays * 2 > count
891
+ ? 'dependency'
892
+ : (slow >= confirm || collapsed || hopeless) && first + count < job.trip
893
+ ? 'no-admission'
894
+ : undefined;
895
+ if (learning)
896
+ pendingStop = named;
897
+ let stop = stalled ? 'stalled' : exempt ? undefined : named;
898
+ if (probing) {
899
+ probes.push(...outcomes);
900
+ if (--probeLeft === 0) {
901
+ const found = probes.length === 2 && probes.every((o) => o.status === 0)
902
+ ? discoverWindow(probes, A.windowBytes)
903
+ : { reason: 'a probe iteration did not complete' };
904
+ const why = found.window
905
+ ? this.#refuseWindow(found.window, job.frameBase)
906
+ : found.reason;
907
+ if (why || !found.window) {
908
+ report.windowRefused = why;
909
+ stop = pendingStop;
910
+ }
911
+ else {
912
+ window = found.window;
913
+ report.window = { ...window, source: 'discovered', batches: 0 };
914
+ }
915
+ }
916
+ }
349
917
  if (stop) {
350
918
  report.stopped ??= stop;
919
+ if (stop === 'no-admission')
920
+ costStop = true;
921
+ if (stop === 'no-admission' && report.admission?.probe)
922
+ report.admission.probeLost = true;
351
923
  stopped = true;
352
924
  }
925
+ first += count;
353
926
  }
927
+ if (probeLeft > 0 && pendingStop)
928
+ report.stopped ??= pendingStop;
929
+ if (job.admit && report.batches)
930
+ this.#cold = costStop;
354
931
  return report;
355
932
  }
356
- #dispatch(first, count, job, report) {
933
+ // replays the rest of a refused loop in blocks of 1, 2, 4 up to a batch, timing each block. The
934
+ // estimate is the lower of the last two blocks so one slow block is not a verdict; when
935
+ // `reconsider` says the remaining iterations pay, dispatch starts there. Returns the index
936
+ // reached and the estimate; the index is the trip count when nothing was dispatchable.
937
+ #probe(job, report, plainMs) {
938
+ let block = 1;
939
+ let last = plainMs;
940
+ let estimate = plainMs;
941
+ const means = [plainMs];
942
+ let probed = 0;
943
+ let spent = 0;
944
+ let k = 1;
945
+ while (k < job.trip) {
946
+ const size = job.reconsider ? Math.min(block, job.trip - k) : job.trip - k;
947
+ const t = performance.now();
948
+ for (let i = 0; i < size; i++) {
949
+ report.serial++;
950
+ job.replay(k + i);
951
+ }
952
+ const elapsed = performance.now() - t;
953
+ const per = elapsed / size;
954
+ k += size;
955
+ probed += size;
956
+ spent += elapsed;
957
+ means.push(per);
958
+ estimate = probeEstimate(admissionSeam.estimator, last, per, means, spent / probed);
959
+ last = per;
960
+ block = Math.min(block * 2, this.arena.batch);
961
+ if (report.admission)
962
+ report.admission.estimateMs = estimate;
963
+ if (k < job.trip && job.reconsider?.(estimate, job.trip - k))
964
+ return { at: k, estimate };
965
+ }
966
+ return { at: k, estimate };
967
+ }
968
+ // pages above the arena for logs of `logCeiling` entries, one per iteration in flight. The undo
969
+ // code writes them without marking, so no bitmap has to cover them and the program never names
970
+ // them. Undefined when the ceiling is not above the default, the memory changed size under the
971
+ // pool, or the memory cannot grow (its declared maximum). The pages stay for later calls.
972
+ #growLog() {
973
+ if (this.#grown)
974
+ return this.#grown;
975
+ const A = this.arena;
976
+ if (this.#ceiling <= A.logCapacity)
977
+ return;
978
+ if (this.#memory.buffer.byteLength !== this.#memoryBytes)
979
+ return;
980
+ const bytes = Math.ceil((this.#ceiling * iterationEntryBytes) / 64) * 64;
981
+ const inFlight = Math.min(2 * this.width, A.batch);
982
+ const pages = Math.ceil((inFlight * bytes) / PAGE);
983
+ try {
984
+ this.#memory.grow(pages);
985
+ }
986
+ catch (error) {
987
+ if (error instanceof RangeError)
988
+ return;
989
+ throw error;
990
+ }
991
+ const base = this.#memoryBytes;
992
+ this.#memoryBytes += pages * PAGE;
993
+ this.#u8 = new Uint8Array(this.#memory.buffer);
994
+ this.#u32 = new Uint32Array(this.#memory.buffer);
995
+ return (this.#grown = { base, capacity: this.#ceiling, bytes, inFlight });
996
+ }
997
+ #dispatch(first, count, job, report, logs, estimateMs, window, readWindows, variant = '') {
357
998
  this.#control[0] = 0;
358
999
  Atomics.store(this.#u32, this.arena.stamp / 4, 0);
1000
+ Atomics.store(this.#u32, this.arena.stamp / 4 + 1, 0);
1001
+ this.#stalled = false;
359
1002
  const used = this.#links.slice(0, Math.min(this.width, count));
360
1003
  const message = {
361
1004
  first,
362
1005
  count,
363
1006
  entry: job.entry,
364
1007
  frameBase: job.frameBase,
365
- reverse: job.schedule === 'reverse'
1008
+ reverse: job.schedule === 'reverse',
1009
+ logs,
1010
+ memoryBytes: this.#memoryBytes,
1011
+ window,
1012
+ readWindows,
1013
+ variant
366
1014
  };
367
1015
  for (const link of used)
368
1016
  link.port.postMessage(message);
369
1017
  const outcomes = [];
370
1018
  let failure;
1019
+ const stall = this.#stall;
1020
+ // the wait covers the iterations one worker runs; the stop word gets the same time to take hold
1021
+ const limit = stall
1022
+ ? stall.floorMs + stall.factor * Math.ceil(count / used.length) * estimateMs
1023
+ : Infinity;
1024
+ let deadline = stall ? performance.now() + limit : Infinity;
371
1025
  for (const link of used) {
372
- const reply = this.#join(link);
1026
+ let reply = this.#join(link, deadline);
1027
+ if (!reply && !this.#stalled) {
1028
+ this.#stalled = true;
1029
+ Atomics.store(this.#control, 0, 1 << 30);
1030
+ Atomics.store(this.#u32, this.arena.stamp / 4 + 1, 1);
1031
+ deadline = performance.now() + limit;
1032
+ reply = this.#join(link, deadline);
1033
+ }
1034
+ if (!reply) {
1035
+ // a worker that polls no stop word is past help, and memory may be changing under the owner
1036
+ this.#broken = `iteration worker did not stop within ${Math.round(limit)} ms of the stall word`;
1037
+ for (const l of this.#links)
1038
+ l.worker.terminate().catch(() => { });
1039
+ throw new Error(this.#broken);
1040
+ }
373
1041
  if (reply.error !== undefined)
374
1042
  failure ??= reply.error;
375
1043
  else {
376
1044
  outcomes.push(...reply.done);
377
1045
  report.workerRunMs += reply.runMs;
378
1046
  report.workerScanMs += reply.scanMs;
1047
+ report.workerMarkMs += reply.markMs;
1048
+ report.workerScanWords += reply.scanWords;
1049
+ report.workerScanSet += reply.scanSet;
379
1050
  }
380
1051
  }
381
1052
  if (failure !== undefined)
382
1053
  throw new Error(`iteration worker failed: ${failure}`);
383
1054
  return outcomes.sort((a, b) => a.index - b.index);
384
1055
  }
385
- // the written frame bytes of the first `kept` iterations of a batch, in order, into the owner frame
386
- #commitFrame(job, outcomes, kept) {
1056
+ // the written bytes of the first `kept` iterations of a batch, in order: frame bytes into the owner
1057
+ // frame, and window bytes into the window, so a later iteration's write wins as it does serially
1058
+ #commitFrame(job, outcomes, kept, window) {
387
1059
  const A = this.arena;
388
- if (!A.frameBytes)
1060
+ const owned = this.#route.ownership;
1061
+ if (owned && kept > 0) {
1062
+ // the last kept iteration wrote every copy-out byte, so its copy is the serial window
1063
+ const last = outcomes[kept - 1];
1064
+ const top = A.slots + (last.index - outcomes[0].index + 1) * A.slotBytes;
1065
+ const { copies } = iterationShadowCopies(top, A.frameBytes, owned.windows);
1066
+ for (const [from, end] of owned.copyOut) {
1067
+ const i = owned.windows.findIndex((w) => from >= w.low && end <= w.end);
1068
+ const at = copies[i].copy - owned.windows[i].low;
1069
+ this.#u8.copyWithin(from, from + at, end + at);
1070
+ }
1071
+ }
1072
+ if (!A.frameBytes && !window)
389
1073
  return;
390
1074
  for (let k = 0; k < kept; k++) {
391
1075
  const o = outcomes[k];
392
1076
  const slot = o.index - outcomes[0].index;
393
- const frame = A.slots + (slot + 1) * A.slotBytes - A.frameBytes;
1077
+ const top = A.slots + (slot + 1) * A.slotBytes;
1078
+ if (!window) {
1079
+ const frame = top - A.frameBytes;
1080
+ o.frameWritten.forEach((word, g) => {
1081
+ for (let b = 0; b < 32; b++)
1082
+ if ((word >>> b) & 1) {
1083
+ const at = 32 * g + b;
1084
+ this.#u8[job.frameBase + at] = this.#u8[frame + at];
1085
+ }
1086
+ });
1087
+ continue;
1088
+ }
1089
+ const w = iterationWindowCopy(top, A.frameBytes, window);
1090
+ const bytes = window.end - window.low;
394
1091
  o.frameWritten.forEach((word, g) => {
395
1092
  for (let b = 0; b < 32; b++)
396
1093
  if ((word >>> b) & 1) {
397
1094
  const at = 32 * g + b;
398
- this.#u8[job.frameBase + at] = this.#u8[frame + at];
1095
+ if (at < bytes)
1096
+ this.#u8[window.low + at] = this.#u8[w.copy + at];
1097
+ else if (at >= w.frameOffset)
1098
+ this.#u8[job.frameBase + at - w.frameOffset] = this.#u8[w.copy + at];
399
1099
  }
400
1100
  });
401
1101
  }
402
1102
  }
403
- // newest stamp first across every iteration being rolled back
404
- #rollback(first, outcomes, from) {
1103
+ // why a window cannot be used for this call, or undefined when it can
1104
+ #refuseWindow(window, frameBase) {
1105
+ const A = this.arena;
1106
+ const bytes = window.end - window.low;
1107
+ if (!A.windowBytes)
1108
+ return 'the arena reserves no window bytes';
1109
+ if (!Number.isSafeInteger(window.low) || !Number.isSafeInteger(window.end) || bytes <= 0)
1110
+ return 'invalid window';
1111
+ if (window.low % 64 || window.end % 64)
1112
+ return 'the window is not 64-byte aligned';
1113
+ if (bytes > A.windowBytes)
1114
+ return `the window of ${bytes} bytes is over ${A.windowBytes}`;
1115
+ if (window.end > this.#memoryBytes)
1116
+ return 'the window passes the end of memory';
1117
+ const meets = (low, end) => window.low < end && window.end > low;
1118
+ if (meets(A.base, A.base + A.bytes))
1119
+ return 'the window overlaps the arena';
1120
+ if (this.#grown &&
1121
+ meets(this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
1122
+ return 'the window overlaps the grown logs';
1123
+ if (A.frameBytes && meets(frameBase, frameBase + A.frameBytes))
1124
+ return 'the window overlaps the owner frame';
1125
+ if (A.slotBytes - A.frameBytes - bytes - 64 < windowStackBytes)
1126
+ return `the window leaves less than ${windowStackBytes} bytes of stack in a slot`;
1127
+ }
1128
+ // why the certified windows cannot be privatized for this call, or undefined when they can
1129
+ #refuseOwnership(plan, frameBase) {
1130
+ const A = this.arena;
1131
+ const meets = (w, low, end) => w.low < end && w.end > low;
1132
+ for (const w of plan.windows) {
1133
+ if (w.end > this.#memoryBytes)
1134
+ return 'a certified window passes the end of memory';
1135
+ if (meets(w, A.base, A.base + A.bytes))
1136
+ return 'a certified window overlaps the arena';
1137
+ if (this.#grown &&
1138
+ meets(w, this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
1139
+ return 'a certified window overlaps the grown logs';
1140
+ if (A.frameBytes && meets(w, frameBase, frameBase + A.frameBytes))
1141
+ return 'a certified window overlaps the owner frame';
1142
+ }
1143
+ }
1144
+ // address ranges a read window must stay out of: the arena and the grown logs
1145
+ #forbidden() {
405
1146
  const A = this.arena;
1147
+ const found = [[A.base, A.base + A.bytes]];
1148
+ if (this.#grown)
1149
+ found.push([
1150
+ this.#grown.base,
1151
+ this.#grown.base + this.#grown.inFlight * this.#grown.bytes
1152
+ ]);
1153
+ return found;
1154
+ }
1155
+ // lowers the variant a batch needs once and hands it to every worker before their next batch;
1156
+ // the key is empty for the module the pool opened with
1157
+ #variant(window, order, count) {
1158
+ const key = `${window ? 'w' : ''}${order ? (order === 'window' ? 'r' : 'x') : ''}${count ? 'c' : ''}`;
1159
+ if (!key || this.#variants.has(key))
1160
+ return key;
1161
+ const lowered = lowerInline(this.#route.module, {
1162
+ readGranule: iterationGranules.read,
1163
+ writeGranule: iterationGranules.write,
1164
+ frame: this.arena.frameBytes > 0,
1165
+ slot: true,
1166
+ window,
1167
+ stop: Boolean(this.#stall),
1168
+ readWindows: order ? 2 : 0,
1169
+ readCount: count,
1170
+ exemptFirst: order === 'exempt',
1171
+ readSummary: this.arena.ssize
1172
+ });
1173
+ const module = new WebAssembly.Module(Uint8Array.from(lowered));
1174
+ this.#variants.set(key, module);
1175
+ for (const link of this.#links)
1176
+ link.port.postMessage({ install: module, key });
1177
+ return key;
1178
+ }
1179
+ // newest stamp first across every iteration being rolled back
1180
+ #rollback(logs, first, outcomes, from) {
406
1181
  const entries = [];
407
1182
  for (let k = from; k < outcomes.length; k++) {
408
1183
  const o = outcomes[k];
409
- const base = A.logs + (o.index - first) * A.logBytes;
1184
+ const base = logs.base + (o.index - first) * logs.bytes;
410
1185
  for (let e = 0; e < o.entries; e++) {
411
1186
  const at = base + e * iterationEntryBytes;
412
1187
  entries.push({