@gmitch215/folio 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +98 -460
  2. package/dist/boot.d.ts +1 -0
  3. package/dist/boot.js +1 -0
  4. package/dist/browser/index.d.ts +73 -0
  5. package/dist/browser/index.js +277 -0
  6. package/dist/browser.d.ts +1 -68
  7. package/dist/browser.js +1 -274
  8. package/dist/continuation.d.ts +1 -0
  9. package/dist/continuation.js +1 -0
  10. package/dist/{compiler.d.ts → execution/compiler.d.ts} +1 -1
  11. package/dist/{compiler.js → execution/compiler.js} +5 -12
  12. package/dist/{coordinator.d.ts → execution/coordinator.d.ts} +1 -1
  13. package/dist/{coordinator.js → execution/coordinator.js} +55 -8
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +22 -13
  15. package/dist/{extract.js → execution/extract.js} +137 -10
  16. package/dist/execution/fold.d.ts +44 -0
  17. package/dist/execution/fold.js +105 -0
  18. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  19. package/dist/execution/runs.d.ts +44 -0
  20. package/dist/execution/runs.js +182 -0
  21. package/dist/{transaction.d.ts → execution/transaction.d.ts} +10 -0
  22. package/dist/execution/types.d.ts +221 -0
  23. package/dist/folds/affine-state.d.ts +142 -0
  24. package/dist/folds/affine-state.js +737 -0
  25. package/dist/folds/affine.d.ts +148 -0
  26. package/dist/folds/affine.js +562 -0
  27. package/dist/folds/boundaries.d.ts +48 -0
  28. package/dist/folds/boundaries.js +119 -0
  29. package/dist/folds/certified.d.ts +55 -0
  30. package/dist/folds/certified.js +178 -0
  31. package/dist/folds/certify.d.ts +87 -0
  32. package/dist/folds/certify.js +2611 -0
  33. package/dist/footprints/memo.d.ts +74 -0
  34. package/dist/footprints/memo.js +256 -0
  35. package/dist/footprints/ranges.d.ts +78 -0
  36. package/dist/footprints/ranges.js +263 -0
  37. package/dist/footprints/read-scan.d.ts +18 -0
  38. package/dist/footprints/read-scan.js +94 -0
  39. package/dist/footprints/read-windows.d.ts +77 -0
  40. package/dist/footprints/read-windows.js +245 -0
  41. package/dist/index.d.ts +16 -4
  42. package/dist/index.js +14 -2
  43. package/dist/iteration/admission.d.ts +149 -0
  44. package/dist/iteration/admission.js +201 -0
  45. package/dist/iteration/index.d.ts +239 -0
  46. package/dist/iteration/index.js +1210 -0
  47. package/dist/iteration/inline.d.ts +182 -0
  48. package/dist/{inline.js → iteration/inline.js} +277 -21
  49. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +16 -3
  50. package/dist/{iteration-owner.js → iteration/owner.js} +6 -5
  51. package/dist/iteration/worker.js +216 -0
  52. package/dist/{managed.d.ts → managed/index.d.ts} +75 -3
  53. package/dist/managed/index.js +817 -0
  54. package/dist/managed/outbox.d.ts +128 -0
  55. package/dist/managed/outbox.js +156 -0
  56. package/dist/managed/pool.d.ts +221 -0
  57. package/dist/managed/pool.js +310 -0
  58. package/dist/managed/tasks.d.ts +154 -0
  59. package/dist/managed/tasks.js +183 -0
  60. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  61. package/dist/{bake.js → memory/bake.js} +9 -7
  62. package/dist/memory/continuation.d.ts +141 -0
  63. package/dist/memory/continuation.js +495 -0
  64. package/dist/memory/elastic-peer.d.ts +20 -0
  65. package/dist/memory/elastic-peer.js +39 -0
  66. package/dist/memory/elastic-sql.d.ts +11 -0
  67. package/dist/memory/elastic-sql.js +35 -0
  68. package/dist/memory/elastic.d.ts +130 -0
  69. package/dist/memory/elastic.js +475 -0
  70. package/dist/memory/growth-governor.d.ts +16 -0
  71. package/dist/memory/growth-governor.js +42 -0
  72. package/dist/memory/imports.d.ts +10 -0
  73. package/dist/memory/imports.js +89 -0
  74. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +61 -1
  75. package/dist/{iteration-layout.js → memory/iteration-layout.js} +54 -3
  76. package/dist/memory/lease.d.ts +45 -0
  77. package/dist/memory/lease.js +274 -0
  78. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  79. package/dist/memory.d.ts +5 -10
  80. package/dist/memory.js +5 -89
  81. package/dist/{context.d.ts → node/context.d.ts} +17 -3
  82. package/dist/{context.js → node/context.js} +60 -14
  83. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  84. package/dist/{host.js → node/host.js} +2 -2
  85. package/dist/{node.d.ts → node/index.d.ts} +46 -49
  86. package/dist/{node.js → node/index.js} +101 -26
  87. package/dist/{tasks.d.ts → node/tasks.d.ts} +16 -17
  88. package/dist/{tasks.js → node/tasks.js} +12 -11
  89. package/dist/node/worker.d.ts +1 -0
  90. package/dist/{worker.js → node/worker.js} +2 -2
  91. package/dist/ownership/index.d.ts +161 -0
  92. package/dist/ownership/index.js +6565 -0
  93. package/dist/ownership/redirect.d.ts +30 -0
  94. package/dist/ownership/redirect.js +179 -0
  95. package/dist/ownership/slices.d.ts +44 -0
  96. package/dist/ownership/slices.js +72 -0
  97. package/dist/{frames.d.ts → remote/frames.d.ts} +6 -2
  98. package/dist/remote/frames.js +306 -0
  99. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  100. package/dist/{remote.js → remote/index.js} +7 -2
  101. package/dist/routing/index.d.ts +203 -0
  102. package/dist/routing/index.js +671 -0
  103. package/dist/routing/worker.d.ts +1 -0
  104. package/dist/routing/worker.js +4 -0
  105. package/dist/slices/index.d.ts +126 -0
  106. package/dist/slices/index.js +441 -0
  107. package/dist/slices/worker.d.ts +1 -0
  108. package/dist/slices/worker.js +38 -0
  109. package/dist/workers.d.ts +5 -0
  110. package/dist/workers.js +5 -0
  111. package/package.json +32 -46
  112. package/dist/frames.js +0 -159
  113. package/dist/inline.d.ts +0 -68
  114. package/dist/iteration-admission.d.ts +0 -76
  115. package/dist/iteration-admission.js +0 -72
  116. package/dist/iteration-worker.js +0 -150
  117. package/dist/iteration.d.ts +0 -163
  118. package/dist/iteration.js +0 -435
  119. package/dist/managed.js +0 -421
  120. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  121. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  122. /package/dist/{guards.js → execution/guards.js} +0 -0
  123. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  124. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  125. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  126. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  127. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  128. /package/dist/{pages.js → memory/pages.js} +0 -0
  129. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  130. /package/dist/{values.js → remote/values.js} +0 -0
package/dist/browser.js CHANGED
@@ -1,274 +1 @@
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
- }
1
+ export * from "./browser/index.js";
@@ -0,0 +1 @@
1
+ export * from './memory/continuation.ts';
@@ -0,0 +1 @@
1
+ export * from "./memory/continuation.js";
@@ -1,6 +1,6 @@
1
1
  import type { AdmissionOptions, ControlPlan, IterationRoute, StackRoute } from './extract.ts';
2
2
  import type { NativePlan } from './guards.ts';
3
- /** Offline exports used to checkpoint a private instance; function bodies remain unchanged. */
3
+ /** Exports added so a caller can checkpoint an instance. */
4
4
  export interface PreparedContext {
5
5
  /** The module as passed in. */
6
6
  original: Uint8Array;
@@ -1,5 +1,5 @@
1
1
  import binaryen from 'binaryen';
2
- import { admission, extract, iterationRoute, stackRoute } from "./extract.js";
2
+ import { admission, extract, info, iterationRoute, stackRoute } from "./extract.js";
3
3
  import { nativePlan } from "./guards.js";
4
4
  /**
5
5
  * Exposes Wasm memories, mutable globals and tables for private-context reset. This adds exports
@@ -114,13 +114,6 @@ export function prepareContext(input) {
114
114
  }
115
115
  return result;
116
116
  }
117
- const info = (expression) => {
118
- const id = binaryen.getExpressionId(expression);
119
- if (id === binaryen.UnreachableId || id === binaryen.NopId) {
120
- return { id, type: binaryen.getExpressionType(expression) };
121
- }
122
- return binaryen.getExpressionInfo(expression);
123
- };
124
117
  function walk(expression, visit) {
125
118
  const value = info(expression);
126
119
  visit(value);
@@ -147,7 +140,7 @@ function walk(expression, visit) {
147
140
  walk(value[key], visit);
148
141
  }
149
142
  }
150
- function loopPlan(module, fn, diagnostic) {
143
+ function loopPlan(fn, diagnostic) {
151
144
  const f = binaryen.getFunctionInfo(fn);
152
145
  if (f.results !== binaryen.none) {
153
146
  diagnostic.reason = 'non-void entry requires a result merge';
@@ -343,8 +336,8 @@ function prepareTracked(bytes, options = {}) {
343
336
  const nativePlans = {};
344
337
  try {
345
338
  const module = (analysisModule = binaryen.readBinary(original));
346
- // Native validation already established the source instruction set. Binaryen
347
- // does not infer every proposal flag from a binary's instruction bodies.
339
+ // native validation already fixed the source instruction set; binaryen
340
+ // does not infer every proposal flag from a binary's instruction bodies
348
341
  const compactImports = binaryen.Features
349
342
  .CompactImports;
350
343
  module.setFeatures(binaryen.Features.All & ~compactImports);
@@ -416,7 +409,7 @@ function prepareTracked(bytes, options = {}) {
416
409
  }
417
410
  });
418
411
  const diagnostic = { reason: 'loop shape not recognized' };
419
- const plan = loopPlan(module, fn, diagnostic);
412
+ const plan = loopPlan(fn, diagnostic);
420
413
  const names = exportedFunctions.get(f.name) ?? [];
421
414
  const proved = names.length && plan ? nativePlan(module, fn) : undefined;
422
415
  for (const name of names) {
@@ -1,5 +1,5 @@
1
- import type { ExecutionReport } from './node.ts';
2
1
  import type { TransactionResult } from './transaction.ts';
2
+ import type { ExecutionReport } from './types.ts';
3
3
  export interface RegionCall {
4
4
  export: string;
5
5
  args: readonly (number | bigint)[];
@@ -1,3 +1,4 @@
1
+ import { DirtyRuns, runBytes } from "./runs.js";
1
2
  function trap(result) {
2
3
  if (!result.trap)
3
4
  return;
@@ -62,7 +63,7 @@ export class Coordinator {
62
63
  }
63
64
  this.#queue.push(call);
64
65
  this.report.regions++;
65
- // Amortize transport/join cost without changing per-region validation order.
66
+ // amortize transport and join cost without changing per-region validation order
66
67
  return this.#queue.length >= this.#width * 16 ? this.flush() : undefined;
67
68
  }
68
69
  /** Bounded polling also joins an earlier trapping region before an infinite loop. */
@@ -96,8 +97,8 @@ export class Coordinator {
96
97
  }
97
98
  async #execute(batch) {
98
99
  if (batch.length === 1) {
99
- // An observation boundary left no independent companion. Keep the work
100
- // at its original owner; IPC and a full ordinary-memory snapshot buy nothing.
100
+ // an observation boundary left no independent companion; keep the work
101
+ // at its original owner, since IPC and a full memory snapshot buy nothing
101
102
  if (this.report.mode === 'serial')
102
103
  this.report.reason = 'single-region';
103
104
  this.#native(batch[0]);
@@ -117,7 +118,7 @@ export class Coordinator {
117
118
  catch (error) {
118
119
  if (!(error instanceof RangeError))
119
120
  throw error;
120
- // A failed optimization allocation must not introduce a program trap.
121
+ // a failed optimization allocation must not introduce a program trap
121
122
  this.report.fallbacks++;
122
123
  for (const call of batch)
123
124
  this.#native(call);
@@ -134,6 +135,7 @@ export class Coordinator {
134
135
  if (failure?.status === 'rejected')
135
136
  throw failure.reason;
136
137
  const dirty = new Set();
138
+ const dirtyRuns = new DirtyRuns();
137
139
  const canonical = new Uint8Array(this.#memory.buffer);
138
140
  const shared = new Uint8Array(this.#workerMemory.buffer);
139
141
  const observe = (result) => {
@@ -141,8 +143,12 @@ export class Coordinator {
141
143
  return;
142
144
  this.#profile.workerWallMs.push(result.timing.wallMs);
143
145
  this.#profile.workerCpuMs.push(result.timing.cpuMs);
144
- this.#profile.readBytes += result.reads.length;
145
- this.#profile.writeBytes += result.writes.length;
146
+ this.#profile.readBytes += result.readRuns
147
+ ? runBytes(result.readRuns)
148
+ : result.reads.length;
149
+ this.#profile.writeBytes += result.writeData
150
+ ? result.writeData.length
151
+ : result.writes.length;
146
152
  };
147
153
  const commit = (result) => {
148
154
  const start = this.#profile ? performance.now() : 0;
@@ -152,6 +158,28 @@ export class Coordinator {
152
158
  shared[address] = value;
153
159
  dirty.add(address);
154
160
  }
161
+ if (result.writeRuns) {
162
+ let at = 0;
163
+ for (let i = 0; i < result.writeRuns.length; i += 2) {
164
+ const start = result.writeRuns[i], length = result.writeRuns[i + 1];
165
+ const data = result.writeData;
166
+ const mirror = this.#memory !== this.#workerMemory;
167
+ if (length > 16) {
168
+ const piece = data.subarray(at, at + length);
169
+ canonical.set(piece, start);
170
+ if (mirror)
171
+ shared.set(piece, start);
172
+ }
173
+ else
174
+ for (let k = 0; k < length; k++) {
175
+ canonical[start + k] = data[at + k];
176
+ if (mirror)
177
+ shared[start + k] = data[at + k];
178
+ }
179
+ dirtyRuns.add(start, length);
180
+ at += length;
181
+ }
182
+ }
155
183
  if (this.#profile)
156
184
  this.#profile.commitMs += performance.now() - start;
157
185
  };
@@ -160,7 +188,13 @@ export class Coordinator {
160
188
  let result = outcome.value[Math.floor(i / width)];
161
189
  observe(result);
162
190
  const start = this.#profile ? performance.now() : 0;
163
- const conflict = result.reads.some((address) => dirty.has(address));
191
+ // a batch's results share one encoding; both paths stay exact if they ever mix
192
+ const stored = dirtyRuns.count > 0;
193
+ const conflict = result.reads.some((address) => dirty.has(address) || (stored && dirtyRuns.has(address))) ||
194
+ (result.readRuns !== undefined &&
195
+ (dirtyRuns.overlaps(result.readRuns) ||
196
+ (dirty.size > 0 &&
197
+ [...dirty].some((address) => overlapsRuns(result.readRuns, address)))));
164
198
  if (this.#profile)
165
199
  this.#profile.validationMs += performance.now() - start;
166
200
  if (result.exhausted || conflict) {
@@ -178,7 +212,7 @@ export class Coordinator {
178
212
  this.#profile.replayMs += performance.now() - replayStart;
179
213
  }
180
214
  if (result.exhausted) {
181
- // Unknown native write footprints invalidate every later speculative result.
215
+ // unknown native write footprints invalidate every later speculative result
182
216
  for (let rest = i; rest < batch.length; rest++)
183
217
  this.#native(batch[rest]);
184
218
  return;
@@ -189,3 +223,16 @@ export class Coordinator {
189
223
  }
190
224
  }
191
225
  }
226
+ function overlapsRuns(runs, address) {
227
+ let low = 0, high = runs.length / 2 - 1;
228
+ while (low <= high) {
229
+ const mid = (low + high) >> 1;
230
+ if (runs[mid * 2] > address)
231
+ high = mid - 1;
232
+ else if (runs[mid * 2] + runs[mid * 2 + 1] <= address)
233
+ low = mid + 1;
234
+ else
235
+ return true;
236
+ }
237
+ return false;
238
+ }
@@ -1,3 +1,4 @@
1
+ import binaryen from 'binaryen';
1
2
  /** Region admission. Both values are estimates in instruction units, not guarantees. */
2
3
  export interface AdmissionOptions {
3
4
  /**
@@ -10,7 +11,6 @@ export interface AdmissionOptions {
10
11
  }
11
12
  /** Calibrated on Apple M2 Pro; see `results/execution/admission/admission-calibration.summary.json`. */
12
13
  export declare const DEFAULT_MINIMUM_REGION_WORK = 200000;
13
- export declare const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
14
14
  export interface ControlPlan {
15
15
  coordinator: Uint8Array;
16
16
  workerOriginal: Uint8Array;
@@ -30,6 +30,8 @@ export interface ControlPlan {
30
30
  }[];
31
31
  diagnostics: string[];
32
32
  }
33
+ export type Info = ReturnType<typeof binaryen.getExpressionInfo> & Record<string, any>;
34
+ export declare function info(expression: number): Info;
33
35
  export interface Work {
34
36
  compute: number;
35
37
  accesses: number;
@@ -38,18 +40,6 @@ export interface Work {
38
40
  export interface Term extends Work {
39
41
  params: number[];
40
42
  }
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
43
  export declare function estimateWork(body: number, callee: (name: string) => Work | undefined, assumedTrips: number): Work;
54
44
  export declare const netWork: (work: Work) => number;
55
45
  /** Resolves defaults and rejects values the estimate cannot use. */
@@ -84,15 +74,32 @@ export interface StackRoute {
84
74
  };
85
75
  /** Immutable globals with a constant initializer that the set reads. */
86
76
  constants: string[];
77
+ /** Delta globals of an ownership redirect that the set reads; the worker module exports them. */
78
+ redirect?: string[];
87
79
  /** The worker set: closed under calls, in module order. */
88
80
  functions: string[];
89
81
  /** The members that sit on a call cycle. */
90
82
  recursive: string[];
83
+ /** Tables a member calls through; every worker holds its own copy, built from the segments. */
84
+ tables: string[];
91
85
  /** Static work per member; a recursive member counts one level of its own calls. */
92
86
  work: Record<string, Work>;
93
87
  /** Why the module is or is not eligible. */
94
88
  diagnostics: string[];
95
89
  }
90
+ /** Name prefix of the mutable delta globals an ownership redirect adds; the stack route sets them aside. */
91
+ export declare const redirectDelta = "__folio_od";
92
+ /** What an ownership redirect hands the iteration executor: windows with their delta globals and the copy-out. */
93
+ export interface OwnershipPlan {
94
+ /** each window `[low, end)` and the exported mutable global that holds `copy - low` */
95
+ windows: {
96
+ low: number;
97
+ end: number;
98
+ delta: string;
99
+ }[];
100
+ /** byte ranges the last record's copy supplies */
101
+ copyOut: [number, number][];
102
+ }
96
103
  /** Computes the stack route of a module. A failure is reported in `diagnostics`, never thrown. */
97
104
  export declare function stackRoute(original: Uint8Array, options?: AdmissionOptions): StackRoute;
98
105
  /** One local of the owner that the schedule or the outlined body needs. */
@@ -156,6 +163,8 @@ export interface IterationRoute {
156
163
  iterate?: string;
157
164
  stackExport?: string;
158
165
  module?: Uint8Array;
166
+ /** set when `module` carries an ownership redirect: the windows each slot keeps a private copy of */
167
+ ownership?: OwnershipPlan;
159
168
  diagnostics: string[];
160
169
  }
161
170
  /**