@gmitch215/folio 1.1.0 → 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 (122) hide show
  1. package/README.md +78 -810
  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} +5 -5
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +3 -13
  15. package/dist/{extract.js → execution/extract.js} +7 -8
  16. package/dist/{fold.d.ts → execution/fold.d.ts} +15 -3
  17. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  18. package/dist/execution/types.d.ts +221 -0
  19. package/dist/{affine-state.d.ts → folds/affine-state.d.ts} +18 -47
  20. package/dist/{affine-state.js → folds/affine-state.js} +18 -44
  21. package/dist/{affine.d.ts → folds/affine.d.ts} +12 -24
  22. package/dist/{affine.js → folds/affine.js} +8 -17
  23. package/dist/{boundaries.d.ts → folds/boundaries.d.ts} +7 -18
  24. package/dist/{boundaries.js → folds/boundaries.js} +5 -13
  25. package/dist/{certified.d.ts → folds/certified.d.ts} +13 -24
  26. package/dist/{certified.js → folds/certified.js} +12 -26
  27. package/dist/{certify.d.ts → folds/certify.d.ts} +11 -22
  28. package/dist/{certify.js → folds/certify.js} +24 -41
  29. package/dist/{memo.d.ts → footprints/memo.d.ts} +8 -33
  30. package/dist/{memo.js → footprints/memo.js} +8 -2
  31. package/dist/{ranges.js → footprints/ranges.js} +1 -1
  32. package/dist/{read-scan.js → footprints/read-scan.js} +1 -1
  33. package/dist/{read-windows.d.ts → footprints/read-windows.d.ts} +6 -32
  34. package/dist/{read-windows.js → footprints/read-windows.js} +8 -7
  35. package/dist/index.d.ts +16 -4
  36. package/dist/index.js +14 -2
  37. package/dist/{iteration-admission.d.ts → iteration/admission.d.ts} +2 -38
  38. package/dist/{iteration.d.ts → iteration/index.d.ts} +8 -98
  39. package/dist/{iteration.js → iteration/index.js} +28 -28
  40. package/dist/{inline.js → iteration/inline.js} +2 -9
  41. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +3 -3
  42. package/dist/{iteration-owner.js → iteration/owner.js} +4 -3
  43. package/dist/{iteration-worker.js → iteration/worker.js} +3 -3
  44. package/dist/{managed.d.ts → managed/index.d.ts} +3 -3
  45. package/dist/{managed.js → managed/index.js} +7 -9
  46. package/dist/managed/outbox.d.ts +128 -0
  47. package/dist/managed/outbox.js +156 -0
  48. package/dist/managed/pool.d.ts +221 -0
  49. package/dist/managed/pool.js +310 -0
  50. package/dist/managed/tasks.d.ts +154 -0
  51. package/dist/managed/tasks.js +183 -0
  52. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  53. package/dist/{bake.js → memory/bake.js} +9 -7
  54. package/dist/memory/continuation.d.ts +141 -0
  55. package/dist/memory/continuation.js +495 -0
  56. package/dist/memory/elastic-peer.d.ts +20 -0
  57. package/dist/memory/elastic-peer.js +39 -0
  58. package/dist/memory/elastic-sql.d.ts +11 -0
  59. package/dist/memory/elastic-sql.js +35 -0
  60. package/dist/memory/elastic.d.ts +130 -0
  61. package/dist/memory/elastic.js +475 -0
  62. package/dist/memory/growth-governor.d.ts +16 -0
  63. package/dist/memory/growth-governor.js +42 -0
  64. package/dist/memory/imports.d.ts +10 -0
  65. package/dist/memory/imports.js +89 -0
  66. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +1 -1
  67. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  68. package/dist/memory.d.ts +5 -10
  69. package/dist/memory.js +5 -89
  70. package/dist/{context.d.ts → node/context.d.ts} +1 -1
  71. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  72. package/dist/{host.js → node/host.js} +2 -2
  73. package/dist/{node.d.ts → node/index.d.ts} +4 -49
  74. package/dist/{node.js → node/index.js} +16 -17
  75. package/dist/{tasks.d.ts → node/tasks.d.ts} +2 -13
  76. package/dist/{worker.js → node/worker.js} +2 -2
  77. package/dist/{ownership.js → ownership/index.js} +7 -10
  78. package/dist/{ownership-redirect.d.ts → ownership/redirect.d.ts} +2 -2
  79. package/dist/{ownership-redirect.js → ownership/redirect.js} +2 -2
  80. package/dist/{ownership-slices.d.ts → ownership/slices.d.ts} +3 -3
  81. package/dist/{ownership-slices.js → ownership/slices.js} +3 -3
  82. package/dist/{frames.d.ts → remote/frames.d.ts} +1 -1
  83. package/dist/{frames.js → remote/frames.js} +2 -2
  84. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  85. package/dist/{remote.js → remote/index.js} +7 -2
  86. package/dist/{router.d.ts → routing/index.d.ts} +3 -3
  87. package/dist/{router.js → routing/index.js} +19 -15
  88. package/dist/{router-worker.js → routing/worker.js} +1 -1
  89. package/dist/{slices.d.ts → slices/index.d.ts} +2 -2
  90. package/dist/{slices.js → slices/index.js} +5 -5
  91. package/dist/slices/worker.d.ts +1 -0
  92. package/dist/{slices-worker.js → slices/worker.js} +2 -2
  93. package/dist/workers.d.ts +5 -0
  94. package/dist/workers.js +5 -0
  95. package/package.json +30 -80
  96. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  97. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  98. /package/dist/{fold.js → execution/fold.js} +0 -0
  99. /package/dist/{guards.js → execution/guards.js} +0 -0
  100. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  101. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  102. /package/dist/{runs.d.ts → execution/runs.d.ts} +0 -0
  103. /package/dist/{runs.js → execution/runs.js} +0 -0
  104. /package/dist/{transaction.d.ts → execution/transaction.d.ts} +0 -0
  105. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  106. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  107. /package/dist/{ranges.d.ts → footprints/ranges.d.ts} +0 -0
  108. /package/dist/{read-scan.d.ts → footprints/read-scan.d.ts} +0 -0
  109. /package/dist/{iteration-admission.js → iteration/admission.js} +0 -0
  110. /package/dist/{inline.d.ts → iteration/inline.d.ts} +0 -0
  111. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  112. /package/dist/{iteration-layout.js → memory/iteration-layout.js} +0 -0
  113. /package/dist/{lease.d.ts → memory/lease.d.ts} +0 -0
  114. /package/dist/{lease.js → memory/lease.js} +0 -0
  115. /package/dist/{pages.js → memory/pages.js} +0 -0
  116. /package/dist/{context.js → node/context.js} +0 -0
  117. /package/dist/{tasks.js → node/tasks.js} +0 -0
  118. /package/dist/{router-worker.d.ts → node/worker.d.ts} +0 -0
  119. /package/dist/{ownership.d.ts → ownership/index.d.ts} +0 -0
  120. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  121. /package/dist/{values.js → remote/values.js} +0 -0
  122. /package/dist/{slices-worker.d.ts → routing/worker.d.ts} +0 -0
@@ -4,9 +4,8 @@ const checkStep = (step) => {
4
4
  throw new RangeError('invalid step');
5
5
  };
6
6
  /**
7
- * Runs the chain serially on a private instance in the calling thread and records the state at
8
- * every `step` bytes. The copy at each boundary costs a few hundred bytes. The state returned is
9
- * the one a single call over the whole input returns when the kernel composes over a split.
7
+ * Runs the chain serially on a private instance and records the state every `step` bytes. The
8
+ * returned state equals a single call over the whole input when the kernel composes over a split.
10
9
  */
11
10
  export function recordBoundaries(subject, input, options) {
12
11
  checkStep(options.step);
@@ -28,16 +27,9 @@ export function recordBoundaries(subject, input, options) {
28
27
  return { state, log: { step: options.step, starts } };
29
28
  }
30
29
  /**
31
- * Runs every chunk of `input` in parallel from the start state the log recorded for it, on workers
32
- * started with `serveContext`, and compares each end state with the next recorded start. If all
33
- * agree, the last end state is the serial result, by induction: each chunk ran from a state that
34
- * the chunk before it ended in. Nothing about the bytes is trusted or hashed, so a log recorded for
35
- * other bytes, other lengths or another chain shows up as a difference and never changes the result.
36
- *
37
- * At the first difference the real end state of that chunk is a real state, and the rest of the
38
- * input runs serially from it in one task that records fresh boundaries; the recorded starts after
39
- * that point are dropped. An edit that changes a chunk's bytes but not its end state (a chain that
40
- * forgets) is not a difference, so the chunks after it stay valid.
30
+ * Runs each chunk in parallel from its recorded start and compares each end with the next start.
31
+ * Nothing about the bytes is hashed, so a stale log shows up as a difference and cannot change the
32
+ * result. At the first difference the rest runs serially and records fresh boundaries.
41
33
  */
42
34
  export function verifyBoundaries(pool, subject, input, log, options = {}) {
43
35
  const width = subject.state.length;
@@ -1,12 +1,12 @@
1
+ import { type FoldChunk } from '../execution/fold.ts';
2
+ import { type TaskLink, type TaskPool } from '../node/tasks.ts';
1
3
  import { type AffineLayout } from './affine.ts';
2
4
  import { type StreamCertificate } from './certify.ts';
3
- import { type FoldChunk } from './fold.ts';
4
- import { type TaskLink, type TaskPool } from './tasks.ts';
5
5
  /** The task name `serveCertified` answers: `certified:<start state in hex>`. */
6
6
  export declare const CERTIFIED_TASK = "certified";
7
- /** A module that imports one shared memory, and the bytes the executor writes into that memory first. */
7
+ /** A module with its memory imported, and the bytes its first call writes into that memory. */
8
8
  export interface SharedSubject {
9
- /** The original module with its memory imported as `env.memory` and its data segments made passive. */
9
+ /** The module with its memory imported as `env.memory` and its data segments passive. */
10
10
  bytes: Uint8Array<ArrayBuffer>;
11
11
  /** Data segments and the bytes the first call would write, in address order. */
12
12
  prefill: {
@@ -18,20 +18,13 @@ export interface SharedSubject {
18
18
  certificate: StreamCertificate;
19
19
  }
20
20
  /**
21
- * Rewrites a certified module to run on a memory the caller owns. Only the memory declaration and
22
- * the data segments change: the functions stay as they were, so the certificate still describes
23
- * them. The segments become passive so that no instance overwrites the shared bytes, and `prefill`
24
- * carries what they held, together with the table a lazily initializing module builds on its
25
- * first call, so every worker starts from the memory the proof assumed.
21
+ * Rewrites a certified module to use caller-owned memory. Only the memory import and the data
22
+ * segments change, so the certificate still describes the functions.
26
23
  */
27
24
  export declare function shareCertified(bytes: Uint8Array, certificate: StreamCertificate, pages: number): SharedSubject;
28
25
  /** Writes the subject's prefill into `memory`, which must hold `pages` pages. */
29
26
  export declare function installPrefill(subject: SharedSubject, memory: WebAssembly.Memory): void;
30
- /**
31
- * Runs on the worker side. Instantiates the shared module on the shared memory and answers
32
- * `certified:<hex state>` tasks: the input is a view of the shared memory, which is read in place,
33
- * and the output is the 8-byte little-endian end state.
34
- */
27
+ /** Worker side: runs `certified:<hex state>` tasks on the shared memory in place. */
35
28
  export declare function serveCertified(link: TaskLink, subject: {
36
29
  module: WebAssembly.Module;
37
30
  memory: WebAssembly.Memory;
@@ -49,18 +42,14 @@ export interface CertifiedFoldResult {
49
42
  tasks: number;
50
43
  }
51
44
  /**
52
- * Folds `input`, a view of `memory`, through the certified kernel on the workers of `pool`, which
53
- * must run `serveCertified` on that memory. Every chunk runs once from state zero, in place, and
54
- * the model turns the end states into the state of the serial call. Nothing is compared or run
55
- * twice: the certificate is what makes the result equal the serial one, so the input must be
56
- * clear of the memory the proof depends on, which this checks.
45
+ * Folds `input`, a view of `memory`, through the certified kernel on `pool`, whose workers must run
46
+ * `serveCertified` on that memory. Each chunk runs once from zero, in place; the certificate, not a
47
+ * comparison, makes the result equal the serial one, so the input must avoid the proof's memory.
57
48
  */
58
49
  export declare function foldCertified(pool: TaskPool, input: Uint8Array, memory: WebAssembly.Memory, certificate: StreamCertificate, options?: CertifiedFoldOptions): CertifiedFoldResult;
59
50
  /**
60
- * Runs a certified kernel that rewrites its input in place, one call per chunk on the workers of
61
- * `pool`. Chunks may start without the ones before them, because the byte step ignores the bytes
62
- * and the model gives the state at every chunk start, so each chunk runs once and writes its own
63
- * bytes. A chunk that ends in a state the model did not predict means the certificate does not
64
- * describe the kernel: the input is already rewritten, so this throws instead of returning.
51
+ * Runs a certified kernel that rewrites its input in place, one call per chunk on `pool`. A chunk
52
+ * that ends in a state the model did not predict means the certificate does not match the kernel.
53
+ * The input is already rewritten by then, so this throws.
65
54
  */
66
55
  export declare function reconstructCertified(pool: TaskPool, input: Uint8Array, memory: WebAssembly.Memory, certificate: StreamCertificate, options?: CertifiedFoldOptions): CertifiedFoldResult;
@@ -1,19 +1,16 @@
1
1
  import binaryen from 'binaryen';
2
2
  import { createHash } from 'node:crypto';
3
+ import { chunkRanges } from "../execution/fold.js";
4
+ import { serveTasks } from "../node/tasks.js";
3
5
  import { predictEnd } from "./affine.js";
4
6
  import { guardInput } from "./certify.js";
5
- import { chunkRanges } from "./fold.js";
6
- import { serveTasks } from "./tasks.js";
7
7
  /** The task name `serveCertified` answers: `certified:<start state in hex>`. */
8
8
  export const CERTIFIED_TASK = 'certified';
9
9
  const compactImports = binaryen.Features.CompactImports;
10
10
  const PAGE = 65536;
11
11
  /**
12
- * Rewrites a certified module to run on a memory the caller owns. Only the memory declaration and
13
- * the data segments change: the functions stay as they were, so the certificate still describes
14
- * them. The segments become passive so that no instance overwrites the shared bytes, and `prefill`
15
- * carries what they held, together with the table a lazily initializing module builds on its
16
- * first call, so every worker starts from the memory the proof assumed.
12
+ * Rewrites a certified module to use caller-owned memory. Only the memory import and the data
13
+ * segments change, so the certificate still describes the functions.
17
14
  */
18
15
  export function shareCertified(bytes, certificate, pages) {
19
16
  if (createHash('sha256').update(bytes).digest('hex') !== certificate.moduleSha256)
@@ -71,11 +68,7 @@ export function installPrefill(subject, memory) {
71
68
  for (const part of subject.prefill)
72
69
  new Uint8Array(memory.buffer, part.address, part.bytes.length).set(part.bytes);
73
70
  }
74
- /**
75
- * Runs on the worker side. Instantiates the shared module on the shared memory and answers
76
- * `certified:<hex state>` tasks: the input is a view of the shared memory, which is read in place,
77
- * and the output is the 8-byte little-endian end state.
78
- */
71
+ /** Worker side: runs `certified:<hex state>` tasks on the shared memory in place. */
79
72
  export function serveCertified(link, subject) {
80
73
  const instance = new WebAssembly.Instance(subject.module, { env: { memory: subject.memory } });
81
74
  const fn = instance.exports[subject.layout.entry];
@@ -97,11 +90,9 @@ export function serveCertified(link, subject) {
97
90
  });
98
91
  }
99
92
  /**
100
- * Folds `input`, a view of `memory`, through the certified kernel on the workers of `pool`, which
101
- * must run `serveCertified` on that memory. Every chunk runs once from state zero, in place, and
102
- * the model turns the end states into the state of the serial call. Nothing is compared or run
103
- * twice: the certificate is what makes the result equal the serial one, so the input must be
104
- * clear of the memory the proof depends on, which this checks.
93
+ * Folds `input`, a view of `memory`, through the certified kernel on `pool`, whose workers must run
94
+ * `serveCertified` on that memory. Each chunk runs once from zero, in place; the certificate, not a
95
+ * comparison, makes the result equal the serial one, so the input must avoid the proof's memory.
105
96
  */
106
97
  export function foldCertified(pool, input, memory, certificate, options = {}) {
107
98
  if (certificate.output)
@@ -150,10 +141,7 @@ function open(pool, input, memory, certificate, options) {
150
141
  throw new RangeError(`chunks cover ${at} of ${input.length} bytes`);
151
142
  return { ...base, chunks };
152
143
  }
153
- /**
154
- * The state after `length` bytes from state zero, for a step that ignores its byte: the doubling
155
- * that builds a chunk's offset needs no run of the kernel.
156
- */
144
+ /** The state after `length` bytes from zero, for a step that ignores its byte. No kernel run. */
157
145
  function zeroRun(certificate, length) {
158
146
  const { model, output } = certificate;
159
147
  let power = output.step;
@@ -168,11 +156,9 @@ function zeroRun(certificate, length) {
168
156
  return result;
169
157
  }
170
158
  /**
171
- * Runs a certified kernel that rewrites its input in place, one call per chunk on the workers of
172
- * `pool`. Chunks may start without the ones before them, because the byte step ignores the bytes
173
- * and the model gives the state at every chunk start, so each chunk runs once and writes its own
174
- * bytes. A chunk that ends in a state the model did not predict means the certificate does not
175
- * describe the kernel: the input is already rewritten, so this throws instead of returning.
159
+ * Runs a certified kernel that rewrites its input in place, one call per chunk on `pool`. A chunk
160
+ * that ends in a state the model did not predict means the certificate does not match the kernel.
161
+ * The input is already rewritten by then, so this throws.
176
162
  */
177
163
  export function reconstructCertified(pool, input, memory, certificate, options = {}) {
178
164
  if (certificate.output?.step === undefined)
@@ -1,8 +1,7 @@
1
1
  import type { AffineLayout, AffineModel } from './affine.ts';
2
2
  /**
3
- * `gf2` forms are bit-level affine over xor, `z2w` forms are word-level affine over add and
4
- * multiply, and `zp` forms are exact integers over two 16-bit digits with a residue after every
5
- * reduction, for state that holds two residues mod one constant, as Adler-32 does.
3
+ * Ring of a form: `gf2` is affine over xor, `z2w` over add and multiply, and `zp` over two 16-bit
4
+ * digits with residues mod a constant (Adler-32 style).
6
5
  */
7
6
  export type CertifiedRing = 'gf2' | 'z2w' | 'zp';
8
7
  export interface CertifyOptions {
@@ -12,12 +11,9 @@ export interface CertifyOptions {
12
11
  ptr: number;
13
12
  len: number;
14
13
  };
15
- /**
16
- * Lengths below this run concretely and the rest as quotient and remainder. The default tries 4
17
- * and then 16, because a smaller block is cheaper and a function with a larger unroll needs more.
18
- */
14
+ /** Lengths below this run concretely, the rest as quotient and remainder. Default: 4, then 16. */
19
15
  block?: number;
20
- /** Wall clock limit of the whole call, across the block ladder, in milliseconds. The default is 30000. */
16
+ /** Wall clock limit of the whole call across the block ladder, in milliseconds. Default 30000. */
21
17
  maxMs?: number;
22
18
  /** Restricts the analysis to one ring. The default tries `gf2`, then `z2w`, then `zp`. */
23
19
  ring?: CertifiedRing;
@@ -28,10 +24,8 @@ export interface CertificateRange {
28
24
  sha256: string;
29
25
  }
30
26
  /**
31
- * A call over `len` bytes at `ptr` also replaces byte `i` of that range with a fixed function of
32
- * the input byte and the fold state before it, and writes nothing else. When the byte step ignores
33
- * the input bytes, `step` is its result from state zero, which with the model gives every state
34
- * along the input without running the kernel, so chunks can run in place from their own start.
27
+ * The byte transform of a call: byte `i` of the range becomes a fixed function of the input byte
28
+ * and the state before it. `step` is its result from zero when the byte is ignored.
35
29
  */
36
30
  export interface CertificateOutput {
37
31
  inPlace: true;
@@ -42,10 +36,8 @@ export interface CertificateWrite {
42
36
  hex: string;
43
37
  }
44
38
  /**
45
- * A proof that `entry(state, ptr, len)` is, for every length of at least one byte, the left fold of
46
- * one affine byte step over the input, and the model of that step. The claim holds when the module
47
- * bytes hash to `moduleSha256`, the input range stays inside `memory` and avoids `exclusions`, and
48
- * the memory the proof read still holds `image` once `initialization` has run.
39
+ * A proof that `entry(state, ptr, len)` is the left fold of one affine byte step, for every length
40
+ * of at least one byte. It holds for a module with hash `moduleSha256`, clear of `exclusions`.
49
41
  */
50
42
  export interface StreamCertificate {
51
43
  kind: 'certificate';
@@ -84,12 +76,9 @@ export interface CertificateRefusal {
84
76
  }
85
77
  export declare const CHECKER = "folio-stream-certifier-2";
86
78
  /**
87
- * Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for every
88
- * length of at least one byte. The proof runs the function symbolically: lengths below `block`
89
- * one by one, and every other length as `block * q + r` for each remainder r with `q` symbolic.
90
- * A loop whose trip count depends on `q` is summarized by induction over its iterations. The
91
- * checker either returns a certificate or the reason it could not prove the claim. Refusing says
92
- * nothing about the function, and an internal failure is also a refusal.
79
+ * Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for
80
+ * every length of at least one byte. Lengths below `block` run one by one, the rest as `block*q+r`.
81
+ * A refusal says nothing about the function.
93
82
  */
94
83
  export declare function certifyStream(bytes: Uint8Array, entry: string, options?: CertifyOptions): StreamCertificate | CertificateRefusal;
95
84
  /** Re-derives the certificate from the module and compares everything except the work counters. */
@@ -247,7 +247,7 @@ function evalUnary(op, bits, a) {
247
247
  return refuse(`unsupported operation ${op}`);
248
248
  }
249
249
  }
250
- // variable layout of a gf2 mask: bit 0 is the constant one, bits 1 to 64 the state, then 8 per input byte
250
+ // gf2 mask layout: bit 0 is the constant, bits 1 to 64 the state, then 8 per input byte
251
251
  const LOW = (1n << 65n) - 1n;
252
252
  const bitVar = (pos, bit) => 1n << BigInt(65 + 8 * pos + bit);
253
253
  const gf = (f) => (f.r === 'gf2' ? f : refuse('mixed rings'));
@@ -380,7 +380,7 @@ const stateFree = (f) => (f.r === 'gf2'
380
380
  freeMemo.set(id, (free = atomList[id].args.every(stateFree)));
381
381
  return free;
382
382
  });
383
- /** Whether the form holds an atom of the state that the ring cannot express: a residue is expressed by `zp`. */
383
+ /** Whether the form holds a state atom the ring cannot express. `zp` expresses residues. */
384
384
  const opaque = (ring, f) => atomIdsOf(f).some((id) => {
385
385
  const key = `${ring.name}:${id}`;
386
386
  let found = opaqueMemo.get(key);
@@ -823,10 +823,7 @@ const zpFits = (x) => {
823
823
  return lo >= 0n && hi <= mask(x.w);
824
824
  };
825
825
  const zpChecked = (x, op) => (zpFits(x) ? x : refuse(`${op} may wrap`));
826
- /**
827
- * The bits of `x` below and from `s` up as two forms, when every state or byte term is either a
828
- * multiple of 2^s or sits wholly below it, so the low part provably stays under 2^s.
829
- */
826
+ /** The bits of `x` below and from `s` up as two forms, when no term crosses the split at 2^s. */
830
827
  function zpSplit(x, s) {
831
828
  if (!zpFits(x))
832
829
  return refuse('a split of a value that may wrap');
@@ -875,9 +872,8 @@ function zpDisjoint(hi, lo) {
875
872
  return l >= 0n && h < 1n << BigInt(s) ? zpLin(hi, lo, 1n) : undefined;
876
873
  }
877
874
  /**
878
- * `f` mod `p` for a form that holds a value in [0, 2^w). A residue atom stands for its argument
879
- * mod p, so a residue inside another one folds away and the argument is kept with every coefficient
880
- * reduced. A value that is already below p is the argument itself.
875
+ * `f` mod `p` for a form that holds a value in [0, 2^w). A residue inside a residue folds away, and
876
+ * a value already below p is the argument itself.
881
877
  */
882
878
  function zpRes(p, f) {
883
879
  let c = f.c;
@@ -910,7 +906,7 @@ function zpRes(p, f) {
910
906
  return g;
911
907
  return zpAtom(f.w, internAtom('Res', f.w, String(p), [g]));
912
908
  }
913
- /** `x` with both digits replaced by the digits of a state form and its byte positions moved by `shift`. */
909
+ /** `x` with both digits replaced by a state form's digits, and byte positions moved by `shift`. */
914
910
  function zpSubst(x, digits, shift) {
915
911
  const bytes = new Map();
916
912
  for (const [pos, v] of x.b)
@@ -945,7 +941,7 @@ function zpRemap(x, map) {
945
941
  }
946
942
  return out;
947
943
  }
948
- /** The modulus and the digit matrix of a one byte step whose two digits are each reduced mod one p. */
944
+ /** Modulus and digit matrix of a one byte step whose two digits are each reduced mod one p. */
949
945
  function zpFacts(f) {
950
946
  const x = zpf(f);
951
947
  if (x.w !== 32)
@@ -1136,12 +1132,11 @@ const zp = {
1136
1132
  },
1137
1133
  lookup: () => refuse('a table lookup is not affine over zp')
1138
1134
  };
1139
- // the first operation a ring kept as an atom although the state feeds it, for the reason a refusal gives
1135
+ // the first atom the state feeds, kept for the refusal reason
1140
1136
  let opaqueWhy = '';
1141
1137
  /**
1142
- * Lets a ring keep an operation it cannot express affinely as an atom. An atom that the state
1143
- * feeds may be stored to memory, which the output proof allows, but never reaches the state
1144
- * itself: `Analysis.check` refuses a result that holds one.
1138
+ * Keeps an operation the ring cannot express affinely as an atom. A state-fed atom may be stored to
1139
+ * memory but never reaches the state itself; `Analysis.check` refuses a result that holds one.
1145
1140
  */
1146
1141
  function withAtoms(ring, make) {
1147
1142
  const binary = ring.binary.bind(ring);
@@ -1246,7 +1241,7 @@ class Mem {
1246
1241
  this.over.set(address + i, Number((value >> BigInt(8 * i)) & 255n));
1247
1242
  }
1248
1243
  }
1249
- /** The offset immediate of a load or store as the unsigned 32-bit value wasm adds to the address. */
1244
+ /** The offset immediate of a load or store, as the unsigned 32-bit value wasm adds. */
1250
1245
  const imm32 = (v) => BigInt.asUintN(32, BigInt(v.offset));
1251
1246
  const info = (expr) => {
1252
1247
  try {
@@ -1266,7 +1261,7 @@ function constBits(v) {
1266
1261
  ? v.value
1267
1262
  : (BigInt(v.value.high) << 32n) | BigInt(v.value.low >>> 0);
1268
1263
  }
1269
- /** Adds every local that `expr` may set to `out`. Calls run on their own locals and set none of the caller's. */
1264
+ /** Adds every local `expr` may set to `out`. Calls set none of the caller's locals. */
1270
1265
  function assigned(expr, out) {
1271
1266
  const id = binaryen.getExpressionId(expr);
1272
1267
  if (id === binaryen.NopId || id === binaryen.ConstId || id === binaryen.LocalGetId)
@@ -1574,7 +1569,7 @@ class Analysis {
1574
1569
  f: this.ring.binary(k.op, this.dataOf(a, k.bits), this.dataOf(b, k.bits))
1575
1570
  };
1576
1571
  }
1577
- /** popcnt(x) & 1 over data, which the generic rules would refuse because the count is not affine. */
1572
+ /** popcnt(x) & 1 over data. The generic rules refuse it: the count is not affine. */
1578
1573
  parity(v) {
1579
1574
  for (const [count, one] of [
1580
1575
  [v.left, v.right],
@@ -1691,7 +1686,7 @@ class Analysis {
1691
1686
  const pos = csub(address, this.st.base);
1692
1687
  if (!isNum(pos) || pos.c < 0n || pos.c + BigInt(width) > MAXPOS)
1693
1688
  return refuse('input load not at a fixed offset from the first unfolded byte');
1694
- // the address wraps at 2^32 but the immediate does not, so the two agree only when the position covers it
1689
+ // the address wraps at 2^32 but the immediate does not; they agree only if the position covers it
1695
1690
  if (offset > pos.c)
1696
1691
  return refuse('a load whose immediate offset exceeds its position');
1697
1692
  const at = csub(address, sym('P0'));
@@ -1741,10 +1736,7 @@ class Analysis {
1741
1736
  const f = this.dataOf(value, value.t === 'd' ? value.f.w : 32);
1742
1737
  return this.ring.binary('And', f, this.ring.konst(255n, f.w));
1743
1738
  }
1744
- /**
1745
- * A byte stored at an address that follows the pointer. In a loop it is kept for `summarize`;
1746
- * otherwise it must be the byte transform of the state before it, which the one byte call defines.
1747
- */
1739
+ /** A byte stored after the pointer: kept for `summarize` in a loop, else the byte transform. */
1748
1740
  output(v, addr, value) {
1749
1741
  if (v.bytes !== 1)
1750
1742
  return refuse('a store of more than one byte');
@@ -1845,7 +1837,7 @@ class Analysis {
1845
1837
  return undefined;
1846
1838
  }
1847
1839
  }
1848
- /** The effect of a counted loop whose length depends on the quotient, by induction over its iterations. */
1840
+ /** Effect of a counted loop whose length depends on the quotient, by induction over iterations. */
1849
1841
  summarize(loop) {
1850
1842
  const outer = this.st;
1851
1843
  if (outer.gen || this.depth)
@@ -2053,7 +2045,7 @@ class Analysis {
2053
2045
  refuse('an input byte is read after the loop wrote it');
2054
2046
  });
2055
2047
  }
2056
- // a state copy written in the loop that equals a live local's next value holds that local's form afterwards
2048
+ // a state copy equal to a live local's next value keeps that local's form afterwards
2057
2049
  const copies = new Map();
2058
2050
  for (const j of gen.written) {
2059
2051
  const value = end[j];
@@ -2252,10 +2244,7 @@ class Analysis {
2252
2244
  written: this.st.written
2253
2245
  };
2254
2246
  }
2255
- /**
2256
- * Once the one byte call has written its byte, every call must write the bytes from the pointer
2257
- * up to its length, each once. Each store was already compared with the transform of the byte.
2258
- */
2247
+ /** After the one byte call, every call writes each byte from the pointer to its length, once. */
2259
2248
  tile(written, length, first) {
2260
2249
  if (!written.length) {
2261
2250
  if (this.out1)
@@ -2312,8 +2301,8 @@ class Analysis {
2312
2301
  }
2313
2302
  let same = ring.equal(out.result, this.iterate(out.pending));
2314
2303
  if (!same && span(csub(out.base, sym('P0')), this.ranges)[0] >= 1n) {
2315
- // the folded prefix is itself one byte step, so a state that was masked or normalized is already in range
2316
- // the image byte sits above every input position and placeholder, so it cannot merge with a real byte
2304
+ // the folded prefix is one byte step, so a masked or normalized state is already in range
2305
+ // the image byte sits above every input position, so it cannot merge with a real byte
2317
2306
  const image = ring.subst(this.f1, ring.state(this.w), IMAGE);
2318
2307
  same = ring.equal(ring.subst(out.result, image, 0), ring.subst(this.iterate(out.pending), image, 0));
2319
2308
  }
@@ -2331,10 +2320,7 @@ class Analysis {
2331
2320
  this.check(undefined, r);
2332
2321
  }
2333
2322
  }
2334
- /**
2335
- * `a & m` when every symbol coefficient is a multiple of 2^j: the low j bits come from the constant
2336
- * alone, and the bits from j up are either all dropped or all kept by the mask.
2337
- */
2323
+ /** `a & m` when every symbol coefficient is a multiple of 2^j, so the mask keeps or drops bits. */
2338
2324
  const maskControl = (a, m) => {
2339
2325
  if (m === M32)
2340
2326
  return a;
@@ -2447,12 +2433,9 @@ function certifyRing(ring, fn, layout, block, segments, limit, entry, moduleSha2
2447
2433
  };
2448
2434
  }
2449
2435
  /**
2450
- * Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for every
2451
- * length of at least one byte. The proof runs the function symbolically: lengths below `block`
2452
- * one by one, and every other length as `block * q + r` for each remainder r with `q` symbolic.
2453
- * A loop whose trip count depends on `q` is summarized by induction over its iterations. The
2454
- * checker either returns a certificate or the reason it could not prove the claim. Refusing says
2455
- * nothing about the function, and an internal failure is also a refusal.
2436
+ * Decides whether `entry(state, ptr, len)` in `bytes` is the byte fold of one affine step, for
2437
+ * every length of at least one byte. Lengths below `block` run one by one, the rest as `block*q+r`.
2438
+ * A refusal says nothing about the function.
2456
2439
  */
2457
2440
  export function certifyStream(bytes, entry, options = {}) {
2458
2441
  const blocks = options.block === undefined ? [4, 16] : [options.block];
@@ -1,36 +1,4 @@
1
- import type { TransactionResult } from './transaction.ts';
2
- /**
3
- * Recorded region results, reused when the bytes a region read have not changed.
4
- *
5
- * A tracked region's result is a function of its module, its export, its integer arguments, the
6
- * memory size and the bytes it read from memory before writing them. After an exact tracked
7
- * execution the memo keeps the read ranges, a SHA-256 of their bytes as they were read, the read
8
- * addresses, the write set, the return value and the time the execution took. A lookup hashes the
9
- * current bytes of each recorded entry's ranges and returns the recorded result on equality.
10
- * Equal module, arguments and bytes give the same execution, so the same writes and value.
11
- *
12
- * Host contract, for a host that tracks its own regions:
13
- *
14
- * - The module string passed to `keyOf` must identify the module bytes and their instrumentation.
15
- * Two calls with the same module string are assumed to execute identically. `ManagedFolio`
16
- * assigns a process-local identity per artifact; a host that shares a memo across processes or
17
- * restarts must use a content hash of the tracked module instead.
18
- * - The host supplies the region export, its arguments, the memory at the start of the call and
19
- * the call's tracked read and write sets. `record` takes the memory before any write of the
20
- * call, because it hashes the read bytes itself. The read set holds only the bytes the region
21
- * read before it wrote them, which is what the execution depends on.
22
- * - The region must be deterministic in its read bytes, arguments and module. It may not read a
23
- * clock, randomness, a host import or any mutable global. The compiler refuses global access in
24
- * a region span (`summarizeSpan` in `src/extract.ts`); the lane resets its fuel counter before
25
- * every call (`FolioLane.execute` in `src/managed.ts`), so the counter carries no state between
26
- * calls.
27
- * - A trap, fuel or budget exhaustion, an inconclusive result or a read the shipped ranges missed
28
- * is refused by `record`.
29
- *
30
- * `RegionMemo.probe` measures repetition without recording writes, so a host can see the reuse
31
- * rate on its own traffic before it enables a memo. The probe is an upper bound on hit rate: it
32
- * keeps no entry limit and no byte budget.
33
- */
1
+ import type { TransactionResult } from '../execution/transaction.ts';
34
2
  export interface MemoStats {
35
3
  lookups: number;
36
4
  hits: number;
@@ -63,6 +31,13 @@ export interface MemoHit {
63
31
  result: TransactionResult;
64
32
  ms: number;
65
33
  }
34
+ /**
35
+ * Recorded region results, reused while the bytes a region read are unchanged. The module string
36
+ * passed to `keyOf` must identify the module bytes and their instrumentation; a memo shared across
37
+ * processes or restarts keys on a content hash. A region must be deterministic in its read bytes
38
+ * and arguments, so it may not read a clock, randomness, a host import or a mutable global.
39
+ * `record` refuses traps, exhausted fuel, inconclusive results and reads outside shipped ranges.
40
+ */
66
41
  export declare class RegionMemo {
67
42
  #private;
68
43
  constructor(options?: MemoOptions);
@@ -1,5 +1,5 @@
1
+ import { writeRunsOf } from "../execution/runs.js";
1
2
  import { FootprintCache, RangeSet } from "./ranges.js";
2
- import { writeRunsOf } from "./runs.js";
3
3
  async function digest(memory, spans) {
4
4
  let total = 0;
5
5
  for (let i = 1; i < spans.length; i += 2)
@@ -41,6 +41,13 @@ function addressForm(result) {
41
41
  writeData: undefined
42
42
  };
43
43
  }
44
+ /**
45
+ * Recorded region results, reused while the bytes a region read are unchanged. The module string
46
+ * passed to `keyOf` must identify the module bytes and their instrumentation; a memo shared across
47
+ * processes or restarts keys on a content hash. A region must be deterministic in its read bytes
48
+ * and arguments, so it may not read a clock, randomness, a host import or a mutable global.
49
+ * `record` refuses traps, exhausted fuel, inconclusive results and reads outside shipped ranges.
50
+ */
44
51
  export class RegionMemo {
45
52
  #budget;
46
53
  #perKey;
@@ -166,7 +173,6 @@ export class RegionMemo {
166
173
  key,
167
174
  memoryBytes,
168
175
  spans,
169
- readBytes: seen.bytes,
170
176
  digest: seen.digest,
171
177
  reads,
172
178
  writeAddresses,
@@ -1,4 +1,4 @@
1
- import { encodeFrame } from "./frames.js";
1
+ import { encodeFrame } from "../remote/frames.js";
2
2
  /** Page size for rounding learned footprints. */
3
3
  export const rangePage = 4096;
4
4
  /** Most ranges one frame carries; the header is capped at 64 KiB. */
@@ -1,4 +1,4 @@
1
- import { iterationSummaryShift, iterationSummaryWords } from "./iteration-layout.js";
1
+ import { iterationSummaryShift, iterationSummaryWords } from "../memory/iteration-layout.js";
2
2
  // one scan at a time per thread; the run being built lives here so the word loop stays flat
3
3
  let start = -1;
4
4
  let at = 0;
@@ -1,23 +1,5 @@
1
- /** A byte range an iteration reads without per-access marks. */
2
- export interface IterationReadWindow {
3
- low: number;
4
- bytes: number;
5
- }
6
- /**
7
- * The read windows of one loop. The strided window moves with the iteration index: iteration `k`
8
- * reads from the granule boundary at or below `low + (k - index) * stride`. The fixed window is the same range in every
9
- * iteration. Neither has to be right for a run to be correct: a load outside the window is tracked
10
- * as usual, and a window only costs a false conflict when another iteration writes inside it.
11
- */
12
- export interface IterationReadWindows {
13
- strided?: {
14
- index: number;
15
- low: number;
16
- stride: number;
17
- bytes: number;
18
- };
19
- fixed?: IterationReadWindow;
20
- }
1
+ import type { IterationReadWindow, IterationReadWindows, ReadWindowCounts } from '../execution/types.ts';
2
+ export type { IterationReadWindow, IterationReadWindows, ReadWindowCounts };
21
3
  /** What one iteration's outcome has to hold for learning. */
22
4
  export interface ReadWindowSample {
23
5
  index: number;
@@ -32,15 +14,6 @@ export declare const readWindowMinimum: {
32
14
  readonly strided: number;
33
15
  readonly fixed: number;
34
16
  };
35
- /**
36
- * Loads of at most 8 bytes of one run on the module with read windows, by where they landed:
37
- * inside a window, tracked outside every window, or exempt (the slot's own callee stack).
38
- */
39
- export interface ReadWindowCounts {
40
- hits: number;
41
- misses: number;
42
- exempt: number;
43
- }
44
17
  /**
45
18
  * Executed Wasm instructions of one load of at most 8 bytes, counted on the lowering with the slot
46
19
  * checks and no frame shadow (one node per instruction). The windows go before the exempt check
@@ -93,9 +66,10 @@ export declare function markReadWindow(u8: Uint8Array, base: number, low: number
93
66
  /**
94
67
  * Windows from the read and write sets of tracked iterations that completed without a conflict.
95
68
  * The strided one follows the largest read run of each iteration when the runs line up on one
96
- * stride; when their lengths differ by more than a granule the window is the shortest one; the fixed one is the largest run
97
- * every iteration read that is not inside the strided one. A window that another iteration wrote
98
- * into, in the sample, is dropped: its reads would conflict. Needs three completed iterations.
69
+ * stride; when their lengths differ by more than a granule the window is the shortest one. The
70
+ * fixed one is the largest run every iteration read that is not inside the strided one. A window
71
+ * that another iteration wrote into, in the sample, is dropped: its reads would conflict. Needs
72
+ * three completed iterations.
99
73
  */
100
74
  export declare function learnReadWindows(samples: readonly ReadWindowSample[]): {
101
75
  windows?: IterationReadWindows;
@@ -1,4 +1,4 @@
1
- import { iterationGranules } from "./iteration-layout.js";
1
+ import { iterationGranules } from "../memory/iteration-layout.js";
2
2
  const READ = iterationGranules.read;
3
3
  const WRITE = iterationGranules.write;
4
4
  /** Smallest window worth marking: four read granules for the strided one, two for the fixed one. */
@@ -109,7 +109,7 @@ function writesTouch(sorted, low, end) {
109
109
  }
110
110
  return a < sorted.length && sorted[a] * WRITE < end;
111
111
  }
112
- // the value in the open interval with the most trailing zero bits, so a power-of-two record size wins
112
+ // the value in the open interval with the most trailing zero bits, so a power-of-two size wins
113
113
  function pickStride(low, high) {
114
114
  for (let step = 4096; step >= 1; step /= 2) {
115
115
  const candidate = (Math.ceil(high / step) - 1) * step;
@@ -151,9 +151,10 @@ function subtractRange(runs, low, end) {
151
151
  /**
152
152
  * Windows from the read and write sets of tracked iterations that completed without a conflict.
153
153
  * The strided one follows the largest read run of each iteration when the runs line up on one
154
- * stride; when their lengths differ by more than a granule the window is the shortest one; the fixed one is the largest run
155
- * every iteration read that is not inside the strided one. A window that another iteration wrote
156
- * into, in the sample, is dropped: its reads would conflict. Needs three completed iterations.
154
+ * stride; when their lengths differ by more than a granule the window is the shortest one. The
155
+ * fixed one is the largest run every iteration read that is not inside the strided one. A window
156
+ * that another iteration wrote into, in the sample, is dropped: its reads would conflict. Needs
157
+ * three completed iterations.
157
158
  */
158
159
  export function learnReadWindows(samples) {
159
160
  const done = samples.filter((s) => s.status === 0).sort((a, b) => a.index - b.index);
@@ -178,8 +179,8 @@ export function learnReadWindows(samples) {
178
179
  if (minLen * READ < readWindowMinimum.strided)
179
180
  why.push('no read run of 256 bytes in every iteration');
180
181
  else {
181
- // the first byte of iteration k lies in granule start[k], so every pair of iterations bounds
182
- // the stride to an open interval of width 128 / distance; the stride is one value in all
182
+ // the first byte of iteration k lies in granule start[k], so each pair of iterations
183
+ // bounds the stride to an open interval of width 128 / distance; one value fits all
183
184
  let low = -Infinity, high = Infinity;
184
185
  for (let i = 0; i < done.length; i++)
185
186
  for (let j = i + 1; j < done.length; j++) {