@gmitch215/folio 0.0.0-stage → 1.0.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.
@@ -0,0 +1,9 @@
1
+ /** Minimal dedicated-worker scope, also usable by a host's event bridge. */
2
+ export interface BrowserWorkerScope {
3
+ onmessage: ((event: {
4
+ data: any;
5
+ }) => void) | null;
6
+ postMessage(value: unknown): void;
7
+ }
8
+ /** Installs the bounded native lane protocol. Attach only compiler-admitted original modules. */
9
+ export declare function installBrowserWorker(scope: BrowserWorkerScope): void;
@@ -0,0 +1,37 @@
1
+ /** Installs the bounded native lane protocol. Attach only compiler-admitted original modules. */
2
+ export function installBrowserWorker(scope) {
3
+ let instance;
4
+ scope.onmessage = ({ data }) => {
5
+ try {
6
+ let value;
7
+ if (data.action === 'attach') {
8
+ if (instance)
9
+ throw new Error('browser worker already attached');
10
+ const memory = data.memory;
11
+ if (!(memory.buffer instanceof SharedArrayBuffer))
12
+ throw new Error('shared WebAssembly.Memory required');
13
+ instance = new WebAssembly.Instance(data.module, {
14
+ [data.importModule]: { [data.importName]: memory }
15
+ });
16
+ const words = new Int32Array(memory.buffer);
17
+ value = Atomics.compareExchange(words, 0, data.before, data.after);
18
+ }
19
+ else if (data.action === 'run') {
20
+ if (!instance)
21
+ throw new Error('browser worker not attached');
22
+ const call = data.call;
23
+ if (!call.args.every((argument) => typeof argument === 'number'))
24
+ throw new TypeError('native lane accepts scalar numeric arguments only');
25
+ instance.exports[call.export](...call.args);
26
+ }
27
+ else
28
+ throw new Error('unknown browser worker action');
29
+ scope.postMessage({ sequence: data.sequence, value });
30
+ }
31
+ catch (error) {
32
+ scope.postMessage({ sequence: data.sequence, error: String(error) });
33
+ }
34
+ };
35
+ }
36
+ if (typeof self !== 'undefined' && typeof document === 'undefined')
37
+ installBrowserWorker(self);
@@ -0,0 +1,68 @@
1
+ import type { LoopPlan } from './compiler.ts';
2
+ import type { NativePlan } from './guards.ts';
3
+ import type { MemoryImport } from './memory.ts';
4
+ /** Trusted build-time metadata for a precompiled original module. No compiler runs in the browser. */
5
+ export interface BrowserProgram {
6
+ module: WebAssembly.Module;
7
+ loops: Record<string, LoopPlan>;
8
+ native?: Record<string, NativePlan>;
9
+ /** The unchanged legacy preparation reasons; only an empty list admits worker instantiation. */
10
+ reasons: string[];
11
+ memories?: MemoryImport[];
12
+ }
13
+ /** A dedicated module worker, or an equivalent host-supplied message port. */
14
+ export type BrowserWorkerPort = Pick<Worker, 'postMessage' | 'addEventListener' | 'removeEventListener' | 'terminate'>;
15
+ /** Browser execution configuration. The caller retains exclusive ownership during open and run. */
16
+ export interface BrowserOptions {
17
+ memory?: WebAssembly.Memory;
18
+ imports?: WebAssembly.Imports;
19
+ workers?: number;
20
+ workerURL?: string | URL;
21
+ workerFactory?: (index: number) => BrowserWorkerPort;
22
+ minimumParallelWork?: number;
23
+ }
24
+ /** A whole-entry result. Values remain wrapped so native externref Promise identity is preserved. */
25
+ export interface BrowserExecutionReport {
26
+ values: unknown[];
27
+ mode: 'serial' | 'native-shared';
28
+ workers: number;
29
+ regions: number;
30
+ reason?: string;
31
+ }
32
+ /** Counted-loop extraction over physically shared memory, without JSPI or runtime compilation. */
33
+ export declare class BrowserFolio {
34
+ #private;
35
+ readonly exports: WebAssembly.Exports;
36
+ readonly memory?: WebAssembly.Memory;
37
+ readonly diagnostics: readonly string[];
38
+ private constructor();
39
+ /** Opens the original instance and attaches only compiler-admitted, initialization-free workers. */
40
+ static open(program: BrowserProgram, options?: BrowserOptions): Promise<BrowserFolio>;
41
+ /** Describes counted-loop coverage; generalized control-flow extraction remains at the owner. */
42
+ inspect(entry: string): {
43
+ mechanism: "counted-loop";
44
+ loop: boolean;
45
+ nativeGuard: boolean;
46
+ workers: number;
47
+ };
48
+ /** Derives guarded regions from one ordinary call, then joins every lane before returning. */
49
+ run(entry: string, args?: unknown[], options?: {
50
+ parallel?: 'auto' | 'off';
51
+ }): Promise<{
52
+ values: any[];
53
+ mode: "serial";
54
+ workers: number;
55
+ regions: number;
56
+ reason: string;
57
+ } | {
58
+ values: undefined[];
59
+ mode: "native-shared";
60
+ workers: number;
61
+ regions: number;
62
+ reason?: undefined;
63
+ }>;
64
+ /** Joins an active finite call before terminating dedicated workers. */
65
+ close(): Promise<void>;
66
+ /** Joins execution and releases workers for `await using`. */
67
+ [Symbol.asyncDispose](): Promise<void>;
68
+ }
@@ -0,0 +1,274 @@
1
+ /** Counted-loop extraction over physically shared memory, without JSPI or runtime compilation. */
2
+ export class BrowserFolio {
3
+ exports;
4
+ memory;
5
+ diagnostics;
6
+ #program;
7
+ #workers = [];
8
+ #listeners = [];
9
+ #minimumWork;
10
+ #sequence = 0;
11
+ #closed = false;
12
+ #busy = false;
13
+ #failure;
14
+ #active;
15
+ #closing;
16
+ constructor(program, options) {
17
+ this.#program = program;
18
+ this.#minimumWork = options.minimumParallelWork ?? 100_000;
19
+ if (!Number.isFinite(this.#minimumWork) || this.#minimumWork < 0)
20
+ throw new RangeError('minimumParallelWork must be finite and nonnegative');
21
+ this.memory = options.memory;
22
+ const descriptor = program.memories?.length === 1 ? program.memories[0] : undefined;
23
+ const original = options.imports ?? {};
24
+ const imports = descriptor && this.memory
25
+ ? new Proxy(original, {
26
+ get: (target, module) => {
27
+ const namespace = Reflect.get(target, module, target);
28
+ if (module !== descriptor.module)
29
+ return namespace;
30
+ return new Proxy(namespace ?? {}, {
31
+ get: (bindings, name) => name === descriptor.name
32
+ ? this.memory
33
+ : Reflect.get(bindings, name, bindings)
34
+ });
35
+ }
36
+ })
37
+ : original;
38
+ this.exports = new WebAssembly.Instance(program.module, imports).exports;
39
+ this.diagnostics = Object.freeze([...program.reasons]);
40
+ }
41
+ /** Opens the original instance and attaches only compiler-admitted, initialization-free workers. */
42
+ static async open(program, options = {}) {
43
+ const width = options.workers ?? 4;
44
+ if (!Number.isInteger(width) || width < 1 || width > 32)
45
+ throw new RangeError('workers must be an integer from 1 through 32');
46
+ const pool = new BrowserFolio(program, options);
47
+ const descriptor = program.memories?.length === 1 ? program.memories[0] : undefined;
48
+ const bindings = WebAssembly.Module.imports(program.module);
49
+ const eligible = width > 1 &&
50
+ program.reasons.length === 0 &&
51
+ Object.keys(program.native ?? {}).some((name) => Object.hasOwn(program.loops, name)) &&
52
+ descriptor?.shared &&
53
+ !descriptor.memory64 &&
54
+ bindings.length === 1 &&
55
+ bindings[0].kind === 'memory' &&
56
+ bindings[0].module === descriptor.module &&
57
+ bindings[0].name === descriptor.name &&
58
+ pool.memory &&
59
+ typeof SharedArrayBuffer !== 'undefined' &&
60
+ pool.memory.buffer.byteLength >= 4 &&
61
+ pool.memory.buffer instanceof SharedArrayBuffer;
62
+ if (!eligible)
63
+ return pool;
64
+ const memory = pool.memory;
65
+ const words = new Int32Array(memory.buffer);
66
+ const saved = Atomics.load(words, 0);
67
+ try {
68
+ for (let index = 0; index < width; index++) {
69
+ const worker = options.workerFactory
70
+ ? options.workerFactory(index)
71
+ : new Worker(options.workerURL ?? new URL('./browser-worker.js', import.meta.url), {
72
+ type: 'module'
73
+ });
74
+ pool.#workers.push(worker);
75
+ const fail = () => {
76
+ pool.#failure ??= new Error('browser worker failed; shared arena requires checkpoint recovery');
77
+ };
78
+ worker.addEventListener('error', fail);
79
+ worker.addEventListener('messageerror', fail);
80
+ pool.#listeners.push(() => {
81
+ worker.removeEventListener('error', fail);
82
+ worker.removeEventListener('messageerror', fail);
83
+ });
84
+ const before = (0x46100000 + index) | 0;
85
+ const after = (before ^ 0x00ffffff) | 0;
86
+ Atomics.store(words, 0, before);
87
+ const result = await pool.#request(worker, {
88
+ action: 'attach',
89
+ module: program.module,
90
+ memory,
91
+ importModule: descriptor.module,
92
+ importName: descriptor.name,
93
+ before,
94
+ after
95
+ });
96
+ if (result !== before || Atomics.load(words, 0) !== after)
97
+ throw new Error('browser worker shared-memory alias handshake failed');
98
+ }
99
+ return pool;
100
+ }
101
+ catch (error) {
102
+ pool.#terminate();
103
+ throw error;
104
+ }
105
+ finally {
106
+ Atomics.store(words, 0, saved);
107
+ }
108
+ }
109
+ /** Describes counted-loop coverage; generalized control-flow extraction remains at the owner. */
110
+ inspect(entry) {
111
+ return {
112
+ mechanism: 'counted-loop',
113
+ loop: Object.hasOwn(this.#program.loops, entry),
114
+ nativeGuard: Object.hasOwn(this.#program.native ?? {}, entry),
115
+ workers: this.#workers.length
116
+ };
117
+ }
118
+ #request(worker, message) {
119
+ const sequence = ++this.#sequence;
120
+ return new Promise((resolve, reject) => {
121
+ const cleanup = () => {
122
+ worker.removeEventListener('message', done);
123
+ worker.removeEventListener('error', fail);
124
+ worker.removeEventListener('messageerror', fail);
125
+ };
126
+ const fail = (event) => {
127
+ cleanup();
128
+ reject(new Error(event.message || 'browser worker failed'));
129
+ };
130
+ const done = (event) => {
131
+ if (event.data?.sequence !== sequence)
132
+ return;
133
+ cleanup();
134
+ if (event.data.error)
135
+ reject(new Error(event.data.error));
136
+ else
137
+ resolve(event.data.value);
138
+ };
139
+ worker.addEventListener('message', done);
140
+ worker.addEventListener('error', fail);
141
+ worker.addEventListener('messageerror', fail);
142
+ try {
143
+ worker.postMessage({ ...message, sequence });
144
+ }
145
+ catch (error) {
146
+ cleanup();
147
+ reject(error);
148
+ }
149
+ });
150
+ }
151
+ #disjoint(calls, proved, plan) {
152
+ const footprints = calls.map((call) => proved.accesses.map((access) => {
153
+ const first = Number(call.args[access.parameter]) >>> 0;
154
+ const count = Number(call.args[plan.countParameter]) >>> 0;
155
+ const step = plan.steps.find((item) => item.parameter === access.parameter)?.step ?? 0;
156
+ const last = first + (count - 1) * step;
157
+ return {
158
+ start: Math.min(first, last) + access.offset,
159
+ end: Math.max(first, last) + access.offset + access.bytes,
160
+ write: access.write,
161
+ wrap: last < 0 || last > 0xffffffff
162
+ };
163
+ }));
164
+ for (let index = 0; index < footprints.length; index++) {
165
+ for (const range of footprints[index]) {
166
+ if (range.wrap || range.start < 0 || range.end > this.memory.buffer.byteLength)
167
+ return false;
168
+ for (const other of footprints.slice(0, index).flat())
169
+ if ((range.write || other.write) &&
170
+ range.start < other.end &&
171
+ other.start < range.end)
172
+ return false;
173
+ }
174
+ }
175
+ return true;
176
+ }
177
+ /** Derives guarded regions from one ordinary call, then joins every lane before returning. */
178
+ run(entry, args = [], options = {}) {
179
+ if (this.#closed)
180
+ return Promise.reject(new Error('folio is closed'));
181
+ if (this.#failure)
182
+ return Promise.reject(this.#failure);
183
+ if (this.#busy)
184
+ return Promise.reject(new Error('memory already has an active run'));
185
+ this.#busy = true;
186
+ const running = this.#run(entry, args, options);
187
+ this.#active = running;
188
+ running
189
+ .finally(() => {
190
+ this.#busy = false;
191
+ if (this.#active === running)
192
+ this.#active = undefined;
193
+ })
194
+ .catch(() => { });
195
+ return running;
196
+ }
197
+ async #run(entry, args, options) {
198
+ const plan = Object.hasOwn(this.#program.loops, entry)
199
+ ? this.#program.loops[entry]
200
+ : undefined;
201
+ const proved = Object.hasOwn(this.#program.native ?? {}, entry)
202
+ ? this.#program.native[entry]
203
+ : undefined;
204
+ const numeric = args.every((arg) => typeof arg === 'number');
205
+ const count = plan && numeric ? Number(args[plan.countParameter]) >>> 0 : 0;
206
+ const work = numeric
207
+ ? proved?.workParameters.reduce((value, parameter) => value * (Number(args[parameter]) >>> 0), count)
208
+ : undefined;
209
+ let reason = options.parallel === 'off'
210
+ ? 'requested'
211
+ : !numeric
212
+ ? 'opaque-input'
213
+ : !plan || !proved || this.#workers.length < 2
214
+ ? 'no-parallel-plan'
215
+ : count < 2
216
+ ? 'single-region'
217
+ : work !== undefined && work < this.#minimumWork
218
+ ? 'small-workload'
219
+ : undefined;
220
+ const calls = [];
221
+ if (!reason && plan && proved) {
222
+ const regions = Math.min(count, this.#workers.length);
223
+ let begin = 0;
224
+ for (let index = 0; index < regions; index++) {
225
+ const end = Math.floor(((index + 1) * count) / regions);
226
+ const parameters = [...args];
227
+ parameters[plan.countParameter] = end - begin;
228
+ for (const { parameter, step } of plan.steps)
229
+ parameters[parameter] =
230
+ ((Number(args[parameter]) | 0) + Math.imul(begin, step)) | 0;
231
+ calls.push({ export: entry, args: parameters });
232
+ begin = end;
233
+ }
234
+ if (!this.#disjoint(calls, proved, plan))
235
+ reason = 'guard-failed';
236
+ }
237
+ if (reason) {
238
+ const value = this.exports[entry](...args);
239
+ return { values: [value], mode: 'serial', workers: 0, regions: 1, reason };
240
+ }
241
+ const outcomes = await Promise.allSettled(calls.map((call, index) => this.#request(this.#workers[index], { action: 'run', call })));
242
+ if (outcomes.some((outcome) => outcome.status === 'rejected')) {
243
+ this.#failure = new Error('native region failed; shared arena requires checkpoint recovery');
244
+ this.#terminate();
245
+ throw this.#failure;
246
+ }
247
+ return {
248
+ values: [undefined],
249
+ mode: 'native-shared',
250
+ workers: calls.length,
251
+ regions: calls.length
252
+ };
253
+ }
254
+ #terminate() {
255
+ for (const detach of this.#listeners)
256
+ detach();
257
+ this.#listeners.length = 0;
258
+ for (const worker of this.#workers)
259
+ worker.terminate();
260
+ this.#workers.length = 0;
261
+ }
262
+ /** Joins an active finite call before terminating dedicated workers. */
263
+ close() {
264
+ this.#closed = true;
265
+ return (this.#closing ??= (async () => {
266
+ await this.#active?.catch(() => { });
267
+ this.#terminate();
268
+ })());
269
+ }
270
+ /** Joins execution and releases workers for `await using`. */
271
+ [Symbol.asyncDispose]() {
272
+ return this.close();
273
+ }
274
+ }
@@ -0,0 +1,43 @@
1
+ import type { AdmissionOptions, ControlPlan } from './extract.ts';
2
+ import type { NativePlan } from './guards.ts';
3
+ /** A counted loop the splitter can divide: the count parameter and the affine pointer steps. */
4
+ export interface LoopPlan {
5
+ /** Index of the parameter holding the iteration count. */
6
+ countParameter: number;
7
+ /** Pointer parameters that advance by `step` bytes per iteration. */
8
+ steps: {
9
+ parameter: number;
10
+ step: number;
11
+ }[];
12
+ }
13
+ /** The output of `prepare`: the untouched program plus the artifacts workers need. Trusted build artifact. */
14
+ export interface PreparedProgram {
15
+ /** The source module bytes; the coordinator runs these unchanged. */
16
+ original: Uint8Array;
17
+ /** Optional precompiled module for hosts that cannot compile at request time. */
18
+ compiled?: WebAssembly.Module;
19
+ /** The tracked worker module that records byte reads and writes. */
20
+ transactional?: Uint8Array;
21
+ /** Counted-loop plans by export name. */
22
+ loops: Record<string, LoopPlan>;
23
+ /** Why an export has no loop plan. */
24
+ loopReasons?: Record<string, string>;
25
+ /** Module-wide reasons optimization was refused. */
26
+ reasons: string[];
27
+ /** Native guard plans by export name. */
28
+ native?: Record<string, NativePlan>;
29
+ /** The generalized control-flow plan, when the module admits one. */
30
+ control?: ControlPlan;
31
+ /** Why control-flow extraction produced no plan; the counted-loop plans above are unaffected. */
32
+ controlReasons?: string[];
33
+ }
34
+ /** Plan options: whether to optimize, and when a region is worth dispatching. */
35
+ export interface PrepareOptions extends AdmissionOptions {
36
+ /** `off` keeps the original module with no plan. */
37
+ parallel?: 'auto' | 'off';
38
+ }
39
+ /**
40
+ * Keeps the original native module and adds independently validated optimizations. A module
41
+ * with no region above `minimumRegionWork` gets no control plan and runs untouched.
42
+ */
43
+ export declare function prepare(bytes: Uint8Array, options?: PrepareOptions): PreparedProgram;