@gmitch215/folio 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +455 -26
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/bake.d.ts +8 -3
  7. package/dist/bake.js +5 -2
  8. package/dist/boundaries.d.ts +59 -0
  9. package/dist/boundaries.js +127 -0
  10. package/dist/certified.d.ts +66 -0
  11. package/dist/certified.js +192 -0
  12. package/dist/certify.d.ts +98 -0
  13. package/dist/certify.js +2628 -0
  14. package/dist/compiler.d.ts +37 -1
  15. package/dist/compiler.js +116 -1
  16. package/dist/context.d.ts +47 -0
  17. package/dist/context.js +139 -0
  18. package/dist/coordinator.d.ts +1 -1
  19. package/dist/coordinator.js +54 -5
  20. package/dist/extract.d.ts +114 -1
  21. package/dist/extract.js +1011 -242
  22. package/dist/fold.d.ts +32 -0
  23. package/dist/fold.js +105 -0
  24. package/dist/frames.d.ts +20 -2
  25. package/dist/frames.js +205 -10
  26. package/dist/inline.d.ts +182 -0
  27. package/dist/inline.js +766 -0
  28. package/dist/iteration-admission.d.ts +185 -0
  29. package/dist/iteration-admission.js +201 -0
  30. package/dist/iteration-layout.d.ts +135 -0
  31. package/dist/iteration-layout.js +169 -0
  32. package/dist/iteration-owner.d.ts +45 -0
  33. package/dist/iteration-owner.js +223 -0
  34. package/dist/iteration-worker.d.ts +1 -0
  35. package/dist/iteration-worker.js +216 -0
  36. package/dist/iteration.d.ts +329 -0
  37. package/dist/iteration.js +1210 -0
  38. package/dist/lease.d.ts +45 -0
  39. package/dist/lease.js +274 -0
  40. package/dist/managed.d.ts +78 -0
  41. package/dist/managed.js +448 -27
  42. package/dist/memo.d.ts +99 -0
  43. package/dist/memo.js +250 -0
  44. package/dist/node.d.ts +61 -5
  45. package/dist/node.js +421 -23
  46. package/dist/ownership-redirect.d.ts +30 -0
  47. package/dist/ownership-redirect.js +179 -0
  48. package/dist/ownership-slices.d.ts +44 -0
  49. package/dist/ownership-slices.js +72 -0
  50. package/dist/ownership.d.ts +161 -0
  51. package/dist/ownership.js +6568 -0
  52. package/dist/ranges.d.ts +78 -0
  53. package/dist/ranges.js +263 -0
  54. package/dist/read-scan.d.ts +18 -0
  55. package/dist/read-scan.js +94 -0
  56. package/dist/read-windows.d.ts +103 -0
  57. package/dist/read-windows.js +244 -0
  58. package/dist/router-worker.d.ts +1 -0
  59. package/dist/router-worker.js +4 -0
  60. package/dist/router.d.ts +203 -0
  61. package/dist/router.js +667 -0
  62. package/dist/runs.d.ts +44 -0
  63. package/dist/runs.js +182 -0
  64. package/dist/slices-worker.d.ts +1 -0
  65. package/dist/slices-worker.js +38 -0
  66. package/dist/slices.d.ts +126 -0
  67. package/dist/slices.js +441 -0
  68. package/dist/tasks.d.ts +14 -4
  69. package/dist/tasks.js +23 -9
  70. package/dist/transaction.d.ts +10 -0
  71. package/package.json +44 -4
package/dist/runs.d.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Run-encoded tracking: reads and writes as sorted, non-touching `[start, length]` runs in a flat
3
+ * `Uint32Array`. A run set is canonical when every length is at least 1 and each start lies past
4
+ * the end of the run before it, so `[0, 4]` followed by `[4, 4]` is not canonical.
5
+ */
6
+ /** Bytes covered by a flat run list. */
7
+ export declare function runBytes(runs: ArrayLike<number>): number;
8
+ /** Canonical runs from addresses sorted ascending; a repeated address counts once. */
9
+ export declare function runsOfSorted(addresses: ArrayLike<number>): Uint32Array;
10
+ /** Runs for written bytes given as `[address, value]` pairs in any order, with their bytes. */
11
+ export declare function writeRunsOf(pairs: readonly (readonly [number, number])[]): {
12
+ runs: Uint32Array;
13
+ data: Uint8Array;
14
+ };
15
+ /**
16
+ * Canonical runs from written pieces in any order; pieces that touch merge. Pieces must not
17
+ * overlap. The bytes are copied once, in address order.
18
+ */
19
+ export declare function packWrites(pieces: readonly (readonly [start: number, data: Uint8Array])[]): {
20
+ runs: Uint32Array;
21
+ data: Uint8Array;
22
+ };
23
+ /** Keeps the first `cap` bytes of a run list. */
24
+ export declare function capRuns(runs: Uint32Array, cap: number): Uint32Array;
25
+ /**
26
+ * Throws unless `runs` is canonical and every byte lies below `limit`. A frame decoder calls it
27
+ * on every run list it reads, so the rest of the owner can rely on the form.
28
+ */
29
+ export declare function checkRuns(runs: ArrayLike<number>, limit: number, label: string): void;
30
+ /**
31
+ * Bytes written so far in one batch, as sorted non-touching intervals. `overlaps` is the
32
+ * conflict test of the owner: true when any read run shares a byte with an interval.
33
+ */
34
+ export declare class DirtyRuns {
35
+ #private;
36
+ get count(): number;
37
+ has(address: number): boolean;
38
+ /** Adds `[start, start + length)`; intervals it touches or overlaps merge. */
39
+ add(start: number, length: number): void;
40
+ /** True when any byte of the canonical run list lies in the set. */
41
+ overlaps(runs: ArrayLike<number>): boolean;
42
+ /** Every dirty byte as one canonical run list. */
43
+ runs(): Uint32Array;
44
+ }
package/dist/runs.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Run-encoded tracking: reads and writes as sorted, non-touching `[start, length]` runs in a flat
3
+ * `Uint32Array`. A run set is canonical when every length is at least 1 and each start lies past
4
+ * the end of the run before it, so `[0, 4]` followed by `[4, 4]` is not canonical.
5
+ */
6
+ /** Bytes covered by a flat run list. */
7
+ export function runBytes(runs) {
8
+ let total = 0;
9
+ for (let i = 1; i < runs.length; i += 2)
10
+ total += runs[i];
11
+ return total;
12
+ }
13
+ /** Canonical runs from addresses sorted ascending; a repeated address counts once. */
14
+ export function runsOfSorted(addresses) {
15
+ const out = [];
16
+ let end = -1;
17
+ for (let i = 0; i < addresses.length; i++) {
18
+ const address = addresses[i];
19
+ if (address === end) {
20
+ out[out.length - 1]++;
21
+ end++;
22
+ }
23
+ else if (address > end) {
24
+ out.push(address, 1);
25
+ end = address + 1;
26
+ }
27
+ }
28
+ return Uint32Array.from(out);
29
+ }
30
+ /** Runs for written bytes given as `[address, value]` pairs in any order, with their bytes. */
31
+ export function writeRunsOf(pairs) {
32
+ const order = Uint32Array.from(pairs, (pair) => pair[0]).sort();
33
+ const values = new Map();
34
+ for (const [address, value] of pairs)
35
+ values.set(address, value);
36
+ const runs = runsOfSorted(order);
37
+ const data = new Uint8Array(runBytes(runs));
38
+ let at = 0;
39
+ for (let i = 0; i < runs.length; i += 2)
40
+ for (let k = 0; k < runs[i + 1]; k++)
41
+ data[at++] = values.get(runs[i] + k);
42
+ return { runs, data };
43
+ }
44
+ /**
45
+ * Canonical runs from written pieces in any order; pieces that touch merge. Pieces must not
46
+ * overlap. The bytes are copied once, in address order.
47
+ */
48
+ export function packWrites(pieces) {
49
+ const sorted = pieces.filter((piece) => piece[1].length).sort((a, b) => a[0] - b[0]);
50
+ const runs = [];
51
+ let total = 0;
52
+ for (const [start, data] of sorted) {
53
+ const last = runs.length - 2;
54
+ if (last >= 0 && start <= runs[last] + runs[last + 1])
55
+ runs[last + 1] = Math.max(runs[last + 1], start + data.length - runs[last]);
56
+ else
57
+ runs.push(start, data.length);
58
+ }
59
+ for (let i = 1; i < runs.length; i += 2)
60
+ total += runs[i];
61
+ const out = new Uint8Array(total);
62
+ let base = 0, run = 0;
63
+ for (const [start, data] of sorted) {
64
+ while (start >= runs[run * 2] + runs[run * 2 + 1]) {
65
+ base += runs[run * 2 + 1];
66
+ run++;
67
+ }
68
+ out.set(data, base + start - runs[run * 2]);
69
+ }
70
+ return { runs: Uint32Array.from(runs), data: out };
71
+ }
72
+ /** Keeps the first `cap` bytes of a run list. */
73
+ export function capRuns(runs, cap) {
74
+ let left = Math.max(0, cap);
75
+ for (let i = 1; i < runs.length; i += 2) {
76
+ if (runs[i] <= left) {
77
+ left -= runs[i];
78
+ continue;
79
+ }
80
+ const out = runs.slice(0, i + 1);
81
+ if (left)
82
+ out[i] = left;
83
+ else
84
+ return runs.slice(0, i - 1);
85
+ return out;
86
+ }
87
+ return runs;
88
+ }
89
+ /**
90
+ * Throws unless `runs` is canonical and every byte lies below `limit`. A frame decoder calls it
91
+ * on every run list it reads, so the rest of the owner can rely on the form.
92
+ */
93
+ export function checkRuns(runs, limit, label) {
94
+ let end = -1;
95
+ for (let i = 0; i < runs.length; i += 2) {
96
+ const start = runs[i], length = runs[i + 1];
97
+ if (length < 1 || start <= end)
98
+ throw new TypeError(`non-canonical lane ${label} runs`);
99
+ if (start + length > limit)
100
+ throw new RangeError(`lane ${label} outside arena`);
101
+ end = start + length;
102
+ }
103
+ }
104
+ /**
105
+ * Bytes written so far in one batch, as sorted non-touching intervals. `overlaps` is the
106
+ * conflict test of the owner: true when any read run shares a byte with an interval.
107
+ */
108
+ export class DirtyRuns {
109
+ // parallel arrays, ascending; end is exclusive
110
+ #starts = [];
111
+ #ends = [];
112
+ get count() {
113
+ return this.#starts.length;
114
+ }
115
+ /** First interval whose end lies past `at`. */
116
+ #after(at, from = 0) {
117
+ let low = from, high = this.#ends.length;
118
+ while (low < high) {
119
+ const mid = (low + high) >> 1;
120
+ if (this.#ends[mid] <= at)
121
+ low = mid + 1;
122
+ else
123
+ high = mid;
124
+ }
125
+ return low;
126
+ }
127
+ has(address) {
128
+ const i = this.#after(address);
129
+ return i < this.#starts.length && this.#starts[i] <= address;
130
+ }
131
+ /** Adds `[start, start + length)`; intervals it touches or overlaps merge. */
132
+ add(start, length) {
133
+ if (length < 1)
134
+ return;
135
+ let end = start + length;
136
+ // ascending writes append: the common case, since a batch walks its output forward
137
+ const top = this.#ends.length - 1;
138
+ if (top < 0 || start > this.#ends[top]) {
139
+ this.#starts.push(start);
140
+ this.#ends.push(end);
141
+ return;
142
+ }
143
+ if (start === this.#ends[top]) {
144
+ this.#ends[top] = end;
145
+ return;
146
+ }
147
+ // touching intervals merge: the first one whose end reaches start
148
+ const first = this.#after(start - 1);
149
+ let last = first;
150
+ while (last < this.#starts.length && this.#starts[last] <= end) {
151
+ end = Math.max(end, this.#ends[last]);
152
+ last++;
153
+ }
154
+ const merged = first < last ? Math.min(start, this.#starts[first]) : start;
155
+ this.#starts.splice(first, last - first, merged);
156
+ this.#ends.splice(first, last - first, end);
157
+ }
158
+ /** True when any byte of the canonical run list lies in the set. */
159
+ overlaps(runs) {
160
+ if (!this.#starts.length)
161
+ return false;
162
+ let i = 0;
163
+ for (let r = 0; r < runs.length; r += 2) {
164
+ const start = runs[r], end = start + runs[r + 1];
165
+ i = this.#after(start, i);
166
+ if (i === this.#starts.length)
167
+ return false;
168
+ if (this.#starts[i] < end)
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+ /** Every dirty byte as one canonical run list. */
174
+ runs() {
175
+ const out = new Uint32Array(this.#starts.length * 2);
176
+ this.#starts.forEach((start, i) => {
177
+ out[i * 2] = start;
178
+ out[i * 2 + 1] = this.#ends[i] - start;
179
+ });
180
+ return out;
181
+ }
182
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,38 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { parentPort, workerData } from 'node:worker_threads';
10
+ import { decodeValues, encodeValues } from "./slices.js";
11
+ import { serveTasks } from "./tasks.js";
12
+ const data = workerData;
13
+ (async () => {
14
+ const extra = data.imports ? (await import(__rewriteRelativeImportExtension(data.imports))).default() : {};
15
+ const imports = {
16
+ ...extra,
17
+ [data.slot.module]: { ...(extra[data.slot.module] ?? {}), [data.slot.name]: data.memory }
18
+ };
19
+ const instance = new WebAssembly.Instance(data.module, imports);
20
+ const stack = data.stack && instance.exports[data.stack.name];
21
+ if (stack)
22
+ stack.value = data.stack.top;
23
+ for (const w of data.windows ?? [])
24
+ instance.exports[w.delta].value = w.copy - w.low;
25
+ serveTasks(data.link, (name, input) => {
26
+ if (data.windows) {
27
+ // a trap leaves the stack pointer deep, and the last slice left its own bytes in the copies
28
+ if (stack)
29
+ stack.value = data.stack.top;
30
+ const bytes = new Uint8Array(data.memory.buffer);
31
+ for (const w of data.windows)
32
+ bytes.copyWithin(w.copy, w.low, w.end);
33
+ }
34
+ const result = instance.exports[name](...decodeValues(String(input)));
35
+ return result === undefined ? '' : encodeValues(result);
36
+ });
37
+ parentPort.postMessage({ ready: true });
38
+ })();
@@ -0,0 +1,126 @@
1
+ import type { OwnershipPlan } from './extract.ts';
2
+ import { type TaskRecord } from './tasks.ts';
3
+ /** Options for `SlicePool.open`. */
4
+ export interface SlicePoolOptions {
5
+ /**
6
+ * The shared memory every worker runs on. It must be a shared memory with a declared maximum
7
+ * that leaves room for one private stack per worker. The pool grows it by that much at open.
8
+ */
9
+ memory: WebAssembly.Memory;
10
+ /** Worker count. The default is the available parallelism, at most 8. */
11
+ workers?: number;
12
+ /**
13
+ * Bytes of private stack per worker, a multiple of 65,536. Only a module that keeps a stack
14
+ * pointer global gets stacks. The default is 65,536.
15
+ */
16
+ stackBytes?: number;
17
+ /**
18
+ * A module specifier or URL whose default export returns the imports the module needs besides
19
+ * its memory. Each worker loads it, because functions do not cross threads.
20
+ */
21
+ imports?: string | URL;
22
+ /**
23
+ * The plan of a module that `redirectOwnership` rewrote. Each worker gets a private copy of every
24
+ * window next to its stack, the owner copies the last record's bytes back after a clean run, and
25
+ * a trap in any slice restores `writes` and runs the calls serially in place.
26
+ */
27
+ ownership?: OwnershipPlan;
28
+ }
29
+ /** Options for one `SlicePool.run`. */
30
+ export interface SliceRunOptions {
31
+ /** Calls per slice. The default splits the range evenly over the workers. */
32
+ grain?: number;
33
+ /**
34
+ * Byte ranges the calls write outside the windows, such as the output slots. A pool opened with
35
+ * `ownership` needs them: they are copied before the run and put back when a slice traps. The
36
+ * list must name every range the calls write: a range left out keeps the writes of the calls
37
+ * after the trap, and the serial replay does not undo them.
38
+ */
39
+ writes?: [number, number][];
40
+ /** Largest copy of `writes` in bytes. Past it the calls run serially in place. Default 64 MiB. */
41
+ snapshotLimit?: number;
42
+ /**
43
+ * Runs the same slices serially on a copy of the memory taken before the run and compares the
44
+ * result and every byte below the stacks. A difference throws `SliceConflictError`. It costs
45
+ * a serial execution and a memory copy, and is meant for tests and canaries.
46
+ */
47
+ audit?: boolean;
48
+ }
49
+ /** What an ownership pool did around the slices of one run. */
50
+ export interface OwnedSliceReport {
51
+ snapshotBytes: number;
52
+ snapshotMs: number;
53
+ copyOutMs: number;
54
+ restoreMs: number;
55
+ /** A slice trapped, so the calls ran again serially in place and that run decided the result. */
56
+ replayed: boolean;
57
+ /** `snapshot` when `writes` was past the limit and the calls ran serially in place. */
58
+ refused?: 'snapshot';
59
+ /** First line of the failure of the first failed slice. */
60
+ trap?: string;
61
+ tasks: TaskRecord[];
62
+ }
63
+ /** What one `run` did. */
64
+ export interface SliceReport {
65
+ slices: number;
66
+ workers: number;
67
+ wallMs: number;
68
+ /** The value each slice's last call returned, in slice order. */
69
+ results: (number | bigint | undefined)[];
70
+ audited: boolean;
71
+ ownership?: OwnedSliceReport;
72
+ }
73
+ /** The audit found the parallel run differs from the serial one. */
74
+ export declare class SliceConflictError extends Error {
75
+ readonly kind: 'memory' | 'result';
76
+ /** First differing byte for `memory`, the slice index for `result`. */
77
+ readonly at: number;
78
+ constructor(kind: 'memory' | 'result', at: number);
79
+ }
80
+ /** @internal */
81
+ export declare const encodeValues: (values: unknown) => string;
82
+ /** @internal */
83
+ export declare const decodeValues: (text: string) => unknown;
84
+ /**
85
+ * Marks the imported memory of a module as shared by setting its limits flag. The module has to
86
+ * declare a maximum already.
87
+ * @internal
88
+ */
89
+ export declare function sharedMemoryImport(bytes: Uint8Array): Uint8Array<ArrayBuffer>;
90
+ /**
91
+ * Runs slices of a call range on several threads over one shared memory, in place. The caller
92
+ * declares that the calls are independent and nothing tracks reads or writes, so a program that
93
+ * touches state the serial program would share returns a different result; `audit` finds that.
94
+ * Nothing is copied into a private context, which is why a bandwidth-bound kernel can win here
95
+ * while a route that copies its input first cannot. The module runs unmodified except for its
96
+ * memory import, which is marked shared. A module that keeps a stack pointer global gets one
97
+ * private stack per worker; any other mutable global, a start function or a data segment that
98
+ * is dropped refuses the module.
99
+ * @since 1.1.0
100
+ */
101
+ export declare class SlicePool {
102
+ #private;
103
+ private constructor();
104
+ /** The shared memory. Write the records into it after `open`, and read the results from it. */
105
+ get memory(): WebAssembly.Memory;
106
+ /** Worker count. */
107
+ get size(): number;
108
+ /** First byte of the private stacks and window copies, or undefined when there are none. */
109
+ get privateBase(): number | undefined;
110
+ /** First byte of the private stacks, or undefined when the module has no stack pointer. */
111
+ get stackBase(): number | undefined;
112
+ /**
113
+ * Compiles the module, grows the memory by one stack per worker when the module has a stack
114
+ * pointer, and starts the workers. Opening applies the module's data segments to the memory,
115
+ * so write the records after it returns.
116
+ */
117
+ static open(bytes: Uint8Array, options: SlicePoolOptions): Promise<SlicePool>;
118
+ /**
119
+ * Calls the exported function `entry` for the range `[0, count)` in slices, one slice per task.
120
+ * `args(from, to)` returns the i32 (or i64 as bigint) arguments of the call for a slice, in the
121
+ * owner thread. The caller guarantees the slices are independent.
122
+ */
123
+ run(entry: string, count: number, args: (from: number, to: number) => (number | bigint)[], options?: SliceRunOptions): Promise<SliceReport>;
124
+ /** Stops the workers. */
125
+ close(): Promise<void>;
126
+ }