@gmitch215/folio 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -460
- package/dist/boot.d.ts +1 -0
- package/dist/boot.js +1 -0
- package/dist/browser/index.d.ts +73 -0
- package/dist/browser/index.js +277 -0
- package/dist/browser.d.ts +1 -68
- package/dist/browser.js +1 -274
- package/dist/continuation.d.ts +1 -0
- package/dist/continuation.js +1 -0
- package/dist/{compiler.d.ts → execution/compiler.d.ts} +1 -1
- package/dist/{compiler.js → execution/compiler.js} +5 -12
- package/dist/{coordinator.d.ts → execution/coordinator.d.ts} +1 -1
- package/dist/{coordinator.js → execution/coordinator.js} +55 -8
- package/dist/{extract.d.ts → execution/extract.d.ts} +22 -13
- package/dist/{extract.js → execution/extract.js} +137 -10
- package/dist/execution/fold.d.ts +44 -0
- package/dist/execution/fold.js +105 -0
- package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
- package/dist/execution/runs.d.ts +44 -0
- package/dist/execution/runs.js +182 -0
- package/dist/{transaction.d.ts → execution/transaction.d.ts} +10 -0
- package/dist/execution/types.d.ts +221 -0
- package/dist/folds/affine-state.d.ts +142 -0
- package/dist/folds/affine-state.js +737 -0
- package/dist/folds/affine.d.ts +148 -0
- package/dist/folds/affine.js +562 -0
- package/dist/folds/boundaries.d.ts +48 -0
- package/dist/folds/boundaries.js +119 -0
- package/dist/folds/certified.d.ts +55 -0
- package/dist/folds/certified.js +178 -0
- package/dist/folds/certify.d.ts +87 -0
- package/dist/folds/certify.js +2611 -0
- package/dist/footprints/memo.d.ts +74 -0
- package/dist/footprints/memo.js +256 -0
- package/dist/footprints/ranges.d.ts +78 -0
- package/dist/footprints/ranges.js +263 -0
- package/dist/footprints/read-scan.d.ts +18 -0
- package/dist/footprints/read-scan.js +94 -0
- package/dist/footprints/read-windows.d.ts +77 -0
- package/dist/footprints/read-windows.js +245 -0
- package/dist/index.d.ts +16 -4
- package/dist/index.js +14 -2
- package/dist/iteration/admission.d.ts +149 -0
- package/dist/iteration/admission.js +201 -0
- package/dist/iteration/index.d.ts +239 -0
- package/dist/iteration/index.js +1210 -0
- package/dist/iteration/inline.d.ts +182 -0
- package/dist/{inline.js → iteration/inline.js} +277 -21
- package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +16 -3
- package/dist/{iteration-owner.js → iteration/owner.js} +6 -5
- package/dist/iteration/worker.js +216 -0
- package/dist/{managed.d.ts → managed/index.d.ts} +75 -3
- package/dist/managed/index.js +817 -0
- package/dist/managed/outbox.d.ts +128 -0
- package/dist/managed/outbox.js +156 -0
- package/dist/managed/pool.d.ts +221 -0
- package/dist/managed/pool.js +310 -0
- package/dist/managed/tasks.d.ts +154 -0
- package/dist/managed/tasks.js +183 -0
- package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
- package/dist/{bake.js → memory/bake.js} +9 -7
- package/dist/memory/continuation.d.ts +141 -0
- package/dist/memory/continuation.js +495 -0
- package/dist/memory/elastic-peer.d.ts +20 -0
- package/dist/memory/elastic-peer.js +39 -0
- package/dist/memory/elastic-sql.d.ts +11 -0
- package/dist/memory/elastic-sql.js +35 -0
- package/dist/memory/elastic.d.ts +130 -0
- package/dist/memory/elastic.js +475 -0
- package/dist/memory/growth-governor.d.ts +16 -0
- package/dist/memory/growth-governor.js +42 -0
- package/dist/memory/imports.d.ts +10 -0
- package/dist/memory/imports.js +89 -0
- package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +61 -1
- package/dist/{iteration-layout.js → memory/iteration-layout.js} +54 -3
- package/dist/memory/lease.d.ts +45 -0
- package/dist/memory/lease.js +274 -0
- package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
- package/dist/memory.d.ts +5 -10
- package/dist/memory.js +5 -89
- package/dist/{context.d.ts → node/context.d.ts} +17 -3
- package/dist/{context.js → node/context.js} +60 -14
- package/dist/{host.d.ts → node/host.d.ts} +1 -1
- package/dist/{host.js → node/host.js} +2 -2
- package/dist/{node.d.ts → node/index.d.ts} +46 -49
- package/dist/{node.js → node/index.js} +101 -26
- package/dist/{tasks.d.ts → node/tasks.d.ts} +16 -17
- package/dist/{tasks.js → node/tasks.js} +12 -11
- package/dist/node/worker.d.ts +1 -0
- package/dist/{worker.js → node/worker.js} +2 -2
- package/dist/ownership/index.d.ts +161 -0
- package/dist/ownership/index.js +6565 -0
- package/dist/ownership/redirect.d.ts +30 -0
- package/dist/ownership/redirect.js +179 -0
- package/dist/ownership/slices.d.ts +44 -0
- package/dist/ownership/slices.js +72 -0
- package/dist/{frames.d.ts → remote/frames.d.ts} +6 -2
- package/dist/remote/frames.js +306 -0
- package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
- package/dist/{remote.js → remote/index.js} +7 -2
- package/dist/routing/index.d.ts +203 -0
- package/dist/routing/index.js +671 -0
- package/dist/routing/worker.d.ts +1 -0
- package/dist/routing/worker.js +4 -0
- package/dist/slices/index.d.ts +126 -0
- package/dist/slices/index.js +441 -0
- package/dist/slices/worker.d.ts +1 -0
- package/dist/slices/worker.js +38 -0
- package/dist/workers.d.ts +5 -0
- package/dist/workers.js +5 -0
- package/package.json +32 -46
- package/dist/frames.js +0 -159
- package/dist/inline.d.ts +0 -68
- package/dist/iteration-admission.d.ts +0 -76
- package/dist/iteration-admission.js +0 -72
- package/dist/iteration-worker.js +0 -150
- package/dist/iteration.d.ts +0 -163
- package/dist/iteration.js +0 -435
- package/dist/managed.js +0 -421
- /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
- /package/dist/{browser-worker.js → browser/worker.js} +0 -0
- /package/dist/{guards.js → execution/guards.js} +0 -0
- /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
- /package/dist/{import-order.js → execution/import-order.js} +0 -0
- /package/dist/{transaction.js → execution/transaction.js} +0 -0
- /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
- /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
- /package/dist/{pages.js → memory/pages.js} +0 -0
- /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
- /package/dist/{values.js → remote/values.js} +0 -0
|
@@ -0,0 +1,1210 @@
|
|
|
1
|
+
import { availableParallelism } from 'node:os';
|
|
2
|
+
import { isSharedArrayBuffer } from 'node:util/types';
|
|
3
|
+
import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
|
|
4
|
+
import { learnReadWindows, readWindowsClear, readWindowsPay } from "../footprints/read-windows.js";
|
|
5
|
+
import { iterationArena, iterationEntryBytes, iterationGranules, iterationShadowCopies, iterationWindowCopy } from "../memory/iteration-layout.js";
|
|
6
|
+
import { admissionSeam, batchBound, probeEstimate, projectBatch, refineEstimate } from "./admission.js";
|
|
7
|
+
import { inlineGlobals, lowerInline } from "./inline.js";
|
|
8
|
+
export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from "../memory/iteration-layout.js";
|
|
9
|
+
const newReport = (workers) => ({
|
|
10
|
+
workers,
|
|
11
|
+
regions: 0,
|
|
12
|
+
replayed: 0,
|
|
13
|
+
rolledBack: 0,
|
|
14
|
+
fallbacks: 0,
|
|
15
|
+
traps: 0,
|
|
16
|
+
exhausted: 0,
|
|
17
|
+
violations: 0,
|
|
18
|
+
stalls: 0,
|
|
19
|
+
stalledIterations: 0,
|
|
20
|
+
batches: 0,
|
|
21
|
+
failedBatches: 0,
|
|
22
|
+
undoEntries: 0,
|
|
23
|
+
maxLogEntries: 0,
|
|
24
|
+
logGrowths: 0,
|
|
25
|
+
retried: 0,
|
|
26
|
+
conflicts: { raw: 0, war: 0, waw: 0, frame: 0 },
|
|
27
|
+
dispatchMs: 0,
|
|
28
|
+
validationMs: 0,
|
|
29
|
+
rollbackMs: 0,
|
|
30
|
+
replayMs: 0,
|
|
31
|
+
workerRunMs: 0,
|
|
32
|
+
workerScanMs: 0,
|
|
33
|
+
workerMarkMs: 0,
|
|
34
|
+
workerScanWords: 0,
|
|
35
|
+
workerScanSet: 0,
|
|
36
|
+
serial: 0,
|
|
37
|
+
windowConflicts: 0
|
|
38
|
+
});
|
|
39
|
+
const writeToReadShift = Math.log2(iterationGranules.read / iterationGranules.write);
|
|
40
|
+
// sorted write granules against sorted read runs
|
|
41
|
+
function hitsReads(writes, runs) {
|
|
42
|
+
let p = 0;
|
|
43
|
+
for (let i = 0; i < writes.length; i++) {
|
|
44
|
+
const g = writes[i] >> writeToReadShift;
|
|
45
|
+
while (p < runs.length && runs[p] + runs[p + 1] <= g)
|
|
46
|
+
p += 2;
|
|
47
|
+
if (p >= runs.length)
|
|
48
|
+
return false;
|
|
49
|
+
if (runs[p] <= g)
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
function hitsWrites(a, b) {
|
|
55
|
+
let i = 0;
|
|
56
|
+
let j = 0;
|
|
57
|
+
while (i < a.length && j < b.length) {
|
|
58
|
+
if (a[i] === b[j])
|
|
59
|
+
return true;
|
|
60
|
+
if (a[i] < b[j])
|
|
61
|
+
i++;
|
|
62
|
+
else
|
|
63
|
+
j++;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
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
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Index of the first outcome that cannot keep its writes, or -1. Writes land in place, so every
|
|
216
|
+
* ordered pair is checked three ways: RAW marks the reader, WAR the earlier reader, WAW the earlier
|
|
217
|
+
* writer. A fourth check covers the frame, which each iteration owns as a private copy: an
|
|
218
|
+
* iteration fails when it read a frame byte before writing it that an earlier iteration wrote, and
|
|
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.
|
|
224
|
+
*/
|
|
225
|
+
export function iterationVerdict(outcomes, skip = [], windowWords = 0) {
|
|
226
|
+
let frameFirst = outcomes.length;
|
|
227
|
+
let firstFailure = outcomes.length;
|
|
228
|
+
outcomes.forEach((o, k) => {
|
|
229
|
+
if (o.status)
|
|
230
|
+
firstFailure = Math.min(firstFailure, k);
|
|
231
|
+
});
|
|
232
|
+
let first = firstFailure;
|
|
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;
|
|
242
|
+
if (!skip.includes('frame')) {
|
|
243
|
+
// the frame bytes written by the iterations before k, against the bytes k read unwritten
|
|
244
|
+
let union;
|
|
245
|
+
outcomes.forEach((o, k) => {
|
|
246
|
+
const exposed = o.frameExposed;
|
|
247
|
+
if (union && exposed?.length && exposed.some((word, w) => word & (union[w] ?? 0))) {
|
|
248
|
+
conflicts.frame++;
|
|
249
|
+
first = Math.min(first, k);
|
|
250
|
+
frameFirst = Math.min(frameFirst, k);
|
|
251
|
+
if (windowWords &&
|
|
252
|
+
exposed.some((word, w) => w < windowWords && word & (union[w] ?? 0)))
|
|
253
|
+
windowed++;
|
|
254
|
+
}
|
|
255
|
+
const written = o.frameWritten;
|
|
256
|
+
if (!written?.length)
|
|
257
|
+
return;
|
|
258
|
+
union ??= new Uint32Array(written.length);
|
|
259
|
+
written.forEach((word, w) => (union[w] |= word));
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
const none = outcomes.length;
|
|
263
|
+
return {
|
|
264
|
+
first: first === none ? -1 : first,
|
|
265
|
+
firstFailure: firstFailure === none ? -1 : firstFailure,
|
|
266
|
+
frameFirst: frameFirst === none ? -1 : frameFirst,
|
|
267
|
+
conflicts,
|
|
268
|
+
...(windowWords ? { window: windowed } : {})
|
|
269
|
+
};
|
|
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;
|
|
319
|
+
/**
|
|
320
|
+
* Runs the loop of one owner call on worker threads. Each iteration gets a private stack slot and
|
|
321
|
+
* tracks its reads and writes inline. The owner validates a batch in order, rolls back the first
|
|
322
|
+
* failing iteration and every later one from the undo logs, and replays them through `replay`.
|
|
323
|
+
* The arena belongs to the pool until `close`.
|
|
324
|
+
*
|
|
325
|
+
* Each iteration runs on a private copy of the owner frame, taken from the owner frame when its
|
|
326
|
+
* batch is dispatched. The lowered module tracks the frame: a written bit per frame byte, and an
|
|
327
|
+
* exposed bit per 32-byte frame granule that the iteration read before it wrote the byte. An
|
|
328
|
+
* iteration fails validation, like a RAW pair, when it has an exposed granule that an earlier
|
|
329
|
+
* iteration of the same batch wrote (`conflicts.frame`); it and every later one in the batch roll
|
|
330
|
+
* back and replay. After a batch validates, each kept
|
|
331
|
+
* iteration's written frame bytes are copied into the owner frame in order, so the next batch
|
|
332
|
+
* starts from the serial frame and a replay runs on it. The guarantee: a read of an owner frame
|
|
333
|
+
* byte that the same iteration has not written yet, with a write by an earlier iteration of the
|
|
334
|
+
* batch to that byte, is detected, and an earlier batch's writes are seen through the copy.
|
|
335
|
+
* Excluded: a read of stack below the frame (callee frames, indeterminate before the callee writes
|
|
336
|
+
* them) is not tracked, and imported host functions that touch memory are not seen. The shadow
|
|
337
|
+
* is byte-exact for scalar accesses and ranges; a conservative read would only add reports.
|
|
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
|
+
*
|
|
345
|
+
* With `admit`, iteration 0 runs first on the owner and the batches cover the rest. Dispatch
|
|
346
|
+
* stops after a batch that exhausted an undo log, had a frame conflict, replayed more than half of
|
|
347
|
+
* its iterations, or (with `loses` and `collapses`) two batches in a row did not beat the serial
|
|
348
|
+
* time of their iterations or one took far longer than it; the rest of the loop runs through
|
|
349
|
+
* `replay` and `report.stopped` names the reason. Once an iteration fails, the workers start no
|
|
350
|
+
* further iteration of that batch, because it and every later one replay anyway.
|
|
351
|
+
*/
|
|
352
|
+
export class IterationPool {
|
|
353
|
+
arena;
|
|
354
|
+
width;
|
|
355
|
+
#report;
|
|
356
|
+
#memory;
|
|
357
|
+
#links = [];
|
|
358
|
+
#control = new Int32Array(new SharedArrayBuffer(4));
|
|
359
|
+
#u8;
|
|
360
|
+
#u32;
|
|
361
|
+
#closed = false;
|
|
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;
|
|
381
|
+
this.#memory = memory;
|
|
382
|
+
this.arena = arena;
|
|
383
|
+
this.width = width;
|
|
384
|
+
this.#ceiling = ceiling;
|
|
385
|
+
this.#memoryBytes = arena.memoryBytes;
|
|
386
|
+
this.#report = newReport(0);
|
|
387
|
+
this.#u8 = new Uint8Array(memory.buffer);
|
|
388
|
+
this.#u32 = new Uint32Array(memory.buffer);
|
|
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
|
+
}
|
|
394
|
+
/** The report of the last run, also after a run that threw. */
|
|
395
|
+
get report() {
|
|
396
|
+
return this.#report;
|
|
397
|
+
}
|
|
398
|
+
/** Lowers the route's worker module inline and starts `width` workers over `memory`. */
|
|
399
|
+
static async open(route, memory, options) {
|
|
400
|
+
if (!route.eligible || !route.module || !route.iterate)
|
|
401
|
+
throw new TypeError('iteration route is not eligible');
|
|
402
|
+
const memoryBytes = memory.buffer.byteLength;
|
|
403
|
+
if (!isSharedArrayBuffer(memory.buffer))
|
|
404
|
+
throw new TypeError('iteration pool requires shared memory');
|
|
405
|
+
const width = options.width ?? Math.min(4, availableParallelism());
|
|
406
|
+
if (!Number.isInteger(width) || width < 1 || width > 64)
|
|
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');
|
|
419
|
+
const frameSize = route.frame?.size ?? 0;
|
|
420
|
+
const arena = iterationArena(options.arenaBase, memoryBytes, {
|
|
421
|
+
...options,
|
|
422
|
+
frameBytes: frameSize
|
|
423
|
+
});
|
|
424
|
+
if (arena.base + arena.bytes > arena.memoryBytes)
|
|
425
|
+
throw new RangeError('arena does not fit in memory');
|
|
426
|
+
if (frameSize >= arena.slotBytes)
|
|
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
|
+
}
|
|
433
|
+
const lowered = lowerInline(route.module, {
|
|
434
|
+
readGranule: iterationGranules.read,
|
|
435
|
+
writeGranule: iterationGranules.write,
|
|
436
|
+
frame: frameSize > 0,
|
|
437
|
+
slot: true,
|
|
438
|
+
stop: Boolean(stall),
|
|
439
|
+
readSummary: arena.ssize
|
|
440
|
+
});
|
|
441
|
+
const module = new WebAssembly.Module(Uint8Array.from(lowered));
|
|
442
|
+
const pool = new IterationPool(route, memory, arena, width, options.logCeiling ?? arena.logCapacity, Boolean(options.readWindows), stall);
|
|
443
|
+
pool.#u8.fill(0, arena.stamp, arena.stamp + 64);
|
|
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);
|
|
447
|
+
const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';
|
|
448
|
+
try {
|
|
449
|
+
await Promise.all(Array.from({ length: width }, () => {
|
|
450
|
+
const channel = new MessageChannel();
|
|
451
|
+
const signal = new SharedArrayBuffer(4);
|
|
452
|
+
const worker = new Worker(new URL(`./worker.${extension}`, import.meta.url), {
|
|
453
|
+
workerData: {
|
|
454
|
+
module,
|
|
455
|
+
memory,
|
|
456
|
+
arena,
|
|
457
|
+
globals: inlineGlobals,
|
|
458
|
+
iterate: route.iterate,
|
|
459
|
+
locals: route.locals,
|
|
460
|
+
frameSize,
|
|
461
|
+
ownership: route.ownership,
|
|
462
|
+
port: channel.port2,
|
|
463
|
+
signal,
|
|
464
|
+
control: pool.#control.buffer
|
|
465
|
+
},
|
|
466
|
+
transferList: [channel.port2]
|
|
467
|
+
});
|
|
468
|
+
pool.#links.push({
|
|
469
|
+
worker,
|
|
470
|
+
port: channel.port1,
|
|
471
|
+
signal: new Int32Array(signal)
|
|
472
|
+
});
|
|
473
|
+
return new Promise((resolve, reject) => {
|
|
474
|
+
worker.once('message', () => resolve());
|
|
475
|
+
worker.once('error', reject);
|
|
476
|
+
});
|
|
477
|
+
}));
|
|
478
|
+
}
|
|
479
|
+
catch (error) {
|
|
480
|
+
await pool.close();
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
return pool;
|
|
484
|
+
}
|
|
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) {
|
|
488
|
+
for (;;) {
|
|
489
|
+
const seen = Atomics.load(link.signal, 0);
|
|
490
|
+
const message = receiveMessageOnPort(link.port);
|
|
491
|
+
if (message)
|
|
492
|
+
return message.message;
|
|
493
|
+
const wait = deadline - performance.now();
|
|
494
|
+
if (wait <= 0)
|
|
495
|
+
return;
|
|
496
|
+
Atomics.wait(link.signal, 0, seen, wait);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
/** Runs the loop to completion with ordered validation. Blocks the calling thread. */
|
|
500
|
+
run(job) {
|
|
501
|
+
if (this.#closed)
|
|
502
|
+
throw new Error('iteration pool is closed');
|
|
503
|
+
if (this.#broken)
|
|
504
|
+
throw new Error(this.#broken);
|
|
505
|
+
if (this.#memory.buffer.byteLength !== this.#memoryBytes)
|
|
506
|
+
throw new Error('memory changed size while the iteration pool was open');
|
|
507
|
+
if (!Number.isSafeInteger(job.trip) || job.trip < 0)
|
|
508
|
+
throw new RangeError('invalid trip count');
|
|
509
|
+
const A = this.arena;
|
|
510
|
+
const report = (this.#report = newReport(Math.min(this.width, Math.max(job.trip, 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 };
|
|
526
|
+
let from = 0;
|
|
527
|
+
if (job.admit && job.trip > 0) {
|
|
528
|
+
// iteration 0 is the serial program's own first iteration, so its writes stay
|
|
529
|
+
const t = performance.now();
|
|
530
|
+
report.serial = 1;
|
|
531
|
+
job.replay(0);
|
|
532
|
+
const plainMs = performance.now() - t;
|
|
533
|
+
estimate = { estimateMs: plainMs };
|
|
534
|
+
from = 1;
|
|
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
|
+
}
|
|
546
|
+
if (!report.admission.admitted) {
|
|
547
|
+
const probed = this.#probe(job, report, plainMs);
|
|
548
|
+
if (probed.at >= job.trip) {
|
|
549
|
+
report.stopped = 'no-admission';
|
|
550
|
+
return report;
|
|
551
|
+
}
|
|
552
|
+
from = probed.at;
|
|
553
|
+
estimate = { estimateMs: probed.estimate };
|
|
554
|
+
report.admission.admitted = true;
|
|
555
|
+
report.admission.readmittedAt = from;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
let stopped = false;
|
|
559
|
+
let slow = 0;
|
|
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;
|
|
615
|
+
if (stopped) {
|
|
616
|
+
const t = performance.now();
|
|
617
|
+
try {
|
|
618
|
+
for (let k = 0; k < count; k++) {
|
|
619
|
+
report.serial++;
|
|
620
|
+
job.replay(first + k);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
finally {
|
|
624
|
+
report.replayMs += performance.now() - t;
|
|
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;
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
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);
|
|
659
|
+
const t0 = performance.now();
|
|
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++;
|
|
664
|
+
const t1 = performance.now();
|
|
665
|
+
report.dispatchMs += t1 - t0;
|
|
666
|
+
for (const o of outcomes) {
|
|
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);
|
|
672
|
+
if (o.status === 1)
|
|
673
|
+
report.traps++;
|
|
674
|
+
if (o.status === 2)
|
|
675
|
+
report.exhausted++;
|
|
676
|
+
if (o.touched !== undefined && o.touched >= 0)
|
|
677
|
+
report.violations++;
|
|
678
|
+
}
|
|
679
|
+
const v = iterationVerdict(outcomes, job.skip, ran ? Math.ceil((ran.end - ran.low) / 32) : 0);
|
|
680
|
+
report.windowConflicts += v.window ?? 0;
|
|
681
|
+
report.conflicts.raw += v.conflicts.raw;
|
|
682
|
+
report.conflicts.war += v.conflicts.war;
|
|
683
|
+
report.conflicts.waw += v.conflicts.waw;
|
|
684
|
+
report.conflicts.frame += v.conflicts.frame;
|
|
685
|
+
const t2 = performance.now();
|
|
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;
|
|
805
|
+
let replays = 0;
|
|
806
|
+
if (v.first < 0)
|
|
807
|
+
this.#commitFrame(job, outcomes, count, ran);
|
|
808
|
+
else {
|
|
809
|
+
replays = count - v.first;
|
|
810
|
+
report.failedBatches++;
|
|
811
|
+
if (v.firstFailure === v.first)
|
|
812
|
+
report.fallbacks++;
|
|
813
|
+
this.#rollback(logs, first, outcomes, v.first);
|
|
814
|
+
report.rolledBack += outcomes.length - v.first;
|
|
815
|
+
this.#commitFrame(job, outcomes, v.first, ran);
|
|
816
|
+
const t3 = performance.now();
|
|
817
|
+
report.rollbackMs += t3 - t2;
|
|
818
|
+
try {
|
|
819
|
+
for (let k = v.first; k < count; k++) {
|
|
820
|
+
if (k < outcomes.length)
|
|
821
|
+
report.replayed++;
|
|
822
|
+
else
|
|
823
|
+
report.serial++;
|
|
824
|
+
job.replay(first + k);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
finally {
|
|
828
|
+
report.replayMs += performance.now() - t3;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const wallMs = performance.now() - t0;
|
|
832
|
+
const tracked = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
|
|
833
|
+
if (job.admit) {
|
|
834
|
+
// the workers' own time per completed iteration, scaled to serial time
|
|
835
|
+
estimate = refineEstimate(estimate, tracked, Boolean(usedRw));
|
|
836
|
+
}
|
|
837
|
+
const serialMs = count * perMs();
|
|
838
|
+
if (report.admission && admissionSeam.trace) {
|
|
839
|
+
(report.admission.trace ??= []).push({
|
|
840
|
+
first,
|
|
841
|
+
count,
|
|
842
|
+
windows: Boolean(usedRw),
|
|
843
|
+
trackedMeanMs: tracked.reduce((a, b) => a + b, 0) / (tracked.length || 1),
|
|
844
|
+
kappa: usedRw ? estimate.kappaWindows : estimate.kappa,
|
|
845
|
+
estimateMs: estimate.estimateMs,
|
|
846
|
+
wallMs,
|
|
847
|
+
serialMs
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
if (report.admission) {
|
|
851
|
+
report.admission.batchWallMs = wallMs;
|
|
852
|
+
report.admission.batchSerialMs = serialMs;
|
|
853
|
+
report.admission.estimateMs = estimate.estimateMs;
|
|
854
|
+
}
|
|
855
|
+
// the first batch also pays for waking the workers, so a batch that is merely slow is not a
|
|
856
|
+
// verdict until a second one confirms it
|
|
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
|
+
if (windowsNext &&
|
|
864
|
+
job.admit &&
|
|
865
|
+
job.hopeless &&
|
|
866
|
+
job.unproven?.(batchBound(perMs(), tracked, this.width)))
|
|
867
|
+
prove = true;
|
|
868
|
+
let hopeless = !exempt &&
|
|
869
|
+
!stalled &&
|
|
870
|
+
!windowsNext &&
|
|
871
|
+
Boolean(job.admit) &&
|
|
872
|
+
job.hopeless?.(batchBound(perMs(), tracked, this.width)) === true;
|
|
873
|
+
// the short batch on new read windows prices the next full one before it runs
|
|
874
|
+
if (short && !hopeless && !exempt && !stalled && job.admit && job.loses) {
|
|
875
|
+
const next = projectBatch(wallMs, tracked, perMs(), Math.min(logs.inFlight, job.trip - first - count), this.width);
|
|
876
|
+
hopeless = next !== undefined && job.loses(next.wallMs, next.serialMs);
|
|
877
|
+
}
|
|
878
|
+
slow = timed && job.admit && job.loses?.(wallMs, serialMs) ? slow + 1 : 0;
|
|
879
|
+
if (timed)
|
|
880
|
+
lastTimed = { wallMs, count };
|
|
881
|
+
const confirm = report.admission?.probe ? 1 : 2;
|
|
882
|
+
const collapsed = timed && job.admit && job.collapses?.(wallMs, serialMs);
|
|
883
|
+
const named = stalled
|
|
884
|
+
? 'stalled'
|
|
885
|
+
: outcomes.some((o) => o.status === 2)
|
|
886
|
+
? 'log-exhausted'
|
|
887
|
+
: v.frameFirst >= 0
|
|
888
|
+
? 'frame-carried dependence'
|
|
889
|
+
: replays * 2 > count
|
|
890
|
+
? 'dependency'
|
|
891
|
+
: (slow >= confirm || collapsed || hopeless) && first + count < job.trip
|
|
892
|
+
? 'no-admission'
|
|
893
|
+
: undefined;
|
|
894
|
+
if (learning)
|
|
895
|
+
pendingStop = named;
|
|
896
|
+
let stop = stalled ? 'stalled' : exempt ? undefined : named;
|
|
897
|
+
if (probing) {
|
|
898
|
+
probes.push(...outcomes);
|
|
899
|
+
if (--probeLeft === 0) {
|
|
900
|
+
const found = probes.length === 2 && probes.every((o) => o.status === 0)
|
|
901
|
+
? discoverWindow(probes, A.windowBytes)
|
|
902
|
+
: { reason: 'a probe iteration did not complete' };
|
|
903
|
+
const why = found.window
|
|
904
|
+
? this.#refuseWindow(found.window, job.frameBase)
|
|
905
|
+
: found.reason;
|
|
906
|
+
if (why || !found.window) {
|
|
907
|
+
report.windowRefused = why;
|
|
908
|
+
stop = pendingStop;
|
|
909
|
+
}
|
|
910
|
+
else {
|
|
911
|
+
window = found.window;
|
|
912
|
+
report.window = { ...window, source: 'discovered', batches: 0 };
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
if (stop) {
|
|
917
|
+
report.stopped ??= stop;
|
|
918
|
+
if (stop === 'no-admission')
|
|
919
|
+
costStop = true;
|
|
920
|
+
if (stop === 'no-admission' && report.admission?.probe)
|
|
921
|
+
report.admission.probeLost = true;
|
|
922
|
+
stopped = true;
|
|
923
|
+
}
|
|
924
|
+
first += count;
|
|
925
|
+
}
|
|
926
|
+
if (probeLeft > 0 && pendingStop)
|
|
927
|
+
report.stopped ??= pendingStop;
|
|
928
|
+
if (job.admit && report.batches)
|
|
929
|
+
this.#cold = costStop;
|
|
930
|
+
return report;
|
|
931
|
+
}
|
|
932
|
+
// replays the rest of a refused loop in blocks of 1, 2, 4 up to a batch, timing each block. The
|
|
933
|
+
// estimate is the lower of the last two blocks so one slow block is not a verdict; when
|
|
934
|
+
// `reconsider` says the remaining iterations pay, dispatch starts there. Returns the index
|
|
935
|
+
// reached and the estimate; the index is the trip count when nothing was dispatchable.
|
|
936
|
+
#probe(job, report, plainMs) {
|
|
937
|
+
let block = 1;
|
|
938
|
+
let last = plainMs;
|
|
939
|
+
let estimate = plainMs;
|
|
940
|
+
const means = [plainMs];
|
|
941
|
+
let probed = 0;
|
|
942
|
+
let spent = 0;
|
|
943
|
+
let k = 1;
|
|
944
|
+
while (k < job.trip) {
|
|
945
|
+
const size = job.reconsider ? Math.min(block, job.trip - k) : job.trip - k;
|
|
946
|
+
const t = performance.now();
|
|
947
|
+
for (let i = 0; i < size; i++) {
|
|
948
|
+
report.serial++;
|
|
949
|
+
job.replay(k + i);
|
|
950
|
+
}
|
|
951
|
+
const elapsed = performance.now() - t;
|
|
952
|
+
const per = elapsed / size;
|
|
953
|
+
k += size;
|
|
954
|
+
probed += size;
|
|
955
|
+
spent += elapsed;
|
|
956
|
+
means.push(per);
|
|
957
|
+
estimate = probeEstimate(admissionSeam.estimator, last, per, means, spent / probed);
|
|
958
|
+
last = per;
|
|
959
|
+
block = Math.min(block * 2, this.arena.batch);
|
|
960
|
+
if (report.admission)
|
|
961
|
+
report.admission.estimateMs = estimate;
|
|
962
|
+
if (k < job.trip && job.reconsider?.(estimate, job.trip - k))
|
|
963
|
+
return { at: k, estimate };
|
|
964
|
+
}
|
|
965
|
+
return { at: k, estimate };
|
|
966
|
+
}
|
|
967
|
+
// pages above the arena for logs of `logCeiling` entries, one per iteration in flight. The undo
|
|
968
|
+
// code writes them without marking, so no bitmap has to cover them and the program never names
|
|
969
|
+
// them. Undefined when the ceiling is not above the default, the memory changed size under the
|
|
970
|
+
// pool, or the memory cannot grow (its declared maximum). The pages stay for later calls.
|
|
971
|
+
#growLog() {
|
|
972
|
+
if (this.#grown)
|
|
973
|
+
return this.#grown;
|
|
974
|
+
const A = this.arena;
|
|
975
|
+
if (this.#ceiling <= A.logCapacity)
|
|
976
|
+
return;
|
|
977
|
+
if (this.#memory.buffer.byteLength !== this.#memoryBytes)
|
|
978
|
+
return;
|
|
979
|
+
const bytes = Math.ceil((this.#ceiling * iterationEntryBytes) / 64) * 64;
|
|
980
|
+
const inFlight = Math.min(2 * this.width, A.batch);
|
|
981
|
+
const pages = Math.ceil((inFlight * bytes) / PAGE);
|
|
982
|
+
try {
|
|
983
|
+
this.#memory.grow(pages);
|
|
984
|
+
}
|
|
985
|
+
catch (error) {
|
|
986
|
+
if (error instanceof RangeError)
|
|
987
|
+
return;
|
|
988
|
+
throw error;
|
|
989
|
+
}
|
|
990
|
+
const base = this.#memoryBytes;
|
|
991
|
+
this.#memoryBytes += pages * PAGE;
|
|
992
|
+
this.#u8 = new Uint8Array(this.#memory.buffer);
|
|
993
|
+
this.#u32 = new Uint32Array(this.#memory.buffer);
|
|
994
|
+
return (this.#grown = { base, capacity: this.#ceiling, bytes, inFlight });
|
|
995
|
+
}
|
|
996
|
+
#dispatch(first, count, job, report, logs, estimateMs, window, readWindows, variant = '') {
|
|
997
|
+
this.#control[0] = 0;
|
|
998
|
+
Atomics.store(this.#u32, this.arena.stamp / 4, 0);
|
|
999
|
+
Atomics.store(this.#u32, this.arena.stamp / 4 + 1, 0);
|
|
1000
|
+
this.#stalled = false;
|
|
1001
|
+
const used = this.#links.slice(0, Math.min(this.width, count));
|
|
1002
|
+
const message = {
|
|
1003
|
+
first,
|
|
1004
|
+
count,
|
|
1005
|
+
entry: job.entry,
|
|
1006
|
+
frameBase: job.frameBase,
|
|
1007
|
+
reverse: job.schedule === 'reverse',
|
|
1008
|
+
logs,
|
|
1009
|
+
memoryBytes: this.#memoryBytes,
|
|
1010
|
+
window,
|
|
1011
|
+
readWindows,
|
|
1012
|
+
variant
|
|
1013
|
+
};
|
|
1014
|
+
for (const link of used)
|
|
1015
|
+
link.port.postMessage(message);
|
|
1016
|
+
const outcomes = [];
|
|
1017
|
+
let failure;
|
|
1018
|
+
const stall = this.#stall;
|
|
1019
|
+
// the wait covers the iterations one worker runs; the stop word gets the same time to take hold
|
|
1020
|
+
const limit = stall
|
|
1021
|
+
? stall.floorMs + stall.factor * Math.ceil(count / used.length) * estimateMs
|
|
1022
|
+
: Infinity;
|
|
1023
|
+
let deadline = stall ? performance.now() + limit : Infinity;
|
|
1024
|
+
for (const link of used) {
|
|
1025
|
+
let reply = this.#join(link, deadline);
|
|
1026
|
+
if (!reply && !this.#stalled) {
|
|
1027
|
+
this.#stalled = true;
|
|
1028
|
+
Atomics.store(this.#control, 0, 1 << 30);
|
|
1029
|
+
Atomics.store(this.#u32, this.arena.stamp / 4 + 1, 1);
|
|
1030
|
+
deadline = performance.now() + limit;
|
|
1031
|
+
reply = this.#join(link, deadline);
|
|
1032
|
+
}
|
|
1033
|
+
if (!reply) {
|
|
1034
|
+
// a worker that polls no stop word is past help, and memory may be changing under the owner
|
|
1035
|
+
this.#broken = `iteration worker did not stop within ${Math.round(limit)} ms of the stall word`;
|
|
1036
|
+
for (const l of this.#links)
|
|
1037
|
+
l.worker.terminate().catch(() => { });
|
|
1038
|
+
throw new Error(this.#broken);
|
|
1039
|
+
}
|
|
1040
|
+
if (reply.error !== undefined)
|
|
1041
|
+
failure ??= reply.error;
|
|
1042
|
+
else {
|
|
1043
|
+
outcomes.push(...reply.done);
|
|
1044
|
+
report.workerRunMs += reply.runMs;
|
|
1045
|
+
report.workerScanMs += reply.scanMs;
|
|
1046
|
+
report.workerMarkMs += reply.markMs;
|
|
1047
|
+
report.workerScanWords += reply.scanWords;
|
|
1048
|
+
report.workerScanSet += reply.scanSet;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (failure !== undefined)
|
|
1052
|
+
throw new Error(`iteration worker failed: ${failure}`);
|
|
1053
|
+
return outcomes.sort((a, b) => a.index - b.index);
|
|
1054
|
+
}
|
|
1055
|
+
// the written bytes of the first `kept` iterations of a batch, in order: frame bytes into the owner
|
|
1056
|
+
// frame, and window bytes into the window, so a later iteration's write wins as it does serially
|
|
1057
|
+
#commitFrame(job, outcomes, kept, window) {
|
|
1058
|
+
const A = this.arena;
|
|
1059
|
+
const owned = this.#route.ownership;
|
|
1060
|
+
if (owned && kept > 0) {
|
|
1061
|
+
// the last kept iteration wrote every copy-out byte, so its copy is the serial window
|
|
1062
|
+
const last = outcomes[kept - 1];
|
|
1063
|
+
const top = A.slots + (last.index - outcomes[0].index + 1) * A.slotBytes;
|
|
1064
|
+
const { copies } = iterationShadowCopies(top, A.frameBytes, owned.windows);
|
|
1065
|
+
for (const [from, end] of owned.copyOut) {
|
|
1066
|
+
const i = owned.windows.findIndex((w) => from >= w.low && end <= w.end);
|
|
1067
|
+
const at = copies[i].copy - owned.windows[i].low;
|
|
1068
|
+
this.#u8.copyWithin(from, from + at, end + at);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
if (!A.frameBytes && !window)
|
|
1072
|
+
return;
|
|
1073
|
+
for (let k = 0; k < kept; k++) {
|
|
1074
|
+
const o = outcomes[k];
|
|
1075
|
+
const slot = o.index - outcomes[0].index;
|
|
1076
|
+
const top = A.slots + (slot + 1) * A.slotBytes;
|
|
1077
|
+
if (!window) {
|
|
1078
|
+
const frame = top - A.frameBytes;
|
|
1079
|
+
o.frameWritten.forEach((word, g) => {
|
|
1080
|
+
for (let b = 0; b < 32; b++)
|
|
1081
|
+
if ((word >>> b) & 1) {
|
|
1082
|
+
const at = 32 * g + b;
|
|
1083
|
+
this.#u8[job.frameBase + at] = this.#u8[frame + at];
|
|
1084
|
+
}
|
|
1085
|
+
});
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
const w = iterationWindowCopy(top, A.frameBytes, window);
|
|
1089
|
+
const bytes = window.end - window.low;
|
|
1090
|
+
o.frameWritten.forEach((word, g) => {
|
|
1091
|
+
for (let b = 0; b < 32; b++)
|
|
1092
|
+
if ((word >>> b) & 1) {
|
|
1093
|
+
const at = 32 * g + b;
|
|
1094
|
+
if (at < bytes)
|
|
1095
|
+
this.#u8[window.low + at] = this.#u8[w.copy + at];
|
|
1096
|
+
else if (at >= w.frameOffset)
|
|
1097
|
+
this.#u8[job.frameBase + at - w.frameOffset] = this.#u8[w.copy + at];
|
|
1098
|
+
}
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
// why a window cannot be used for this call, or undefined when it can
|
|
1103
|
+
#refuseWindow(window, frameBase) {
|
|
1104
|
+
const A = this.arena;
|
|
1105
|
+
const bytes = window.end - window.low;
|
|
1106
|
+
if (!A.windowBytes)
|
|
1107
|
+
return 'the arena reserves no window bytes';
|
|
1108
|
+
if (!Number.isSafeInteger(window.low) || !Number.isSafeInteger(window.end) || bytes <= 0)
|
|
1109
|
+
return 'invalid window';
|
|
1110
|
+
if (window.low % 64 || window.end % 64)
|
|
1111
|
+
return 'the window is not 64-byte aligned';
|
|
1112
|
+
if (bytes > A.windowBytes)
|
|
1113
|
+
return `the window of ${bytes} bytes is over ${A.windowBytes}`;
|
|
1114
|
+
if (window.end > this.#memoryBytes)
|
|
1115
|
+
return 'the window passes the end of memory';
|
|
1116
|
+
const overlap = this.#overlap(window, frameBase, 'the window');
|
|
1117
|
+
if (overlap)
|
|
1118
|
+
return overlap;
|
|
1119
|
+
if (A.slotBytes - A.frameBytes - bytes - 64 < windowStackBytes)
|
|
1120
|
+
return `the window leaves less than ${windowStackBytes} bytes of stack in a slot`;
|
|
1121
|
+
}
|
|
1122
|
+
// why the certified windows cannot be privatized for this call, or undefined when they can
|
|
1123
|
+
#refuseOwnership(plan, frameBase) {
|
|
1124
|
+
for (const w of plan.windows) {
|
|
1125
|
+
if (w.end > this.#memoryBytes)
|
|
1126
|
+
return 'a certified window passes the end of memory';
|
|
1127
|
+
const overlap = this.#overlap(w, frameBase, 'a certified window');
|
|
1128
|
+
if (overlap)
|
|
1129
|
+
return overlap;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
// the arena, the grown logs and the owner frame, in that order
|
|
1133
|
+
#overlap(window, frameBase, subject) {
|
|
1134
|
+
const A = this.arena;
|
|
1135
|
+
const meets = (low, end) => window.low < end && window.end > low;
|
|
1136
|
+
if (meets(A.base, A.base + A.bytes))
|
|
1137
|
+
return `${subject} overlaps the arena`;
|
|
1138
|
+
if (this.#grown &&
|
|
1139
|
+
meets(this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
|
|
1140
|
+
return `${subject} overlaps the grown logs`;
|
|
1141
|
+
if (A.frameBytes && meets(frameBase, frameBase + A.frameBytes))
|
|
1142
|
+
return `${subject} overlaps the owner frame`;
|
|
1143
|
+
}
|
|
1144
|
+
// address ranges a read window must stay out of: the arena and the grown logs
|
|
1145
|
+
#forbidden() {
|
|
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) {
|
|
1181
|
+
const entries = [];
|
|
1182
|
+
for (let k = from; k < outcomes.length; k++) {
|
|
1183
|
+
const o = outcomes[k];
|
|
1184
|
+
const base = logs.base + (o.index - first) * logs.bytes;
|
|
1185
|
+
for (let e = 0; e < o.entries; e++) {
|
|
1186
|
+
const at = base + e * iterationEntryBytes;
|
|
1187
|
+
entries.push({
|
|
1188
|
+
address: this.#u32[at / 4],
|
|
1189
|
+
stamp: this.#u32[at / 4 + 1],
|
|
1190
|
+
data: at + 8
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
entries.sort((a, b) => b.stamp - a.stamp);
|
|
1195
|
+
for (const e of entries)
|
|
1196
|
+
this.#u8.copyWithin(e.address, e.data, e.data + iterationGranules.write);
|
|
1197
|
+
}
|
|
1198
|
+
/** Stops the workers. Safe to call twice. */
|
|
1199
|
+
async close() {
|
|
1200
|
+
if (this.#closed)
|
|
1201
|
+
return;
|
|
1202
|
+
this.#closed = true;
|
|
1203
|
+
await Promise.all(this.#links.map((link) => link.worker.terminate()));
|
|
1204
|
+
for (const link of this.#links)
|
|
1205
|
+
link.port.close();
|
|
1206
|
+
}
|
|
1207
|
+
[Symbol.asyncDispose]() {
|
|
1208
|
+
return this.close();
|
|
1209
|
+
}
|
|
1210
|
+
}
|