@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,671 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import binaryen from 'binaryen';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { availableParallelism } from 'node:os';
|
|
13
|
+
import { Worker } from 'node:worker_threads';
|
|
14
|
+
import { foldCertified, installPrefill, reconstructCertified, shareCertified } from "../folds/certified.js";
|
|
15
|
+
import { certifyStream, CHECKER } from "../folds/certify.js";
|
|
16
|
+
import { iterationAdmissionConstants } from "../iteration/admission.js";
|
|
17
|
+
import { Folio } from "../node/index.js";
|
|
18
|
+
import { TaskPool } from "../node/tasks.js";
|
|
19
|
+
import { certifyOwnership, guardRecords, OWNERSHIP_CHECKER } from "../ownership/index.js";
|
|
20
|
+
import { OwnershipSlices } from "../ownership/slices.js";
|
|
21
|
+
import { decodeValues, encodeValues, sharedMemoryImport } from "../slices/index.js";
|
|
22
|
+
/** @since 1.1.0 */
|
|
23
|
+
export const ROUTER_VERSION = 'folio-router-2';
|
|
24
|
+
/** Every decision names one of these. The first four are routes taken, the rest are refusals. */
|
|
25
|
+
export const ROUTER_REASONS = [
|
|
26
|
+
'certified-summary',
|
|
27
|
+
'certified-window',
|
|
28
|
+
'explicit-runner',
|
|
29
|
+
'tracked-eligible',
|
|
30
|
+
'mode-serial',
|
|
31
|
+
'single-worker',
|
|
32
|
+
'below-floor',
|
|
33
|
+
'dispatch-lost',
|
|
34
|
+
'not-a-stream',
|
|
35
|
+
'stream-refused',
|
|
36
|
+
'no-route-in-mode',
|
|
37
|
+
'no-certificate',
|
|
38
|
+
'allocator-state',
|
|
39
|
+
'shared-state',
|
|
40
|
+
'unclassified-dependency',
|
|
41
|
+
'wild-store',
|
|
42
|
+
'layout-overlap',
|
|
43
|
+
'assumption-unasserted',
|
|
44
|
+
'tracked-ineligible',
|
|
45
|
+
'memory-not-imported'
|
|
46
|
+
];
|
|
47
|
+
/**
|
|
48
|
+
* The tracked floor is the admission constants of the iteration route (fitted on the blake3 sweep,
|
|
49
|
+
* `results/corpus/iteration-admission`). The window floor is the smallest serial time at which all
|
|
50
|
+
* five paired runs of `aes-cbc-decrypt-shared` at 8 workers beat serial by 1.25 (4 records, 0.82
|
|
51
|
+
* ms; 3 records at 0.69 ms did not). The summary length is the smallest size at which every paired
|
|
52
|
+
* run of two hand stream modules did (1 MiB; 256 KiB did not). One driver and two hand modules,
|
|
53
|
+
* Mac, loaded.
|
|
54
|
+
*/
|
|
55
|
+
export const routerConstants = {
|
|
56
|
+
trackedFloorMs: iterationAdmissionConstants.fixedMs * iterationAdmissionConstants.margin,
|
|
57
|
+
windowFloorMs: 0.8,
|
|
58
|
+
summaryMinBytes: 1 << 20
|
|
59
|
+
};
|
|
60
|
+
/** Records a first call runs serially to estimate the serial time of one record. */
|
|
61
|
+
const PROBE_RECORDS = 4;
|
|
62
|
+
/** The per-record serial estimate after a tracked call: the lower of it and that call's plain first iteration. @internal */
|
|
63
|
+
export const lowerEstimate = (current, plainMs) => plainMs !== undefined && plainMs > 0 && plainMs < current ? plainMs : current;
|
|
64
|
+
const sha = (data) => createHash('sha256').update(data).digest('hex');
|
|
65
|
+
/** The runtime a certificate was made on: a different engine or checker build is a different key. */
|
|
66
|
+
export const defaultBackend = () => `node-${process.version}-${process.arch}-binaryen-${createRequire(import.meta.url)('binaryen/package.json').version}`;
|
|
67
|
+
/**
|
|
68
|
+
* Certificates and refusals keyed by the SHA-256 of the module and a configuration key (backend,
|
|
69
|
+
* checker and router versions, and the options that change a certificate). A refusal is stored
|
|
70
|
+
* like a certificate, so a refused module costs a map lookup after the first call.
|
|
71
|
+
* @since 1.1.0
|
|
72
|
+
*/
|
|
73
|
+
export class CertificateCache {
|
|
74
|
+
backend;
|
|
75
|
+
#entries = new Map();
|
|
76
|
+
hits = 0;
|
|
77
|
+
misses = 0;
|
|
78
|
+
constructor(options = {}) {
|
|
79
|
+
this.backend = options.backend ?? defaultBackend();
|
|
80
|
+
}
|
|
81
|
+
get size() {
|
|
82
|
+
return this.#entries.size;
|
|
83
|
+
}
|
|
84
|
+
key(bytes, config) {
|
|
85
|
+
const versions = [this.backend, CHECKER, OWNERSHIP_CHECKER, ROUTER_VERSION];
|
|
86
|
+
return `${sha(bytes)}:${sha(JSON.stringify([versions, config ?? null]))}`;
|
|
87
|
+
}
|
|
88
|
+
/** Returns the stored answer of `slot`, or makes, times and stores it. `ms` is 0 on a hit. */
|
|
89
|
+
get(bytes, config, slot, make) {
|
|
90
|
+
const key = this.key(bytes, config);
|
|
91
|
+
const entry = this.#entries.get(key) ?? { ms: {} };
|
|
92
|
+
this.#entries.set(key, entry);
|
|
93
|
+
const stored = entry[slot];
|
|
94
|
+
if (stored !== undefined) {
|
|
95
|
+
this.hits++;
|
|
96
|
+
return { value: stored, ms: 0, hit: true };
|
|
97
|
+
}
|
|
98
|
+
this.misses++;
|
|
99
|
+
const started = performance.now();
|
|
100
|
+
const value = make();
|
|
101
|
+
const ms = performance.now() - started;
|
|
102
|
+
entry[slot] = value;
|
|
103
|
+
entry.ms[slot] = ms;
|
|
104
|
+
return { value, ms, hit: false };
|
|
105
|
+
}
|
|
106
|
+
/** Wall time the analysis took when it filled the slot, for an offline certification report. */
|
|
107
|
+
filledMs(bytes, config, slot) {
|
|
108
|
+
return this.#entries.get(this.key(bytes, config))?.ms[slot];
|
|
109
|
+
}
|
|
110
|
+
serialize() {
|
|
111
|
+
return encodeValues([...this.#entries]);
|
|
112
|
+
}
|
|
113
|
+
/** Loads what `serialize` wrote. Entries made under another backend never match a key. */
|
|
114
|
+
load(text) {
|
|
115
|
+
for (const [key, entry] of decodeValues(text))
|
|
116
|
+
this.#entries.set(key, entry);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const TYPE_NAME = new Map([
|
|
120
|
+
[binaryen.i32, 'i32'],
|
|
121
|
+
[binaryen.i64, 'i64'],
|
|
122
|
+
[binaryen.f32, 'f32'],
|
|
123
|
+
[binaryen.f64, 'f64']
|
|
124
|
+
]);
|
|
125
|
+
/** One decode of the module: what both certificate builders need to know before they start. */
|
|
126
|
+
export function analyzeModule(bytes, entry) {
|
|
127
|
+
const shape = {
|
|
128
|
+
valid: false,
|
|
129
|
+
entryFound: false,
|
|
130
|
+
entryParams: [],
|
|
131
|
+
entryResults: 0,
|
|
132
|
+
functionImports: 0,
|
|
133
|
+
memoryImported: false
|
|
134
|
+
};
|
|
135
|
+
let compiled;
|
|
136
|
+
try {
|
|
137
|
+
compiled = new WebAssembly.Module(Uint8Array.from(bytes));
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return shape;
|
|
141
|
+
}
|
|
142
|
+
shape.valid = true;
|
|
143
|
+
for (const item of WebAssembly.Module.imports(compiled)) {
|
|
144
|
+
if (item.kind === 'function')
|
|
145
|
+
shape.functionImports++;
|
|
146
|
+
if (item.kind === 'memory')
|
|
147
|
+
shape.memoryImported = true;
|
|
148
|
+
}
|
|
149
|
+
const module = binaryen.readBinary(Uint8Array.from(bytes));
|
|
150
|
+
try {
|
|
151
|
+
const exported = module.getExport(entry);
|
|
152
|
+
if (exported) {
|
|
153
|
+
const info = binaryen.getExportInfo(exported);
|
|
154
|
+
if (info.kind === binaryen.ExternalFunction) {
|
|
155
|
+
const fn = binaryen.getFunctionInfo(module.getFunction(info.value));
|
|
156
|
+
shape.entryFound = true;
|
|
157
|
+
shape.entryParams = binaryen
|
|
158
|
+
.expandType(fn.params)
|
|
159
|
+
.map((type) => TYPE_NAME.get(type) ?? 'other');
|
|
160
|
+
shape.entryResults = binaryen.expandType(fn.results).length;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
module.dispose();
|
|
166
|
+
}
|
|
167
|
+
return shape;
|
|
168
|
+
}
|
|
169
|
+
const streamShaped = (s) => s.entryFound &&
|
|
170
|
+
s.entryParams.length === 3 &&
|
|
171
|
+
s.entryParams[1] === 'i32' &&
|
|
172
|
+
s.entryParams[2] === 'i32' &&
|
|
173
|
+
(s.entryParams[0] === 'i32' || s.entryParams[0] === 'i64') &&
|
|
174
|
+
s.entryResults === 1;
|
|
175
|
+
const recordsShaped = (s) => s.entryFound &&
|
|
176
|
+
s.entryParams.length >= 3 &&
|
|
177
|
+
s.entryParams.slice(0, 3).every((t) => t === 'i32');
|
|
178
|
+
// #endregion
|
|
179
|
+
const MODE_ROUTES = {
|
|
180
|
+
serial: [],
|
|
181
|
+
w1: ['summary'],
|
|
182
|
+
w2: ['window'],
|
|
183
|
+
independent: ['summary', 'window'],
|
|
184
|
+
shared: ['summary', 'window'],
|
|
185
|
+
router: ['summary', 'window', 'explicit', 'tracked']
|
|
186
|
+
};
|
|
187
|
+
function ownershipReason(refusal) {
|
|
188
|
+
switch (refusal.reason) {
|
|
189
|
+
case 'no-window':
|
|
190
|
+
return 'no-certificate';
|
|
191
|
+
case 'allocator':
|
|
192
|
+
case 'ptr-store':
|
|
193
|
+
case 'ptr-return':
|
|
194
|
+
case 'ptr-import':
|
|
195
|
+
case 'ptr-compare':
|
|
196
|
+
case 'ptr-control':
|
|
197
|
+
case 'ptr-deref':
|
|
198
|
+
return 'allocator-state';
|
|
199
|
+
case 'read-before-write':
|
|
200
|
+
case 'aliasing':
|
|
201
|
+
case 'final-state':
|
|
202
|
+
return 'shared-state';
|
|
203
|
+
default:
|
|
204
|
+
return 'unclassified-dependency';
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** The prefix domain is tried after a plain refusal unless the caller chose an option the checker does not combine with it. @internal */
|
|
208
|
+
export function effectiveOwnership(given) {
|
|
209
|
+
const o = given ?? {};
|
|
210
|
+
const prefixFallback = o.prefix === undefined && !o.allocator && !o.config && (o.recursion ?? 1) <= 1;
|
|
211
|
+
return {
|
|
212
|
+
options: prefixFallback ? { ...o, prefix: true } : (given ?? null),
|
|
213
|
+
prefixFallback
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Chooses the route from the module bytes and the call, without running the call. The order is the
|
|
218
|
+
* certified summary, then the certified window, then the explicit route when the caller supplied
|
|
219
|
+
* one, then the tracked route when its assumptions hold, else serial. Both certifiers are asked
|
|
220
|
+
* only for the call shape they can serve, and a refusal is cached like a certificate.
|
|
221
|
+
* @since 1.1.0
|
|
222
|
+
*/
|
|
223
|
+
export function decide(bytes, call, options) {
|
|
224
|
+
const cache = options.cache ?? new CertificateCache();
|
|
225
|
+
const workers = options.workers ?? Math.max(1, Math.min(availableParallelism(), 8));
|
|
226
|
+
const allowed = MODE_ROUTES[options.mode];
|
|
227
|
+
const considered = [];
|
|
228
|
+
const analyses = [];
|
|
229
|
+
let certifyMs = 0;
|
|
230
|
+
let anyMiss = false;
|
|
231
|
+
const note = (route, verdict, reason, detail = '') => considered.push({ route, verdict, reason, detail });
|
|
232
|
+
const finish = (route, reason, detail, extra = {}) => {
|
|
233
|
+
note(route, route === 'serial' ? 'refused' : 'taken', reason, detail);
|
|
234
|
+
return {
|
|
235
|
+
decision: {
|
|
236
|
+
route,
|
|
237
|
+
reason,
|
|
238
|
+
detail,
|
|
239
|
+
mode: options.mode,
|
|
240
|
+
certifyMs,
|
|
241
|
+
cacheHit: analyses.length > 0 && !anyMiss,
|
|
242
|
+
analyses,
|
|
243
|
+
considered
|
|
244
|
+
},
|
|
245
|
+
...extra
|
|
246
|
+
};
|
|
247
|
+
};
|
|
248
|
+
const ask = (slot, config, make) => {
|
|
249
|
+
const answer = cache.get(bytes, config, slot, make);
|
|
250
|
+
analyses.push(slot);
|
|
251
|
+
certifyMs += answer.ms;
|
|
252
|
+
if (!answer.hit)
|
|
253
|
+
anyMiss = true;
|
|
254
|
+
return answer.value;
|
|
255
|
+
};
|
|
256
|
+
const config = (extra) => ({ entry: call.entry, extra });
|
|
257
|
+
if (options.mode === 'serial')
|
|
258
|
+
return finish('serial', 'mode-serial', 'the mode is serial');
|
|
259
|
+
if (workers < 2)
|
|
260
|
+
return finish('serial', 'single-worker', 'one worker leaves nothing to run beside');
|
|
261
|
+
if (call.kind === 'stream') {
|
|
262
|
+
if (!allowed.includes('summary'))
|
|
263
|
+
return finish('serial', 'no-route-in-mode', 'the mode has no route for a stream call');
|
|
264
|
+
if (options.mode === 'shared') {
|
|
265
|
+
const shape = ask('shape', config('shape'), () => analyzeModule(bytes, call.entry));
|
|
266
|
+
if (!streamShaped(shape))
|
|
267
|
+
return finish('serial', 'not-a-stream', 'the entry is not state, pointer, length');
|
|
268
|
+
}
|
|
269
|
+
const result = ask('stream', config('stream'), () => certifyStream(bytes, call.entry));
|
|
270
|
+
if (result.kind !== 'certificate')
|
|
271
|
+
return finish('serial', 'stream-refused', result.reason);
|
|
272
|
+
return finish('summary', 'certified-summary', `${result.ring} over ${result.bits} bits`, {
|
|
273
|
+
stream: result
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
if (allowed.includes('summary'))
|
|
277
|
+
note('summary', 'skipped', 'not-a-stream', 'the call is a loop of records');
|
|
278
|
+
if (options.mode === 'shared') {
|
|
279
|
+
const shape = ask('shape', config('shape'), () => analyzeModule(bytes, call.entry));
|
|
280
|
+
if (!recordsShaped(shape))
|
|
281
|
+
return finish('serial', 'no-certificate', 'the entry does not take a table, a count and an output');
|
|
282
|
+
if (!shape.memoryImported)
|
|
283
|
+
return finish('serial', 'memory-not-imported', 'the module defines its memory');
|
|
284
|
+
}
|
|
285
|
+
if (!allowed.includes('window') &&
|
|
286
|
+
!allowed.includes('tracked') &&
|
|
287
|
+
!allowed.includes('explicit'))
|
|
288
|
+
return finish('serial', 'no-route-in-mode', 'the mode has no route for a records call');
|
|
289
|
+
const ownership = effectiveOwnership(options.ownership);
|
|
290
|
+
const result = ask('ownership', config(['ownership', ownership.options]), () => {
|
|
291
|
+
const plain = certifyOwnership(bytes, { entry: call.entry, ...options.ownership });
|
|
292
|
+
if (plain.kind === 'certificate' || !ownership.prefixFallback)
|
|
293
|
+
return plain;
|
|
294
|
+
// the prefix option is not a superset of the plain check, so it runs second
|
|
295
|
+
// and a refusal keeps the plain reason
|
|
296
|
+
const prefixed = certifyOwnership(bytes, {
|
|
297
|
+
entry: call.entry,
|
|
298
|
+
...options.ownership,
|
|
299
|
+
prefix: true
|
|
300
|
+
});
|
|
301
|
+
return prefixed.kind === 'certificate' ? prefixed : plain;
|
|
302
|
+
});
|
|
303
|
+
let refusal;
|
|
304
|
+
if (result.kind === 'certificate') {
|
|
305
|
+
if (!allowed.includes('window')) {
|
|
306
|
+
note('window', 'skipped', 'no-route-in-mode', 'the mode excludes the window route');
|
|
307
|
+
}
|
|
308
|
+
else if (result.wildStores > 0)
|
|
309
|
+
note('window', 'refused', 'wild-store', `${result.wildStores} stores write an address no record owns`);
|
|
310
|
+
else if (!guardRecords(result, [...call.regions, ...call.writes]))
|
|
311
|
+
note('window', 'refused', 'layout-overlap', 'a record region overlaps a certified window');
|
|
312
|
+
else
|
|
313
|
+
return finish('window', 'certified-window', `${result.windows.length} windows`, {
|
|
314
|
+
window: result
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
refusal = result;
|
|
319
|
+
note('window', 'refused', ownershipReason(result), `${result.reason}: ${result.detail}`);
|
|
320
|
+
}
|
|
321
|
+
if (allowed.includes('explicit') && options.explicit)
|
|
322
|
+
return finish('explicit', 'explicit-runner', 'the caller supplied a runner');
|
|
323
|
+
if (!allowed.includes('tracked')) {
|
|
324
|
+
const last = considered[considered.length - 1];
|
|
325
|
+
const reason = last.verdict === 'refused' ? last.reason : 'no-certificate';
|
|
326
|
+
return finish('serial', reason, last.detail);
|
|
327
|
+
}
|
|
328
|
+
// the tracked route runs only where the certifier found no shared state to protect
|
|
329
|
+
if (!refusal) {
|
|
330
|
+
const last = considered[considered.length - 1];
|
|
331
|
+
return finish('serial', last.reason, last.detail);
|
|
332
|
+
}
|
|
333
|
+
// allocator statics move to a slot-private window the route validates
|
|
334
|
+
// and the loss rule ends a dispatch that does not pay
|
|
335
|
+
const why = ownershipReason(refusal);
|
|
336
|
+
if (why !== 'no-certificate' && why !== 'allocator-state')
|
|
337
|
+
return finish('serial', why, `${refusal.reason}: ${refusal.detail}`);
|
|
338
|
+
const { importsDeterministic, residueUnobserved } = options.assume ?? {};
|
|
339
|
+
const shape = ask('shape', config('shape'), () => analyzeModule(bytes, call.entry));
|
|
340
|
+
if (!(importsDeterministic || shape.functionImports === 0) || !residueUnobserved)
|
|
341
|
+
return finish('serial', 'assumption-unasserted', 'the tracked route needs deterministic imports and unobserved stack residue');
|
|
342
|
+
return finish('tracked', 'tracked-eligible', 'no shared window; the caller asserts the tracked assumptions');
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* The open route behind one call description: it holds the memory, the pools and the sticky
|
|
346
|
+
* admission decision. Write the inputs into `memory` after `open`, then `run`.
|
|
347
|
+
* @since 1.1.0
|
|
348
|
+
*/
|
|
349
|
+
export class Router {
|
|
350
|
+
decision;
|
|
351
|
+
/** Wall time of `open` after the decision: memory, instances and pools. */
|
|
352
|
+
setupMs;
|
|
353
|
+
#call;
|
|
354
|
+
#options;
|
|
355
|
+
#memory;
|
|
356
|
+
#owner;
|
|
357
|
+
#route;
|
|
358
|
+
#window;
|
|
359
|
+
#folio;
|
|
360
|
+
#stream;
|
|
361
|
+
// serial time of one record from the first probe, kept so the floor test needs no second probe
|
|
362
|
+
#perRecordMs;
|
|
363
|
+
#dispatches = 0;
|
|
364
|
+
#losses = 0;
|
|
365
|
+
#why;
|
|
366
|
+
#exports = {};
|
|
367
|
+
// width of the stream state in bits, for the serial path of a stream call
|
|
368
|
+
#bits = 32;
|
|
369
|
+
#closed = false;
|
|
370
|
+
constructor(decision, call, options, memory, owner, route, setupMs) {
|
|
371
|
+
this.decision = decision;
|
|
372
|
+
this.#call = call;
|
|
373
|
+
this.#options = options;
|
|
374
|
+
this.#memory = memory;
|
|
375
|
+
this.#owner = owner;
|
|
376
|
+
this.#route = route;
|
|
377
|
+
this.setupMs = setupMs;
|
|
378
|
+
}
|
|
379
|
+
get memory() {
|
|
380
|
+
return this.#memory;
|
|
381
|
+
}
|
|
382
|
+
/** The route the next call takes: the decision's, or serial once a floor test refused it. */
|
|
383
|
+
get route() {
|
|
384
|
+
return this.#route;
|
|
385
|
+
}
|
|
386
|
+
static async open(bytes, call, options) {
|
|
387
|
+
const plan = decide(bytes, call, options);
|
|
388
|
+
const started = performance.now();
|
|
389
|
+
const workers = options.workers ?? Math.max(1, Math.min(availableParallelism(), 8));
|
|
390
|
+
const extra = options.imports
|
|
391
|
+
? (await import(__rewriteRelativeImportExtension(String(options.imports)))).default()
|
|
392
|
+
: {};
|
|
393
|
+
let decision = plan.decision;
|
|
394
|
+
const refuse = (reason, detail) => {
|
|
395
|
+
decision = { ...decision, route: 'serial', reason, detail };
|
|
396
|
+
decision.considered = [
|
|
397
|
+
...decision.considered,
|
|
398
|
+
{ route: plan.decision.route, verdict: 'refused', reason, detail }
|
|
399
|
+
];
|
|
400
|
+
};
|
|
401
|
+
const serialOwner = (module, memory) => {
|
|
402
|
+
const compiled = new WebAssembly.Module(Uint8Array.from(module));
|
|
403
|
+
const wantsMemory = WebAssembly.Module.imports(compiled).find((i) => i.kind === 'memory');
|
|
404
|
+
// a program that imports its memory shared links only to a shared one
|
|
405
|
+
const sharedImport = !!wantsMemory &&
|
|
406
|
+
(() => {
|
|
407
|
+
try {
|
|
408
|
+
return Buffer.compare(sharedMemoryImport(module), module) === 0;
|
|
409
|
+
}
|
|
410
|
+
catch {
|
|
411
|
+
return false;
|
|
412
|
+
}
|
|
413
|
+
})();
|
|
414
|
+
const own = memory ??
|
|
415
|
+
new WebAssembly.Memory({
|
|
416
|
+
initial: options.pages,
|
|
417
|
+
maximum: options.pages,
|
|
418
|
+
...(sharedImport ? { shared: true } : {})
|
|
419
|
+
});
|
|
420
|
+
const imports = {
|
|
421
|
+
...extra,
|
|
422
|
+
...(wantsMemory
|
|
423
|
+
? {
|
|
424
|
+
[wantsMemory.module]: {
|
|
425
|
+
...(extra[wantsMemory.module] ?? {}),
|
|
426
|
+
[wantsMemory.name]: own
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
: {})
|
|
430
|
+
};
|
|
431
|
+
const exports = new WebAssembly.Instance(compiled, imports).exports;
|
|
432
|
+
const exported = exports.memory;
|
|
433
|
+
return {
|
|
434
|
+
memory: wantsMemory ? own : (exported ?? own),
|
|
435
|
+
fn: exports[call.entry],
|
|
436
|
+
exports
|
|
437
|
+
};
|
|
438
|
+
};
|
|
439
|
+
if (decision.route === 'summary') {
|
|
440
|
+
const certificate = plan.stream;
|
|
441
|
+
const subject = shareCertified(bytes, certificate, options.pages);
|
|
442
|
+
const memory = new WebAssembly.Memory({
|
|
443
|
+
initial: options.pages,
|
|
444
|
+
maximum: options.pages,
|
|
445
|
+
shared: true
|
|
446
|
+
});
|
|
447
|
+
installPrefill(subject, memory);
|
|
448
|
+
const module = new WebAssembly.Module(subject.bytes);
|
|
449
|
+
const pool = new TaskPool(workers);
|
|
450
|
+
const threads = Array.from({ length: workers }, (_, index) => {
|
|
451
|
+
const link = pool.link(index);
|
|
452
|
+
return new Worker(workerUrl(), {
|
|
453
|
+
workerData: { module, memory, link, layout: certificate.layout },
|
|
454
|
+
transferList: [link.port]
|
|
455
|
+
});
|
|
456
|
+
});
|
|
457
|
+
const exports = new WebAssembly.Instance(module, { env: { memory } }).exports;
|
|
458
|
+
const fn = exports[call.entry];
|
|
459
|
+
const router = new Router(decision, call, options, memory, fn, 'summary', 0);
|
|
460
|
+
router.#exports = exports;
|
|
461
|
+
router.#stream = { certificate, pool, workers: threads, module };
|
|
462
|
+
router.#bits = certificate.bits;
|
|
463
|
+
return router.#timed(started);
|
|
464
|
+
}
|
|
465
|
+
if (decision.route === 'serial') {
|
|
466
|
+
const { memory, fn, exports } = serialOwner(bytes);
|
|
467
|
+
const router = new Router(decision, call, options, memory, fn, 'serial', 0);
|
|
468
|
+
router.#exports = exports;
|
|
469
|
+
if (call.kind === 'stream')
|
|
470
|
+
router.#bits = analyzeModule(bytes, call.entry).entryParams[0] === 'i64' ? 64 : 32;
|
|
471
|
+
return router.#timed(started);
|
|
472
|
+
}
|
|
473
|
+
// a parallel route over a records call needs a shared memory the module imports
|
|
474
|
+
let shared;
|
|
475
|
+
try {
|
|
476
|
+
shared = sharedMemoryImport(bytes);
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
refuse('memory-not-imported', error.message);
|
|
480
|
+
const { memory, fn, exports } = serialOwner(bytes);
|
|
481
|
+
const router = new Router(decision, call, options, memory, fn, 'serial', 0);
|
|
482
|
+
router.#exports = exports;
|
|
483
|
+
return router.#timed(started);
|
|
484
|
+
}
|
|
485
|
+
const memory = new WebAssembly.Memory({
|
|
486
|
+
initial: options.pages,
|
|
487
|
+
maximum: options.maxPages ?? 65536,
|
|
488
|
+
shared: true
|
|
489
|
+
});
|
|
490
|
+
const route = decision.route;
|
|
491
|
+
const { fn, exports } = serialOwner(shared, memory);
|
|
492
|
+
const router = new Router(decision, call, options, memory, fn, route, 0);
|
|
493
|
+
router.#exports = exports;
|
|
494
|
+
try {
|
|
495
|
+
if (route === 'window')
|
|
496
|
+
router.#window = await OwnershipSlices.open(bytes, plan.window, {
|
|
497
|
+
memory,
|
|
498
|
+
workers,
|
|
499
|
+
imports: options.imports
|
|
500
|
+
});
|
|
501
|
+
else if (route === 'tracked')
|
|
502
|
+
router.#folio = await Folio.open(bytes, {
|
|
503
|
+
memory,
|
|
504
|
+
workers,
|
|
505
|
+
imports: Object.keys(extra).length ? extra : undefined
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
catch (error) {
|
|
509
|
+
if (route !== 'tracked')
|
|
510
|
+
throw error;
|
|
511
|
+
router.#route = 'serial';
|
|
512
|
+
const detail = String(error.message).slice(0, 200);
|
|
513
|
+
router.decision.route = 'serial';
|
|
514
|
+
router.decision.reason = 'tracked-ineligible';
|
|
515
|
+
router.decision.detail = detail;
|
|
516
|
+
router.decision.considered.push({
|
|
517
|
+
route: 'tracked',
|
|
518
|
+
verdict: 'refused',
|
|
519
|
+
reason: 'tracked-ineligible',
|
|
520
|
+
detail
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
return router.#timed(started);
|
|
524
|
+
}
|
|
525
|
+
/** Calls another export of the module on the owner thread, for setup that is not part of the loop. */
|
|
526
|
+
exec(name, args = []) {
|
|
527
|
+
const fn = this.#exports[name];
|
|
528
|
+
if (typeof fn !== 'function')
|
|
529
|
+
throw new TypeError(`the module exports no function ${name}`);
|
|
530
|
+
return fn(...args);
|
|
531
|
+
}
|
|
532
|
+
#timed(started) {
|
|
533
|
+
this.setupMs = performance.now() - started;
|
|
534
|
+
return this;
|
|
535
|
+
}
|
|
536
|
+
/** Runs the call. A records call probes record 0 once and then follows the floor test. */
|
|
537
|
+
async run(options = {}) {
|
|
538
|
+
const call = this.#call;
|
|
539
|
+
const started = performance.now();
|
|
540
|
+
const done = (route, reason, extra = {}) => ({
|
|
541
|
+
route,
|
|
542
|
+
reason,
|
|
543
|
+
wallMs: performance.now() - started,
|
|
544
|
+
...extra
|
|
545
|
+
});
|
|
546
|
+
if (call.kind === 'stream') {
|
|
547
|
+
const input = new Uint8Array(this.#memory.buffer, call.ptr, call.len);
|
|
548
|
+
const floor = this.#options.floors?.summaryMinBytes ?? routerConstants.summaryMinBytes;
|
|
549
|
+
if (this.#stream && call.len >= floor) {
|
|
550
|
+
const { certificate, pool } = this.#stream;
|
|
551
|
+
const fold = certificate.output ? reconstructCertified : foldCertified;
|
|
552
|
+
const result = fold(pool, input, this.#memory, certificate, {
|
|
553
|
+
initial: options.initial
|
|
554
|
+
});
|
|
555
|
+
return done('summary', 'certified-summary', { state: result.state });
|
|
556
|
+
}
|
|
557
|
+
const layout = this.#stream?.certificate.layout ?? { state: 0, ptr: 1, len: 2 };
|
|
558
|
+
const args = [0, 0, 0];
|
|
559
|
+
const initial = options.initial ?? 0n;
|
|
560
|
+
args[layout.state] =
|
|
561
|
+
this.#bits === 32 ? Number(BigInt.asIntN(32, initial)) : BigInt.asIntN(64, initial);
|
|
562
|
+
args[layout.ptr] = call.ptr;
|
|
563
|
+
args[layout.len] = call.len;
|
|
564
|
+
const end = this.#owner(...args);
|
|
565
|
+
return done('serial', this.#stream ? 'below-floor' : this.decision.reason, {
|
|
566
|
+
state: BigInt.asUintN(this.#bits, BigInt(end))
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
if (this.#route === 'serial') {
|
|
570
|
+
this.#owner(...call.args(0, call.count));
|
|
571
|
+
return done('serial', this.decision.route === 'serial'
|
|
572
|
+
? this.decision.reason
|
|
573
|
+
: (this.#why ?? 'below-floor'));
|
|
574
|
+
}
|
|
575
|
+
let probeMs;
|
|
576
|
+
if (this.#perRecordMs === undefined) {
|
|
577
|
+
if (call.count < 2) {
|
|
578
|
+
this.#owner(...call.args(0, call.count));
|
|
579
|
+
return done('serial', 'below-floor');
|
|
580
|
+
}
|
|
581
|
+
// the first record pays the compile and cold caches, so a probe of several
|
|
582
|
+
// takes the least of the rest
|
|
583
|
+
const probed = Math.max(1, Math.min(PROBE_RECORDS, call.count >> 2));
|
|
584
|
+
const times = [];
|
|
585
|
+
for (let i = 0; i < probed; i++) {
|
|
586
|
+
const t = performance.now();
|
|
587
|
+
this.#owner(...call.args(i, i + 1));
|
|
588
|
+
times.push(performance.now() - t);
|
|
589
|
+
}
|
|
590
|
+
probeMs = times.reduce((sum, ms) => sum + ms, 0);
|
|
591
|
+
this.#perRecordMs = Math.min(...(probed > 1 ? times.slice(1) : times));
|
|
592
|
+
return this.#after(call, probed, probeMs, started);
|
|
593
|
+
}
|
|
594
|
+
return this.#after(call, 0, undefined, started);
|
|
595
|
+
}
|
|
596
|
+
// two dispatches in a row past the first that cost more than the serial time
|
|
597
|
+
// of their records end the dispatch
|
|
598
|
+
#judge(ms, left) {
|
|
599
|
+
this.#dispatches++;
|
|
600
|
+
if (this.#dispatches < 2)
|
|
601
|
+
return;
|
|
602
|
+
if (ms * iterationAdmissionConstants.margin <= left * this.#perRecordMs)
|
|
603
|
+
this.#losses = 0;
|
|
604
|
+
else if (++this.#losses >= 2) {
|
|
605
|
+
this.#route = 'serial';
|
|
606
|
+
this.#why = 'dispatch-lost';
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
async #after(call, from, probeMs, started) {
|
|
610
|
+
const done = (route, reason, extra = {}) => ({
|
|
611
|
+
route,
|
|
612
|
+
reason,
|
|
613
|
+
wallMs: performance.now() - started,
|
|
614
|
+
probeMs,
|
|
615
|
+
...extra
|
|
616
|
+
});
|
|
617
|
+
const left = call.count - from;
|
|
618
|
+
const floors = { ...routerConstants, ...this.#options.floors };
|
|
619
|
+
const floor = this.#route === 'window' ? floors.windowFloorMs : floors.trackedFloorMs;
|
|
620
|
+
if (left < 2 || left * this.#perRecordMs <= floor) {
|
|
621
|
+
const t = performance.now();
|
|
622
|
+
if (left > 0)
|
|
623
|
+
this.#owner(...call.args(from, call.count));
|
|
624
|
+
// a serial run is the best estimate of the serial time; the estimate only goes down
|
|
625
|
+
if (from === 0 && left > 0)
|
|
626
|
+
this.#perRecordMs = Math.min(this.#perRecordMs, (performance.now() - t) / left);
|
|
627
|
+
return done('serial', 'below-floor');
|
|
628
|
+
}
|
|
629
|
+
const dispatched = performance.now();
|
|
630
|
+
if (this.#route === 'window') {
|
|
631
|
+
await this.#window.run(left, (a, b) => call.args(a + from, b + from), {
|
|
632
|
+
regions: call.regions,
|
|
633
|
+
writes: call.writes
|
|
634
|
+
});
|
|
635
|
+
this.#judge(performance.now() - dispatched, left);
|
|
636
|
+
return done('window', 'certified-window');
|
|
637
|
+
}
|
|
638
|
+
if (this.#route === 'tracked') {
|
|
639
|
+
const rest = call.args(from, call.count);
|
|
640
|
+
const report = await this.#folio.run(call.entry, rest);
|
|
641
|
+
// a loop the iteration route skipped pays its lowered owner on every call: stop asking
|
|
642
|
+
if (!report.iteration?.batches) {
|
|
643
|
+
this.#route = 'serial';
|
|
644
|
+
this.#why = 'below-floor';
|
|
645
|
+
}
|
|
646
|
+
else {
|
|
647
|
+
this.#perRecordMs = lowerEstimate(this.#perRecordMs, report.iteration.admission?.plainIterationMs);
|
|
648
|
+
this.#judge(performance.now() - dispatched, left);
|
|
649
|
+
}
|
|
650
|
+
return done('tracked', 'tracked-eligible', {
|
|
651
|
+
tracked: { mode: report.mode, reason: report.reason, iteration: report.iteration }
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
await this.#options.explicit(from ? { ...call, count: left, args: (a, b) => call.args(a + from, b + from) } : call);
|
|
655
|
+
this.#judge(performance.now() - dispatched, left);
|
|
656
|
+
return done('explicit', 'explicit-runner');
|
|
657
|
+
}
|
|
658
|
+
async close() {
|
|
659
|
+
if (this.#closed)
|
|
660
|
+
return;
|
|
661
|
+
this.#closed = true;
|
|
662
|
+
await this.#window?.close();
|
|
663
|
+
await this.#folio?.close();
|
|
664
|
+
if (this.#stream) {
|
|
665
|
+
this.#stream.pool.close();
|
|
666
|
+
await Promise.all(this.#stream.workers.map((w) => w.terminate()));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
const workerUrl = () => new URL(`./worker.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`, import.meta.url);
|
|
671
|
+
export const openRouter = Router.open;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|