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