@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,189 @@
1
+ function trap(result) {
2
+ if (!result.trap)
3
+ return;
4
+ if (result.errorKind === 'TypeError')
5
+ throw new TypeError(result.trap);
6
+ if (result.errorKind === 'RangeError')
7
+ throw new RangeError(result.trap);
8
+ throw new WebAssembly.RuntimeError(result.trap);
9
+ }
10
+ /** Owns only effect-free regions. The original Wasm stack remains the coordinator. */
11
+ export class Coordinator {
12
+ report;
13
+ #queue = [];
14
+ #memory;
15
+ #workerMemory;
16
+ #width;
17
+ #dispatch;
18
+ #native;
19
+ #profile;
20
+ #pending;
21
+ #armed = false;
22
+ #polls = 0;
23
+ #flushing;
24
+ constructor(options) {
25
+ this.#pending = options.pending;
26
+ this.#memory = options.memory;
27
+ this.#workerMemory = options.workerMemory;
28
+ this.#width = options.width;
29
+ this.#dispatch = options.dispatch;
30
+ this.#native = options.native;
31
+ this.#profile = options.profile
32
+ ? {
33
+ wallMs: 0,
34
+ workerWallMs: [],
35
+ workerCpuMs: [],
36
+ validationMs: 0,
37
+ commitMs: 0,
38
+ replayMs: 0,
39
+ readBytes: 0,
40
+ writeBytes: 0
41
+ }
42
+ : undefined;
43
+ this.report = {
44
+ values: [],
45
+ workers: 0,
46
+ regions: 0,
47
+ replayed: 0,
48
+ fallbacks: 0,
49
+ mode: 'serial',
50
+ extraction: 'control-flow',
51
+ memoryMode: this.#memory === this.#workerMemory ? 'shared' : 'snapshot',
52
+ snapshotBytes: 0,
53
+ ...(this.#profile ? { profile: this.#profile } : {})
54
+ };
55
+ }
56
+ enqueue(call) {
57
+ if (!this.#armed) {
58
+ this.#armed = true;
59
+ if (this.#pending)
60
+ this.#pending.value = 1;
61
+ }
62
+ this.#queue.push(call);
63
+ this.report.regions++;
64
+ // Amortize transport/join cost without changing per-region validation order.
65
+ return this.#queue.length >= this.#width * 16 ? this.flush() : undefined;
66
+ }
67
+ /** Bounded polling also joins an earlier trapping region before an infinite loop. */
68
+ poll() {
69
+ if (++this.#polls < 1024)
70
+ return undefined;
71
+ this.#polls = 0;
72
+ return this.flush();
73
+ }
74
+ flush() {
75
+ if (this.#flushing)
76
+ return this.#flushing;
77
+ if (!this.#queue.length) {
78
+ this.#settle();
79
+ return undefined;
80
+ }
81
+ const batch = this.#queue.splice(0);
82
+ const pending = this.#execute(batch);
83
+ this.#flushing = pending;
84
+ return pending.finally(() => {
85
+ this.#flushing = undefined;
86
+ this.#settle();
87
+ });
88
+ }
89
+ #settle() {
90
+ if (!this.#armed || this.#queue.length)
91
+ return;
92
+ this.#armed = false;
93
+ if (this.#pending)
94
+ this.#pending.value = 0;
95
+ }
96
+ async #execute(batch) {
97
+ if (batch.length === 1) {
98
+ // An observation boundary left no independent companion. Keep the work
99
+ // at its original owner; IPC and a full ordinary-memory snapshot buy nothing.
100
+ if (this.report.mode === 'serial')
101
+ this.report.reason = 'single-region';
102
+ this.#native(batch[0]);
103
+ return;
104
+ }
105
+ if (this.report.reason === 'single-region')
106
+ delete this.report.reason;
107
+ if (this.#memory !== this.#workerMemory) {
108
+ try {
109
+ const pages = this.#memory.buffer.byteLength / 65536;
110
+ const current = this.#workerMemory.buffer.byteLength / 65536;
111
+ if (pages > current)
112
+ this.#workerMemory.grow(pages - current);
113
+ new Uint8Array(this.#workerMemory.buffer).set(new Uint8Array(this.#memory.buffer));
114
+ this.report.snapshotBytes += this.#memory.buffer.byteLength;
115
+ }
116
+ catch (error) {
117
+ if (!(error instanceof RangeError))
118
+ throw error;
119
+ // A failed optimization allocation must not introduce a program trap.
120
+ this.report.fallbacks++;
121
+ for (const call of batch)
122
+ this.#native(call);
123
+ return;
124
+ }
125
+ }
126
+ this.report.mode = 'speculative';
127
+ const width = Math.min(this.#width, batch.length);
128
+ this.report.workers = Math.max(this.report.workers, width);
129
+ const lanes = Array.from({ length: width }, (_, lane) => batch.filter((_, index) => index % width === lane));
130
+ const outcomes = await Promise.allSettled(lanes.map((calls, i) => this.#dispatch(i, calls)));
131
+ const failure = outcomes.find((outcome) => outcome.status === 'rejected');
132
+ if (failure?.status === 'rejected')
133
+ throw failure.reason;
134
+ const dirty = new Set();
135
+ const canonical = new Uint8Array(this.#memory.buffer);
136
+ const shared = new Uint8Array(this.#workerMemory.buffer);
137
+ const observe = (result) => {
138
+ if (!this.#profile)
139
+ return;
140
+ this.#profile.workerWallMs.push(result.timing.wallMs);
141
+ this.#profile.workerCpuMs.push(result.timing.cpuMs);
142
+ this.#profile.readBytes += result.reads.length;
143
+ this.#profile.writeBytes += result.writes.length;
144
+ };
145
+ const commit = (result) => {
146
+ const start = this.#profile ? performance.now() : 0;
147
+ for (const [address, value] of result.writes) {
148
+ canonical[address] = value;
149
+ if (this.#memory !== this.#workerMemory)
150
+ shared[address] = value;
151
+ dirty.add(address);
152
+ }
153
+ if (this.#profile)
154
+ this.#profile.commitMs += performance.now() - start;
155
+ };
156
+ for (let i = 0; i < batch.length; i++) {
157
+ const outcome = outcomes[i % width];
158
+ let result = outcome.value[Math.floor(i / width)];
159
+ observe(result);
160
+ const start = this.#profile ? performance.now() : 0;
161
+ const conflict = result.reads.some((address) => dirty.has(address));
162
+ if (this.#profile)
163
+ this.#profile.validationMs += performance.now() - start;
164
+ if (result.exhausted || conflict) {
165
+ if (result.exhausted)
166
+ this.report.fallbacks++;
167
+ else {
168
+ this.report.replayed++;
169
+ this.report.reason = 'dependency';
170
+ }
171
+ if (!result.exhausted) {
172
+ const replayStart = this.#profile ? performance.now() : 0;
173
+ result = (await this.#dispatch(0, [batch[i]]))[0];
174
+ observe(result);
175
+ if (this.#profile)
176
+ this.#profile.replayMs += performance.now() - replayStart;
177
+ }
178
+ if (result.exhausted) {
179
+ // Unknown native write footprints invalidate every later speculative result.
180
+ for (let rest = i; rest < batch.length; rest++)
181
+ this.#native(batch[rest]);
182
+ return;
183
+ }
184
+ }
185
+ commit(result);
186
+ trap(result);
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,71 @@
1
+ /** Region admission. Both values are estimates in instruction units, not guarantees. */
2
+ export interface AdmissionOptions {
3
+ /**
4
+ * Net work a region needs before dispatch, join and validation can pay for themselves; 0 admits
5
+ * every pure region. A loop bounded by a parameter is checked against the call's arguments.
6
+ */
7
+ minimumRegionWork?: number;
8
+ /** Iterations assumed for a loop whose bound is neither a constant nor a parameter. */
9
+ assumedTripCount?: number;
10
+ }
11
+ /** Calibrated on Apple M2 Pro; see `results/20261020-regress/admission-calibration.summary.json`. */
12
+ export declare const DEFAULT_MINIMUM_REGION_WORK = 200000;
13
+ export declare const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
14
+ export interface ControlPlan {
15
+ coordinator: Uint8Array;
16
+ workerOriginal: Uint8Array;
17
+ transactional: Uint8Array;
18
+ namespace: string;
19
+ serialGlobal: string;
20
+ pendingGlobal: string;
21
+ memoryExport: string;
22
+ shared: boolean;
23
+ initial: number;
24
+ maximum: number;
25
+ entries: string[];
26
+ regions: {
27
+ importName: string;
28
+ exportName: string;
29
+ parameters: ('i32' | 'i64')[];
30
+ }[];
31
+ diagnostics: string[];
32
+ }
33
+ export interface Work {
34
+ compute: number;
35
+ accesses: number;
36
+ }
37
+ /** Work that grows with the product of the listed parameters, each bounding a loop. */
38
+ export interface Term extends Work {
39
+ params: number[];
40
+ }
41
+ /** Which locals feed a loop bound untouched, and which are written and so can count. */
42
+ export interface LoopInputs {
43
+ input(index: number): boolean;
44
+ counter(index: number): boolean;
45
+ }
46
+ /**
47
+ * Trip-weighted instruction and tracked-access counts of one body, calls included. A loop bounded
48
+ * by an untouched input makes a term in that local; other unknown bounds use `assumedTrips`.
49
+ */
50
+ export declare function estimateTerms(body: number, callee: (name: string) => Work | undefined, assumedTrips: number, inputs?: LoopInputs): Term[];
51
+ /** Numeric work with every parameter-bounded loop assumed to run `assumedTrips` times. */
52
+ export declare function settleWork(terms: readonly Term[], assumedTrips: number): Work;
53
+ export declare function estimateWork(body: number, callee: (name: string) => Work | undefined, assumedTrips: number): Work;
54
+ export declare const netWork: (work: Work) => number;
55
+ /** Resolves defaults and rejects values the estimate cannot use. */
56
+ export declare function admission(options: AdmissionOptions): {
57
+ minimumWork: number;
58
+ assumedTrips: number;
59
+ };
60
+ export declare function extract(original: Uint8Array, prepareTracked: (bytes: Uint8Array) => {
61
+ transactional?: Uint8Array;
62
+ }, options?: AdmissionOptions & {
63
+ refused?: (reason: string) => void;
64
+ /** called once per candidate span or pure function with its estimate and verdict */
65
+ observed?: (site: {
66
+ name: string;
67
+ kind: string;
68
+ compute: number;
69
+ accesses: number;
70
+ }) => void;
71
+ }): ControlPlan | undefined;