@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
@@ -0,0 +1,763 @@
1
+ import { foldExact, gfApply, gfMul, mulberry } from "./affine.js";
2
+ import { chunkRanges } from "./fold.js";
3
+ import { serveTasks } from "./tasks.js";
4
+ /** Where the probe puts the context and the data in the kernel's linear memory. */
5
+ export const CONTEXT_ADDRESS = 1 << 19;
6
+ export const DATA_ADDRESS = 1 << 20;
7
+ const PAGE = 65536;
8
+ const MAX_WINDOW = 256;
9
+ /** One private instance of a context kernel: put and get bytes, call it, count the calls. */
10
+ export class ContextKernel {
11
+ #fn;
12
+ #memory;
13
+ #image;
14
+ arity;
15
+ entry;
16
+ calls = 0;
17
+ constructor(module, entry) {
18
+ this.entry = entry;
19
+ const compiled = module instanceof WebAssembly.Module
20
+ ? module
21
+ : new WebAssembly.Module(module);
22
+ if (WebAssembly.Module.imports(compiled).length)
23
+ throw new Error('the kernel imports something; only freestanding modules are probed');
24
+ const exports = new WebAssembly.Instance(compiled, {}).exports;
25
+ const fn = exports[entry];
26
+ const memory = exports.memory;
27
+ if (typeof fn !== 'function')
28
+ throw new Error(`no function export ${entry}`);
29
+ if (!(memory instanceof WebAssembly.Memory))
30
+ throw new Error('the kernel exports no memory');
31
+ this.#fn = fn;
32
+ this.#memory = memory;
33
+ this.#image = new Uint8Array(memory.buffer).slice();
34
+ this.arity = fn.length;
35
+ }
36
+ #ensure(end) {
37
+ const have = this.#memory.buffer.byteLength;
38
+ if (have < end)
39
+ this.#memory.grow(Math.ceil((end - have) / PAGE));
40
+ }
41
+ /** Puts the memory back to what it was after instantiation. */
42
+ restore() {
43
+ new Uint8Array(this.#memory.buffer).set(this.#image);
44
+ }
45
+ put(at, bytes) {
46
+ this.#ensure(at + bytes.length);
47
+ new Uint8Array(this.#memory.buffer, at, bytes.length).set(bytes);
48
+ }
49
+ get(at, length) {
50
+ return new Uint8Array(this.#memory.buffer, at, length).slice();
51
+ }
52
+ raw(args) {
53
+ this.calls++;
54
+ return this.#fn(...args);
55
+ }
56
+ /** Copies of every byte of memory outside the given ranges, for the hidden state check. */
57
+ outside(ranges) {
58
+ const all = new Uint8Array(this.#memory.buffer).slice();
59
+ for (const [from, to] of ranges)
60
+ all.fill(0, from, Math.min(to, all.length));
61
+ return all;
62
+ }
63
+ /**
64
+ * One call: the context image at the context address, the data at the data address. Returns the
65
+ * context window afterwards, or undefined when the kernel traps.
66
+ */
67
+ run(layout, image, data) {
68
+ this.put(CONTEXT_ADDRESS, image);
69
+ this.put(DATA_ADDRESS, data);
70
+ const args = [0, 0, 0];
71
+ args[layout.ctx] = CONTEXT_ADDRESS;
72
+ args[layout.ptr] = DATA_ADDRESS;
73
+ args[layout.len] = data.length;
74
+ try {
75
+ this.raw(args);
76
+ }
77
+ catch (error) {
78
+ if (error instanceof WebAssembly.RuntimeError)
79
+ return undefined;
80
+ throw error;
81
+ }
82
+ return this.get(CONTEXT_ADDRESS, layout.window);
83
+ }
84
+ }
85
+ /**
86
+ * The context image after one call of an init function, for a subject whose state starts from
87
+ * something other than zeros. `args` gets the context address; `inputs` is placed at the data
88
+ * address first, for init functions that take a key or an IV.
89
+ */
90
+ export function initialContext(module, entry, args, inputs = new Uint8Array(0), window = MAX_WINDOW) {
91
+ const kernel = new ContextKernel(module, entry);
92
+ kernel.put(DATA_ADDRESS, inputs);
93
+ kernel.raw(args(CONTEXT_ADDRESS, DATA_ADDRESS));
94
+ return kernel.get(CONTEXT_ADDRESS, window);
95
+ }
96
+ /** A subject whose state is the whole window, for chains with no model. */
97
+ export function contextSubject(module, entry, context, layout = {}) {
98
+ const window = layout.window ?? context.length;
99
+ const image = new Uint8Array(window);
100
+ image.set(context.subarray(0, window));
101
+ return {
102
+ module,
103
+ layout: { entry, ctx: 0, ptr: 1, len: 2, window, ...layout },
104
+ context: image,
105
+ state: Array.from({ length: window }, (_, i) => i)
106
+ };
107
+ }
108
+ /** The subject a model describes, for `serveContext`. */
109
+ export function modelSubject(module, model) {
110
+ return { module, layout: model.layout, context: model.context, state: model.state };
111
+ }
112
+ export const pick = (image, offsets) => Uint8Array.from(offsets, (o) => image[o]);
113
+ export function toHex(bytes) {
114
+ let out = '';
115
+ for (const b of bytes)
116
+ out += (b < 16 ? '0' : '') + b.toString(16);
117
+ return out;
118
+ }
119
+ export function fromHex(hex) {
120
+ const out = new Uint8Array(hex.length / 2);
121
+ for (let i = 0; i < out.length; i++)
122
+ out[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
123
+ return out;
124
+ }
125
+ export const bytesEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
126
+ const wordMask = (f) => (1n << BigInt(f.bits)) - 1n;
127
+ function toWords(f, bytes) {
128
+ const out = [];
129
+ for (let w = 0; w < f.words; w++) {
130
+ let value = 0n;
131
+ for (let t = 0; t < f.wordBytes; t++) {
132
+ const shift = f.endian === 'le' ? t : f.wordBytes - 1 - t;
133
+ value |= BigInt(bytes[w * f.wordBytes + t]) << BigInt(8 * shift);
134
+ }
135
+ out.push(value);
136
+ }
137
+ return out;
138
+ }
139
+ function fromWords(f, words) {
140
+ const out = new Uint8Array(f.words * f.wordBytes);
141
+ for (let w = 0; w < f.words; w++)
142
+ for (let t = 0; t < f.wordBytes; t++) {
143
+ const shift = f.endian === 'le' ? t : f.wordBytes - 1 - t;
144
+ out[w * f.wordBytes + t] = Number((words[w] >> BigInt(8 * shift)) & 255n);
145
+ }
146
+ return out;
147
+ }
148
+ const plus = (f, a, b) => f.ring === 'gf2' ? [a[0] ^ b[0]] : a.map((x, i) => (x + b[i]) & wordMask(f));
149
+ const minus = (f, a, b) => f.ring === 'gf2' ? [a[0] ^ b[0]] : a.map((x, i) => BigInt.asUintN(f.bits, x - b[i]));
150
+ function applyOperator(f, op, v) {
151
+ if (f.ring === 'gf2')
152
+ return [gfApply(op, v[0])];
153
+ return op.map((row) => BigInt.asUintN(f.bits, row.reduce((sum, m, j) => sum + m * v[j], 0n)));
154
+ }
155
+ function identity(f) {
156
+ if (f.ring === 'gf2')
157
+ return Array.from({ length: f.bits }, (_, k) => 1n << BigInt(k));
158
+ return Array.from({ length: f.words }, (_, i) => Array.from({ length: f.words }, (_, j) => (i === j ? 1n : 0n)));
159
+ }
160
+ function multiply(f, a, b) {
161
+ if (f.ring === 'gf2')
162
+ return gfMul(a, b);
163
+ const x = a;
164
+ const y = b;
165
+ return x.map((row) => y[0].map((_, j) => BigInt.asUintN(f.bits, row.reduce((sum, m, l) => sum + m * y[l][j], 0n))));
166
+ }
167
+ const powers = new WeakMap();
168
+ /** The operator for `units` align-byte steps, by repeated squaring, cached per length. */
169
+ function powerOf(f, units) {
170
+ let cache = powers.get(f);
171
+ if (!cache) {
172
+ cache = { squares: [f.operator], byUnits: new Map() };
173
+ powers.set(f, cache);
174
+ }
175
+ const cached = cache.byUnits.get(units);
176
+ if (cached)
177
+ return cached;
178
+ let result = identity(f);
179
+ for (let n = units, k = 0; n > 0; n = Math.floor(n / 2), k++) {
180
+ if (!cache.squares[k])
181
+ cache.squares[k] = multiply(f, cache.squares[k - 1], cache.squares[k - 1]);
182
+ if (n % 2 === 1)
183
+ result = multiply(f, cache.squares[k], result);
184
+ }
185
+ cache.byUnits.set(units, result);
186
+ return result;
187
+ }
188
+ /**
189
+ * The state vector after a chunk of `length` bytes from `start`, given `offset`, the state vector
190
+ * after the same chunk from zero: A(length) start + offset, factor by factor. `length` must be a
191
+ * multiple of `model.align`.
192
+ */
193
+ export function predictState(model, start, length, offset) {
194
+ if (!Number.isSafeInteger(length) || length < 0 || length % model.align)
195
+ throw new RangeError(`length ${length} is not a multiple of ${model.align}`);
196
+ const out = new Uint8Array(model.state.length);
197
+ for (const f of model.factors) {
198
+ const v = toWords(f, pick(start, f.slots));
199
+ const o = toWords(f, pick(offset, f.slots));
200
+ const next = plus(f, applyOperator(f, powerOf(f, length / model.align), v), o);
201
+ fromWords(f, next).forEach((b, k) => (out[f.slots[k]] = b));
202
+ }
203
+ return out;
204
+ }
205
+ // #endregion
206
+ class StateTrap extends Error {
207
+ constructor() {
208
+ super('the kernel trapped on a random state value');
209
+ }
210
+ }
211
+ function shapesFor(offsets) {
212
+ const g = offsets.length;
213
+ const shapes = [
214
+ { ring: 'gf2', wordBytes: g, endian: 'le', words: 1, label: `GF(2)^${8 * g}` }
215
+ ];
216
+ const contiguous = offsets.every((o, i) => i === 0 || o === offsets[i - 1] + 1);
217
+ if (!contiguous)
218
+ return shapes;
219
+ if (g % 4 === 0)
220
+ shapes.push({
221
+ ring: 'z2w',
222
+ wordBytes: 4,
223
+ endian: 'le',
224
+ words: g / 4,
225
+ label: `(Z/2^32)^${g / 4}`
226
+ });
227
+ if (g <= 32) {
228
+ if (g !== 4)
229
+ shapes.push({
230
+ ring: 'z2w',
231
+ wordBytes: g,
232
+ endian: 'le',
233
+ words: 1,
234
+ label: `Z/2^${8 * g} little endian`
235
+ });
236
+ shapes.push({
237
+ ring: 'z2w',
238
+ wordBytes: g,
239
+ endian: 'be',
240
+ words: 1,
241
+ label: `Z/2^${8 * g} big endian`
242
+ });
243
+ }
244
+ return shapes;
245
+ }
246
+ /**
247
+ * Probes `entry`, a function (context pointer, data pointer, length) that updates a context struct
248
+ * in place, and decides by trial what its state is and whether the state transition is affine.
249
+ *
250
+ * It finds the parameter order under which the call composes over a split, then, from contexts the
251
+ * function itself produced, flips each of the first `window` context bytes and records which bytes
252
+ * the result depends on. State is the set of bytes a call both reads and writes. A byte that is read
253
+ * and never written is a parameter and stays at its value in `options.context`. State bytes that
254
+ * do not depend on each other form independent factors. Each factor is tested over GF(2) and over
255
+ * Z/2^bits (as one little or big endian integer, or as 32-bit words coupled by a matrix) with the
256
+ * five checks of `probeAffine`, with the other factors set to random bytes in every call, which
257
+ * tests that they do not interact. A factor that is affine in no ring refuses the whole context.
258
+ *
259
+ * A pass is evidence on the sampled inputs only. It cannot see state outside the window, a byte
260
+ * that is read only on rare inputs, or behaviour above the probed lengths. `foldState` in exact
261
+ * mode does not trust the model, but its guarantee needs the state to be complete.
262
+ */
263
+ export function probeState(module, entry, options = {}) {
264
+ const trials = options.trials ?? 32;
265
+ const align = options.align ?? 1;
266
+ const window = options.window ?? MAX_WINDOW;
267
+ if (!Number.isSafeInteger(trials) || trials < 1)
268
+ throw new RangeError('invalid trial count');
269
+ if (!Number.isSafeInteger(align) || align < 1)
270
+ throw new RangeError('invalid alignment');
271
+ if (!Number.isSafeInteger(window) || window < 1 || window > MAX_WINDOW)
272
+ throw new RangeError(`the window is 1 to ${MAX_WINDOW} bytes`);
273
+ const template = new Uint8Array(window);
274
+ if (options.context) {
275
+ if (options.context.length > window)
276
+ throw new RangeError('the context is larger than the window');
277
+ template.set(options.context);
278
+ }
279
+ const kernel = new ContextKernel(module, entry);
280
+ const checks = [];
281
+ const refuse = (reason) => ({
282
+ kind: 'refusal',
283
+ reason,
284
+ checks,
285
+ calls: kernel.calls
286
+ });
287
+ try {
288
+ return probe(kernel, template, checks, refuse, trials, align, options.seed ?? 0x9e3779b9);
289
+ }
290
+ catch (error) {
291
+ return refuse(`the kernel trapped: ${error.message}`);
292
+ }
293
+ }
294
+ function probe(kernel, template, checks, refuse, trials, align, seed) {
295
+ const window = template.length;
296
+ if (kernel.arity !== 3)
297
+ return refuse(`expected 3 parameters, found ${kernel.arity}`);
298
+ try {
299
+ kernel.raw([0, 0, 0]);
300
+ }
301
+ catch (error) {
302
+ if (error instanceof TypeError)
303
+ return refuse('the parameters are not all i32');
304
+ }
305
+ const rng = mulberry(seed);
306
+ const bytes = (length) => {
307
+ const out = new Uint8Array(length);
308
+ for (let i = 0; i < length; i += 4) {
309
+ const value = rng();
310
+ for (let k = 0; k < 4 && i + k < length; k++)
311
+ out[i + k] = (value >>> (8 * k)) & 255;
312
+ }
313
+ return out;
314
+ };
315
+ const units = (most) => align * (1 + (rng() % Math.max(1, Math.floor(most / align))));
316
+ const rounded = (length) => Math.ceil(length / align) * align;
317
+ // roles: the order of (context, pointer, data length) under which the call composes over a split
318
+ const orders = [
319
+ [0, 1, 2],
320
+ [0, 2, 1],
321
+ [1, 0, 2],
322
+ [1, 2, 0],
323
+ [2, 0, 1],
324
+ [2, 1, 0]
325
+ ];
326
+ const streaming = (layout) => {
327
+ try {
328
+ const first = kernel.run(layout, template, bytes(units(64)));
329
+ if (!first || bytesEqual(first, template))
330
+ return false;
331
+ for (let i = 0; i < 6; i++) {
332
+ const a = units(100);
333
+ const b = units(100);
334
+ const data = bytes(a + b);
335
+ const whole = kernel.run(layout, template, data);
336
+ const head = kernel.run(layout, template, data.subarray(0, a));
337
+ const split = head && kernel.run(layout, head, data.subarray(a));
338
+ if (!whole || !split)
339
+ return false;
340
+ // dead bytes (a partial block buffer) may differ, so compare after one more call
341
+ const more = bytes(rounded(130));
342
+ const x = kernel.run(layout, whole, more);
343
+ const y = kernel.run(layout, split, more);
344
+ if (!x || !y || !bytesEqual(x, y))
345
+ return false;
346
+ }
347
+ return true;
348
+ }
349
+ catch {
350
+ return false;
351
+ }
352
+ };
353
+ let layout;
354
+ for (const [ctx, ptr, len] of orders) {
355
+ const candidate = { entry: kernel.entry, ctx, ptr, len, window };
356
+ kernel.restore();
357
+ if (streaming(candidate)) {
358
+ layout = candidate;
359
+ break;
360
+ }
361
+ }
362
+ if (!layout) {
363
+ kernel.restore();
364
+ return refuse('no parameter order is a streaming update over (context, pointer, length)');
365
+ }
366
+ const lay = layout;
367
+ // hidden state: memory outside the context and the data must be the same after two identical calls
368
+ {
369
+ const data = bytes(units(200));
370
+ const ranges = [
371
+ [CONTEXT_ADDRESS, CONTEXT_ADDRESS + window],
372
+ [DATA_ADDRESS, DATA_ADDRESS + data.length]
373
+ ];
374
+ kernel.run(layout, template, data);
375
+ kernel.run(layout, template, data);
376
+ const second = kernel.outside(ranges);
377
+ kernel.run(layout, template, data);
378
+ const third = kernel.outside(ranges);
379
+ if (!bytesEqual(second, third))
380
+ return refuse('memory outside the context changed between two identical calls');
381
+ }
382
+ // discovery: which context bytes a call writes and which bytes the result depends on. The bases
383
+ // are contexts the function produced, plus all zeros and all ones, which carry chains reach.
384
+ const bases = [template];
385
+ for (let i = 1; i < 16; i++) {
386
+ const next = kernel.run(lay, bases[i - 1], bytes(units(150)));
387
+ if (next)
388
+ bases.push(next);
389
+ }
390
+ for (const fill of [0x00, 0xff])
391
+ if (kernel.run(lay, new Uint8Array(window).fill(fill), bytes(align)))
392
+ bases.push(new Uint8Array(window).fill(fill));
393
+ const lengths = [1, 2, 3, 5, 7, 8, 9, 12, 16, 17, 31, 33, 64, 65, 100, 130];
394
+ const writes = new Set();
395
+ const flips = [];
396
+ bases.forEach((base, b) => {
397
+ const data = bytes(align * lengths[b % lengths.length]);
398
+ const out = kernel.run(lay, base, data);
399
+ if (!out)
400
+ return;
401
+ for (let j = 0; j < window; j++)
402
+ if (base[j] !== out[j])
403
+ writes.add(j);
404
+ for (let i = 0; i < window; i++)
405
+ for (const value of [0x00, 0xff, rng() & 255, rng() & 255]) {
406
+ const image = Uint8Array.from(base);
407
+ image[i] = value === base[i] ? value ^ 0x5a : value;
408
+ flips.push({ i, out, after: kernel.run(lay, image, data) });
409
+ }
410
+ });
411
+ const reads = new Set();
412
+ const trapSensitive = new Set();
413
+ const depends = new Map();
414
+ for (const { i, out, after } of flips) {
415
+ if (!after) {
416
+ reads.add(i);
417
+ trapSensitive.add(i);
418
+ continue;
419
+ }
420
+ for (const j of writes) {
421
+ if (j === i ? after[i] === out[i] : after[j] === out[j])
422
+ continue;
423
+ reads.add(i);
424
+ if (!depends.has(i))
425
+ depends.set(i, new Set());
426
+ depends.get(i).add(j);
427
+ }
428
+ }
429
+ const state = [...writes].filter((i) => reads.has(i)).sort((a, b) => a - b);
430
+ const params = [...reads].filter((i) => !writes.has(i)).sort((a, b) => a - b);
431
+ const scratch = [...writes].filter((i) => !reads.has(i)).sort((a, b) => a - b);
432
+ if (!state.length)
433
+ return refuse('no byte of the context is both read and written, so nothing is carried');
434
+ // factors: state bytes that depend on each other, or that trap when changed, share a factor
435
+ const parent = new Map(state.map((i) => [i, i]));
436
+ const find = (i) => (parent.get(i) === i ? i : find(parent.get(i)));
437
+ const join = (a, b) => parent.set(find(a), find(b));
438
+ for (const i of state)
439
+ for (const j of depends.get(i) ?? [])
440
+ if (parent.has(j))
441
+ join(i, j);
442
+ const trapped = state.filter((i) => trapSensitive.has(i));
443
+ for (const i of trapped)
444
+ join(i, trapped[0]);
445
+ const groups = new Map();
446
+ for (const i of state) {
447
+ const root = find(i);
448
+ groups.set(root, [...(groups.get(root) ?? []), i]);
449
+ }
450
+ const sets = [...groups.values()].sort((a, b) => a[0] - b[0]);
451
+ // a context with invariants traps on random state values; additivity of valid contexts that
452
+ // share their control bytes (the same call lengths) is the evidence left
453
+ const rejectsRandomState = () => {
454
+ for (let i = 0; i < trials; i++) {
455
+ const a = units(130);
456
+ const made = [0, 1, 2].map(() => kernel.run(lay, template, bytes(a)));
457
+ if (made.some((m) => !m))
458
+ break;
459
+ const [p, q, r] = made;
460
+ const mixed = p.map((v, k) => v ^ q[k] ^ r[k]);
461
+ const x = bytes(units(130));
462
+ const outs = [p, q, r, mixed].map((m) => kernel.run(lay, m, x));
463
+ if (outs.some((o) => !o))
464
+ break;
465
+ if (state.some((k) => outs[3][k] !== (outs[0][k] ^ outs[1][k] ^ outs[2][k]))) {
466
+ checks.push({
467
+ ring: 'gf2',
468
+ name: 'additivity on reachable states',
469
+ trials: i + 1,
470
+ passed: false,
471
+ factor: -1,
472
+ shape: 'reachable'
473
+ });
474
+ return `the context rejects random state values and is not additive over GF(2) on reachable states (failed at trial ${i + 1})`;
475
+ }
476
+ }
477
+ return 'the context rejects random state values, so affinity over the state space cannot be shown';
478
+ };
479
+ const factorize = () => {
480
+ const factors = [];
481
+ for (const [index, offsets] of sets.entries()) {
482
+ const g = offsets.length;
483
+ const others = state.filter((i) => !offsets.includes(i));
484
+ const zero = new Uint8Array(g);
485
+ const T = (s, x) => {
486
+ const image = Uint8Array.from(template);
487
+ for (const o of others)
488
+ image[o] = rng() & 255;
489
+ offsets.forEach((o, k) => (image[o] = s[k]));
490
+ const out = kernel.run(lay, image, x);
491
+ if (!out)
492
+ throw new StateTrap();
493
+ return pick(out, offsets);
494
+ };
495
+ const failures = [];
496
+ let found;
497
+ for (const shape of shapesFor(offsets)) {
498
+ const f = {
499
+ ring: shape.ring,
500
+ offsets,
501
+ slots: offsets.map((o) => state.indexOf(o)),
502
+ wordBytes: shape.wordBytes,
503
+ endian: shape.endian,
504
+ words: shape.words,
505
+ bits: shape.ring === 'gf2' ? 8 * g : 8 * shape.wordBytes,
506
+ operator: []
507
+ };
508
+ const W = (b) => toWords(f, b);
509
+ const B = (w) => fromWords(f, w);
510
+ const same = (a, b) => a.every((v, i) => v === b[i]);
511
+ const run = (name, count, body) => {
512
+ for (let i = 0; i < count; i++)
513
+ if (!body(i)) {
514
+ checks.push({
515
+ ring: f.ring,
516
+ name,
517
+ trials: i + 1,
518
+ passed: false,
519
+ factor: index,
520
+ shape: shape.label
521
+ });
522
+ return false;
523
+ }
524
+ checks.push({
525
+ ring: f.ring,
526
+ name,
527
+ trials: count,
528
+ passed: true,
529
+ factor: index,
530
+ shape: shape.label
531
+ });
532
+ return true;
533
+ };
534
+ const rand = () => bytes(g);
535
+ const additive = run('additivity of the state part', trials, () => {
536
+ const x = bytes(units(4096));
537
+ const s1 = rand();
538
+ const s2 = rand();
539
+ const lhs = W(T(B(plus(f, W(s1), W(s2))), x));
540
+ const rhs = minus(f, plus(f, W(T(s1, x)), W(T(s2, x))), W(T(zero, x)));
541
+ return same(lhs, rhs);
542
+ });
543
+ if (!additive) {
544
+ failures.push(`${shape.label}: additivity`);
545
+ continue;
546
+ }
547
+ const ux = bytes(align);
548
+ const base = W(T(zero, ux));
549
+ if (f.ring === 'gf2') {
550
+ f.operator = Array.from({ length: f.bits }, (_, k) => minus(f, W(T(B([1n << BigInt(k)]), ux)), base)[0]);
551
+ }
552
+ else {
553
+ const columns = Array.from({ length: f.words }, (_, j) => {
554
+ const e = Array.from({ length: f.words }, (_, i) => (i === j ? 1n : 0n));
555
+ return minus(f, W(T(B(e), ux)), base);
556
+ });
557
+ f.operator = Array.from({ length: f.words }, (_, i) => columns.map((column) => column[i]));
558
+ }
559
+ const independent = run('data independence of the state part', trials, () => {
560
+ const length = units(4096);
561
+ const x = bytes(length);
562
+ const y = bytes(length);
563
+ const s = rand();
564
+ return same(minus(f, W(T(s, x)), W(T(zero, x))), minus(f, W(T(s, y)), W(T(zero, y))));
565
+ });
566
+ const homogeneous = () => {
567
+ let tried = 0;
568
+ for (const length of [1, 2, 7, 64, 1000, 65537].map(rounded)) {
569
+ const x = bytes(length);
570
+ for (let i = 0; i < 4; i++, tried++) {
571
+ const s = rand();
572
+ const want = applyOperator(f, powerOf(f, length / align), W(s));
573
+ if (!same(minus(f, W(T(s, x)), W(T(zero, x))), want)) {
574
+ checks.push({
575
+ ring: f.ring,
576
+ name: 'homogeneity',
577
+ trials: tried + 1,
578
+ passed: false,
579
+ factor: index,
580
+ shape: shape.label
581
+ });
582
+ return false;
583
+ }
584
+ }
585
+ }
586
+ checks.push({
587
+ ring: f.ring,
588
+ name: 'homogeneity',
589
+ trials: tried,
590
+ passed: true,
591
+ factor: index,
592
+ shape: shape.label
593
+ });
594
+ return true;
595
+ };
596
+ const additiveData = () => run('additivity of the data part', trials, () => {
597
+ const a = units(2048);
598
+ const b = units(2048);
599
+ const x = bytes(a + b);
600
+ const whole = W(T(zero, x));
601
+ const head = W(T(zero, x.subarray(0, a)));
602
+ const tail = W(T(zero, x.subarray(a)));
603
+ return same(whole, plus(f, applyOperator(f, powerOf(f, b / align), head), tail));
604
+ });
605
+ const streamed = () => run('streaming composition', trials, () => {
606
+ const a = units(2048);
607
+ const b = units(2048);
608
+ const x = bytes(a + b);
609
+ const s = rand();
610
+ return same(W(T(s, x)), W(T(T(s, x.subarray(0, a)), x.subarray(a))));
611
+ });
612
+ if (independent && homogeneous() && additiveData() && streamed()) {
613
+ found = f;
614
+ break;
615
+ }
616
+ const failed = checks.filter((c) => c.factor === index && c.shape === shape.label && !c.passed)[0];
617
+ failures.push(`${shape.label}: ${failed.name}`);
618
+ }
619
+ if (!found)
620
+ return refuse(`state bytes ${offsets[0]} to ${offsets[g - 1]} (${g} bytes) are affine in no ring: ${failures.join('; ')}`);
621
+ factors.push(found);
622
+ }
623
+ return factors;
624
+ };
625
+ let factors;
626
+ try {
627
+ factors = factorize();
628
+ }
629
+ catch (error) {
630
+ if (!(error instanceof StateTrap))
631
+ throw error;
632
+ return refuse(rejectsRandomState());
633
+ }
634
+ if (!Array.isArray(factors))
635
+ return factors;
636
+ return {
637
+ kind: 'state',
638
+ layout,
639
+ context: template,
640
+ state,
641
+ params,
642
+ scratch,
643
+ factors,
644
+ align,
645
+ checks,
646
+ calls: kernel.calls
647
+ };
648
+ }
649
+ /**
650
+ * Runs on the worker side. Answers `ctx:<hex state>` with the end state bytes, and
651
+ * `ctxrec:<hex state>:<step>` with the state after every `step` bytes, concatenated, the last one
652
+ * being the end state. The context image is rebuilt from `subject.context` for every task.
653
+ */
654
+ export function serveContext(link, subject) {
655
+ const kernel = new ContextKernel(subject.module, subject.layout.entry);
656
+ const image = (state) => {
657
+ const out = Uint8Array.from(subject.context);
658
+ subject.state.forEach((o, k) => (out[o] = state[k]));
659
+ return out;
660
+ };
661
+ const step = (state, data) => {
662
+ const out = kernel.run(subject.layout, image(state), data);
663
+ if (!out)
664
+ throw new Error('the kernel trapped');
665
+ return pick(out, subject.state);
666
+ };
667
+ serveTasks(link, (name, input) => {
668
+ const [task, hex, size] = name.split(':');
669
+ if (!hex || (task !== 'ctx' && task !== 'ctxrec'))
670
+ throw new Error(`unknown task ${name}`);
671
+ const data = input;
672
+ let state = fromHex(hex);
673
+ if (task === 'ctx')
674
+ return step(state, data);
675
+ const each = Number(size);
676
+ if (!Number.isSafeInteger(each) || each < 1)
677
+ throw new Error(`invalid step in ${name}`);
678
+ const out = new Uint8Array(Math.ceil(data.length / each) * subject.state.length);
679
+ for (let at = 0, k = 0; at < data.length; at += each, k++) {
680
+ state = step(state, data.subarray(at, at + each));
681
+ out.set(state, k * subject.state.length);
682
+ }
683
+ return out;
684
+ });
685
+ }
686
+ /** The serial reference: one call over all the bytes on a private instance. */
687
+ export function stateSerial(subject) {
688
+ const kernel = new ContextKernel(subject.module, subject.layout.entry);
689
+ return (input, state = pick(subject.context, subject.state)) => {
690
+ const image = Uint8Array.from(subject.context);
691
+ subject.state.forEach((o, k) => (image[o] = state[k]));
692
+ const out = kernel.run(subject.layout, image, input);
693
+ if (!out)
694
+ throw new Error('the kernel trapped');
695
+ return pick(out, subject.state);
696
+ };
697
+ }
698
+ /**
699
+ * `foldAffine` exact mode for a state vector in the context: pass 1 runs every chunk but the last
700
+ * from the zero state, the model turns the offsets into predicted start vectors, pass 2 runs
701
+ * chunks 1 to n-1 from them in workers started with `serveContext`, and each end vector is compared
702
+ * with the next predicted start. All equal: the last end vector is the serial state, by induction,
703
+ * whatever the model got wrong. The first difference hands the rest to one serial task.
704
+ *
705
+ * The result is the state bytes only. Bytes a call writes and does not read (`model.scratch`, and
706
+ * the data a call changes in place) are not returned.
707
+ */
708
+ export function foldState(pool, input, model, options = {}) {
709
+ const initial = options.initial ?? pick(model.context, model.state);
710
+ if (initial.length !== model.state.length)
711
+ throw new RangeError('invalid initial state length');
712
+ if (!input.length)
713
+ return {
714
+ state: initial,
715
+ chunks: 0,
716
+ tasks: 0,
717
+ validated: 0,
718
+ mismatchAt: -1,
719
+ fallbackBytes: 0
720
+ };
721
+ const chunks = options.chunks ?? chunkRanges(input.length, pool.width, model.align);
722
+ let at = 0;
723
+ chunks.forEach((chunk, index) => {
724
+ if (chunk.start !== at || chunk.end <= chunk.start)
725
+ throw new RangeError(`chunk ${index} is not contiguous`);
726
+ if (index < chunks.length - 1 && chunk.end % model.align !== 0)
727
+ throw new RangeError(`chunk ${index} ends at ${chunk.end}, not a multiple of ${model.align}`);
728
+ at = chunk.end;
729
+ });
730
+ if (at !== input.length)
731
+ throw new RangeError(`chunks cover ${at} of ${input.length} bytes`);
732
+ let tasks = 0;
733
+ const submit = (start, from, to) => {
734
+ tasks++;
735
+ return pool.submit(`ctx:${start}`, input.slice(from, to));
736
+ };
737
+ const endOf = (handle) => toHex(pool.join(handle).bytes);
738
+ if (chunks.length === 1)
739
+ return {
740
+ state: fromHex(endOf(submit(toHex(initial), 0, input.length))),
741
+ chunks: 1,
742
+ tasks,
743
+ validated: 0,
744
+ mismatchAt: -1,
745
+ fallbackBytes: 0
746
+ };
747
+ const hooks = {
748
+ zero: toHex(new Uint8Array(model.state.length)),
749
+ submit,
750
+ end: endOf,
751
+ predict: (start, length, offset) => toHex(predictState(model, fromHex(start), length, fromHex(offset))),
752
+ equal: (a, b) => a === b
753
+ };
754
+ const outcome = foldExact(chunks, input.length, toHex(initial), hooks);
755
+ return {
756
+ state: fromHex(outcome.state),
757
+ chunks: chunks.length,
758
+ tasks,
759
+ validated: outcome.validated,
760
+ mismatchAt: outcome.mismatchAt,
761
+ fallbackBytes: outcome.fallbackBytes
762
+ };
763
+ }