@gmitch215/folio 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +455 -26
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/bake.d.ts +8 -3
  7. package/dist/bake.js +5 -2
  8. package/dist/boundaries.d.ts +59 -0
  9. package/dist/boundaries.js +127 -0
  10. package/dist/certified.d.ts +66 -0
  11. package/dist/certified.js +192 -0
  12. package/dist/certify.d.ts +98 -0
  13. package/dist/certify.js +2628 -0
  14. package/dist/compiler.d.ts +37 -1
  15. package/dist/compiler.js +116 -1
  16. package/dist/context.d.ts +47 -0
  17. package/dist/context.js +139 -0
  18. package/dist/coordinator.d.ts +1 -1
  19. package/dist/coordinator.js +54 -5
  20. package/dist/extract.d.ts +114 -1
  21. package/dist/extract.js +1011 -242
  22. package/dist/fold.d.ts +32 -0
  23. package/dist/fold.js +105 -0
  24. package/dist/frames.d.ts +20 -2
  25. package/dist/frames.js +205 -10
  26. package/dist/inline.d.ts +182 -0
  27. package/dist/inline.js +766 -0
  28. package/dist/iteration-admission.d.ts +185 -0
  29. package/dist/iteration-admission.js +201 -0
  30. package/dist/iteration-layout.d.ts +135 -0
  31. package/dist/iteration-layout.js +169 -0
  32. package/dist/iteration-owner.d.ts +45 -0
  33. package/dist/iteration-owner.js +223 -0
  34. package/dist/iteration-worker.d.ts +1 -0
  35. package/dist/iteration-worker.js +216 -0
  36. package/dist/iteration.d.ts +329 -0
  37. package/dist/iteration.js +1210 -0
  38. package/dist/lease.d.ts +45 -0
  39. package/dist/lease.js +274 -0
  40. package/dist/managed.d.ts +78 -0
  41. package/dist/managed.js +448 -27
  42. package/dist/memo.d.ts +99 -0
  43. package/dist/memo.js +250 -0
  44. package/dist/node.d.ts +61 -5
  45. package/dist/node.js +421 -23
  46. package/dist/ownership-redirect.d.ts +30 -0
  47. package/dist/ownership-redirect.js +179 -0
  48. package/dist/ownership-slices.d.ts +44 -0
  49. package/dist/ownership-slices.js +72 -0
  50. package/dist/ownership.d.ts +161 -0
  51. package/dist/ownership.js +6568 -0
  52. package/dist/ranges.d.ts +78 -0
  53. package/dist/ranges.js +263 -0
  54. package/dist/read-scan.d.ts +18 -0
  55. package/dist/read-scan.js +94 -0
  56. package/dist/read-windows.d.ts +103 -0
  57. package/dist/read-windows.js +244 -0
  58. package/dist/router-worker.d.ts +1 -0
  59. package/dist/router-worker.js +4 -0
  60. package/dist/router.d.ts +203 -0
  61. package/dist/router.js +667 -0
  62. package/dist/runs.d.ts +44 -0
  63. package/dist/runs.js +182 -0
  64. package/dist/slices-worker.d.ts +1 -0
  65. package/dist/slices-worker.js +38 -0
  66. package/dist/slices.d.ts +126 -0
  67. package/dist/slices.js +441 -0
  68. package/dist/tasks.d.ts +14 -4
  69. package/dist/tasks.js +23 -9
  70. package/dist/transaction.d.ts +10 -0
  71. package/package.json +44 -4
package/dist/router.js ADDED
@@ -0,0 +1,667 @@
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 "./certified.js";
15
+ import { certifyStream, CHECKER } from "./certify.js";
16
+ import { iterationAdmissionConstants } from "./iteration-admission.js";
17
+ import { Folio } from "./node.js";
18
+ import { OwnershipSlices } from "./ownership-slices.js";
19
+ import { certifyOwnership, guardRecords, OWNERSHIP_CHECKER } from "./ownership.js";
20
+ import { decodeValues, encodeValues, sharedMemoryImport } from "./slices.js";
21
+ import { TaskPool } from "./tasks.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: `scratchpad/v11/w3/dev/fit-*.jsonl`.
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 and a refusal keeps the plain reason
295
+ const prefixed = certifyOwnership(bytes, {
296
+ entry: call.entry,
297
+ ...options.ownership,
298
+ prefix: true
299
+ });
300
+ return prefixed.kind === 'certificate' ? prefixed : plain;
301
+ });
302
+ let refusal;
303
+ if (result.kind === 'certificate') {
304
+ if (!allowed.includes('window')) {
305
+ note('window', 'skipped', 'no-route-in-mode', 'the mode excludes the window route');
306
+ }
307
+ else if (result.wildStores > 0)
308
+ note('window', 'refused', 'wild-store', `${result.wildStores} stores write an address no record owns`);
309
+ else if (!guardRecords(result, [...call.regions, ...call.writes]))
310
+ note('window', 'refused', 'layout-overlap', 'a record region overlaps a certified window');
311
+ else
312
+ return finish('window', 'certified-window', `${result.windows.length} windows`, {
313
+ window: result
314
+ });
315
+ }
316
+ else {
317
+ refusal = result;
318
+ note('window', 'refused', ownershipReason(result), `${result.reason}: ${result.detail}`);
319
+ }
320
+ if (allowed.includes('explicit') && options.explicit)
321
+ return finish('explicit', 'explicit-runner', 'the caller supplied a runner');
322
+ if (!allowed.includes('tracked')) {
323
+ const last = considered[considered.length - 1];
324
+ const reason = last.verdict === 'refused' ? last.reason : 'no-certificate';
325
+ return finish('serial', reason, last.detail);
326
+ }
327
+ // the tracked route runs only where the certifier found no shared state to protect
328
+ if (!refusal) {
329
+ const last = considered[considered.length - 1];
330
+ return finish('serial', last.reason, last.detail);
331
+ }
332
+ // allocator statics move to a slot-private window the route validates, and the loss rule ends a dispatch that does not pay
333
+ const why = ownershipReason(refusal);
334
+ if (why !== 'no-certificate' && why !== 'allocator-state')
335
+ return finish('serial', why, `${refusal.reason}: ${refusal.detail}`);
336
+ const { importsDeterministic, residueUnobserved } = options.assume ?? {};
337
+ const shape = ask('shape', config('shape'), () => analyzeModule(bytes, call.entry));
338
+ if (!(importsDeterministic || shape.functionImports === 0) || !residueUnobserved)
339
+ return finish('serial', 'assumption-unasserted', 'the tracked route needs deterministic imports and unobserved stack residue');
340
+ return finish('tracked', 'tracked-eligible', 'no shared window; the caller asserts the tracked assumptions');
341
+ }
342
+ /**
343
+ * The open route behind one call description: it holds the memory, the pools and the sticky
344
+ * admission decision. Write the inputs into `memory` after `open`, then `run`.
345
+ * @since 1.1.0
346
+ */
347
+ export class Router {
348
+ decision;
349
+ /** Wall time of `open` after the decision: memory, instances and pools. */
350
+ setupMs;
351
+ #call;
352
+ #options;
353
+ #memory;
354
+ #owner;
355
+ #route;
356
+ #window;
357
+ #folio;
358
+ #stream;
359
+ // serial time of one record from the first probe, kept so the floor test needs no second probe
360
+ #perRecordMs;
361
+ #dispatches = 0;
362
+ #losses = 0;
363
+ #why;
364
+ #exports = {};
365
+ // width of the stream state in bits, for the serial path of a stream call
366
+ #bits = 32;
367
+ #closed = false;
368
+ constructor(decision, call, options, memory, owner, route, setupMs) {
369
+ this.decision = decision;
370
+ this.#call = call;
371
+ this.#options = options;
372
+ this.#memory = memory;
373
+ this.#owner = owner;
374
+ this.#route = route;
375
+ this.setupMs = setupMs;
376
+ }
377
+ get memory() {
378
+ return this.#memory;
379
+ }
380
+ /** The route the next call takes: the decision's, or serial once a floor test refused it. */
381
+ get route() {
382
+ return this.#route;
383
+ }
384
+ static async open(bytes, call, options) {
385
+ const plan = decide(bytes, call, options);
386
+ const started = performance.now();
387
+ const workers = options.workers ?? Math.max(1, Math.min(availableParallelism(), 8));
388
+ const extra = options.imports
389
+ ? (await import(__rewriteRelativeImportExtension(String(options.imports)))).default()
390
+ : {};
391
+ let decision = plan.decision;
392
+ const refuse = (reason, detail) => {
393
+ decision = { ...decision, route: 'serial', reason, detail };
394
+ decision.considered = [
395
+ ...decision.considered,
396
+ { route: plan.decision.route, verdict: 'refused', reason, detail }
397
+ ];
398
+ };
399
+ const serialOwner = (module, memory) => {
400
+ const compiled = new WebAssembly.Module(Uint8Array.from(module));
401
+ const wantsMemory = WebAssembly.Module.imports(compiled).find((i) => i.kind === 'memory');
402
+ // a program that imports its memory shared links only to a shared one
403
+ const sharedImport = !!wantsMemory &&
404
+ (() => {
405
+ try {
406
+ return Buffer.compare(sharedMemoryImport(module), module) === 0;
407
+ }
408
+ catch {
409
+ return false;
410
+ }
411
+ })();
412
+ const own = memory ??
413
+ new WebAssembly.Memory({
414
+ initial: options.pages,
415
+ maximum: options.pages,
416
+ ...(sharedImport ? { shared: true } : {})
417
+ });
418
+ const imports = {
419
+ ...extra,
420
+ ...(wantsMemory
421
+ ? {
422
+ [wantsMemory.module]: {
423
+ ...(extra[wantsMemory.module] ?? {}),
424
+ [wantsMemory.name]: own
425
+ }
426
+ }
427
+ : {})
428
+ };
429
+ const exports = new WebAssembly.Instance(compiled, imports).exports;
430
+ const exported = exports.memory;
431
+ return {
432
+ memory: wantsMemory ? own : (exported ?? own),
433
+ fn: exports[call.entry],
434
+ exports
435
+ };
436
+ };
437
+ if (decision.route === 'summary') {
438
+ const certificate = plan.stream;
439
+ const subject = shareCertified(bytes, certificate, options.pages);
440
+ const memory = new WebAssembly.Memory({
441
+ initial: options.pages,
442
+ maximum: options.pages,
443
+ shared: true
444
+ });
445
+ installPrefill(subject, memory);
446
+ const module = new WebAssembly.Module(subject.bytes);
447
+ const pool = new TaskPool(workers);
448
+ const threads = Array.from({ length: workers }, (_, index) => {
449
+ const link = pool.link(index);
450
+ return new Worker(workerUrl(), {
451
+ workerData: { module, memory, link, layout: certificate.layout },
452
+ transferList: [link.port]
453
+ });
454
+ });
455
+ const exports = new WebAssembly.Instance(module, { env: { memory } }).exports;
456
+ const fn = exports[call.entry];
457
+ const router = new Router(decision, call, options, memory, fn, 'summary', 0);
458
+ router.#exports = exports;
459
+ router.#stream = { certificate, pool, workers: threads, module };
460
+ router.#bits = certificate.bits;
461
+ return router.#timed(started);
462
+ }
463
+ if (decision.route === 'serial') {
464
+ const { memory, fn, exports } = serialOwner(bytes);
465
+ const router = new Router(decision, call, options, memory, fn, 'serial', 0);
466
+ router.#exports = exports;
467
+ if (call.kind === 'stream')
468
+ router.#bits = analyzeModule(bytes, call.entry).entryParams[0] === 'i64' ? 64 : 32;
469
+ return router.#timed(started);
470
+ }
471
+ // a parallel route over a records call needs a shared memory the module imports
472
+ let shared;
473
+ try {
474
+ shared = sharedMemoryImport(bytes);
475
+ }
476
+ catch (error) {
477
+ refuse('memory-not-imported', error.message);
478
+ const { memory, fn, exports } = serialOwner(bytes);
479
+ const router = new Router(decision, call, options, memory, fn, 'serial', 0);
480
+ router.#exports = exports;
481
+ return router.#timed(started);
482
+ }
483
+ const memory = new WebAssembly.Memory({
484
+ initial: options.pages,
485
+ maximum: options.maxPages ?? 65536,
486
+ shared: true
487
+ });
488
+ const route = decision.route;
489
+ const { fn, exports } = serialOwner(shared, memory);
490
+ const router = new Router(decision, call, options, memory, fn, route, 0);
491
+ router.#exports = exports;
492
+ try {
493
+ if (route === 'window')
494
+ router.#window = await OwnershipSlices.open(bytes, plan.window, {
495
+ memory,
496
+ workers,
497
+ imports: options.imports
498
+ });
499
+ else if (route === 'tracked')
500
+ router.#folio = await Folio.open(bytes, {
501
+ memory,
502
+ workers,
503
+ imports: Object.keys(extra).length ? extra : undefined
504
+ });
505
+ }
506
+ catch (error) {
507
+ if (route !== 'tracked')
508
+ throw error;
509
+ router.#route = 'serial';
510
+ const detail = String(error.message).slice(0, 200);
511
+ router.decision.route = 'serial';
512
+ router.decision.reason = 'tracked-ineligible';
513
+ router.decision.detail = detail;
514
+ router.decision.considered.push({
515
+ route: 'tracked',
516
+ verdict: 'refused',
517
+ reason: 'tracked-ineligible',
518
+ detail
519
+ });
520
+ }
521
+ return router.#timed(started);
522
+ }
523
+ /** Calls another export of the module on the owner thread, for setup that is not part of the loop. */
524
+ exec(name, args = []) {
525
+ const fn = this.#exports[name];
526
+ if (typeof fn !== 'function')
527
+ throw new TypeError(`the module exports no function ${name}`);
528
+ return fn(...args);
529
+ }
530
+ #timed(started) {
531
+ this.setupMs = performance.now() - started;
532
+ return this;
533
+ }
534
+ /** Runs the call. A records call probes record 0 once and then follows the floor test. */
535
+ async run(options = {}) {
536
+ const call = this.#call;
537
+ const started = performance.now();
538
+ const done = (route, reason, extra = {}) => ({
539
+ route,
540
+ reason,
541
+ wallMs: performance.now() - started,
542
+ ...extra
543
+ });
544
+ if (call.kind === 'stream') {
545
+ const input = new Uint8Array(this.#memory.buffer, call.ptr, call.len);
546
+ const floor = this.#options.floors?.summaryMinBytes ?? routerConstants.summaryMinBytes;
547
+ if (this.#stream && call.len >= floor) {
548
+ const { certificate, pool } = this.#stream;
549
+ const fold = certificate.output ? reconstructCertified : foldCertified;
550
+ const result = fold(pool, input, this.#memory, certificate, {
551
+ initial: options.initial
552
+ });
553
+ return done('summary', 'certified-summary', { state: result.state });
554
+ }
555
+ const layout = this.#stream?.certificate.layout ?? { state: 0, ptr: 1, len: 2 };
556
+ const args = [0, 0, 0];
557
+ const initial = options.initial ?? 0n;
558
+ args[layout.state] =
559
+ this.#bits === 32 ? Number(BigInt.asIntN(32, initial)) : BigInt.asIntN(64, initial);
560
+ args[layout.ptr] = call.ptr;
561
+ args[layout.len] = call.len;
562
+ const end = this.#owner(...args);
563
+ return done('serial', this.#stream ? 'below-floor' : this.decision.reason, {
564
+ state: BigInt.asUintN(this.#bits, BigInt(end))
565
+ });
566
+ }
567
+ if (this.#route === 'serial') {
568
+ this.#owner(...call.args(0, call.count));
569
+ return done('serial', this.decision.route === 'serial'
570
+ ? this.decision.reason
571
+ : (this.#why ?? 'below-floor'));
572
+ }
573
+ let probeMs;
574
+ if (this.#perRecordMs === undefined) {
575
+ if (call.count < 2) {
576
+ this.#owner(...call.args(0, call.count));
577
+ return done('serial', 'below-floor');
578
+ }
579
+ // the first record pays the compile and the cold caches, so a probe of several takes the least of the rest
580
+ const probed = Math.max(1, Math.min(PROBE_RECORDS, call.count >> 2));
581
+ const times = [];
582
+ for (let i = 0; i < probed; i++) {
583
+ const t = performance.now();
584
+ this.#owner(...call.args(i, i + 1));
585
+ times.push(performance.now() - t);
586
+ }
587
+ probeMs = times.reduce((sum, ms) => sum + ms, 0);
588
+ this.#perRecordMs = Math.min(...(probed > 1 ? times.slice(1) : times));
589
+ return this.#after(call, probed, probeMs, started);
590
+ }
591
+ return this.#after(call, 0, undefined, started);
592
+ }
593
+ // two dispatches in a row past the first that cost more than the serial time of their records end the dispatch
594
+ #judge(ms, left) {
595
+ this.#dispatches++;
596
+ if (this.#dispatches < 2)
597
+ return;
598
+ if (ms * iterationAdmissionConstants.margin <= left * this.#perRecordMs)
599
+ this.#losses = 0;
600
+ else if (++this.#losses >= 2) {
601
+ this.#route = 'serial';
602
+ this.#why = 'dispatch-lost';
603
+ }
604
+ }
605
+ async #after(call, from, probeMs, started) {
606
+ const done = (route, reason, extra = {}) => ({
607
+ route,
608
+ reason,
609
+ wallMs: performance.now() - started,
610
+ probeMs,
611
+ ...extra
612
+ });
613
+ const left = call.count - from;
614
+ const floors = { ...routerConstants, ...this.#options.floors };
615
+ const floor = this.#route === 'window' ? floors.windowFloorMs : floors.trackedFloorMs;
616
+ if (left < 2 || left * this.#perRecordMs <= floor) {
617
+ const t = performance.now();
618
+ if (left > 0)
619
+ this.#owner(...call.args(from, call.count));
620
+ // a serial run is the best estimate of the serial time; the estimate only goes down
621
+ if (from === 0 && left > 0)
622
+ this.#perRecordMs = Math.min(this.#perRecordMs, (performance.now() - t) / left);
623
+ return done('serial', 'below-floor');
624
+ }
625
+ const dispatched = performance.now();
626
+ if (this.#route === 'window') {
627
+ await this.#window.run(left, (a, b) => call.args(a + from, b + from), {
628
+ regions: call.regions,
629
+ writes: call.writes
630
+ });
631
+ this.#judge(performance.now() - dispatched, left);
632
+ return done('window', 'certified-window');
633
+ }
634
+ if (this.#route === 'tracked') {
635
+ const rest = call.args(from, call.count);
636
+ const report = await this.#folio.run(call.entry, rest);
637
+ // a loop the iteration route did not dispatch pays its lowered owner on every call: stop asking
638
+ if (!report.iteration?.batches) {
639
+ this.#route = 'serial';
640
+ this.#why = 'below-floor';
641
+ }
642
+ else {
643
+ this.#perRecordMs = lowerEstimate(this.#perRecordMs, report.iteration.admission?.plainIterationMs);
644
+ this.#judge(performance.now() - dispatched, left);
645
+ }
646
+ return done('tracked', 'tracked-eligible', {
647
+ tracked: { mode: report.mode, reason: report.reason, iteration: report.iteration }
648
+ });
649
+ }
650
+ await this.#options.explicit(from ? { ...call, count: left, args: (a, b) => call.args(a + from, b + from) } : call);
651
+ this.#judge(performance.now() - dispatched, left);
652
+ return done('explicit', 'explicit-runner');
653
+ }
654
+ async close() {
655
+ if (this.#closed)
656
+ return;
657
+ this.#closed = true;
658
+ await this.#window?.close();
659
+ await this.#folio?.close();
660
+ if (this.#stream) {
661
+ this.#stream.pool.close();
662
+ await Promise.all(this.#stream.workers.map((w) => w.terminate()));
663
+ }
664
+ }
665
+ }
666
+ const workerUrl = () => new URL(`./router-worker.${import.meta.url.endsWith('.ts') ? 'ts' : 'js'}`, import.meta.url);
667
+ export const openRouter = Router.open;