@gmitch215/folio 1.0.1 → 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 (65) hide show
  1. package/README.md +398 -28
  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/boundaries.d.ts +59 -0
  7. package/dist/boundaries.js +127 -0
  8. package/dist/certified.d.ts +66 -0
  9. package/dist/certified.js +192 -0
  10. package/dist/certify.d.ts +98 -0
  11. package/dist/certify.js +2628 -0
  12. package/dist/context.d.ts +16 -2
  13. package/dist/context.js +60 -14
  14. package/dist/coordinator.js +50 -3
  15. package/dist/extract.d.ts +19 -0
  16. package/dist/extract.js +133 -5
  17. package/dist/fold.d.ts +32 -0
  18. package/dist/fold.js +105 -0
  19. package/dist/frames.d.ts +5 -1
  20. package/dist/frames.js +156 -9
  21. package/dist/inline.d.ts +114 -0
  22. package/dist/inline.js +276 -13
  23. package/dist/iteration-admission.d.ts +116 -7
  24. package/dist/iteration-admission.js +137 -8
  25. package/dist/iteration-layout.d.ts +60 -0
  26. package/dist/iteration-layout.js +54 -3
  27. package/dist/iteration-owner.d.ts +14 -1
  28. package/dist/iteration-owner.js +2 -2
  29. package/dist/iteration-worker.js +124 -58
  30. package/dist/iteration.d.ts +179 -13
  31. package/dist/iteration.js +845 -70
  32. package/dist/lease.d.ts +45 -0
  33. package/dist/lease.js +274 -0
  34. package/dist/managed.d.ts +72 -0
  35. package/dist/managed.js +425 -27
  36. package/dist/memo.d.ts +99 -0
  37. package/dist/memo.js +250 -0
  38. package/dist/node.d.ts +43 -1
  39. package/dist/node.js +87 -11
  40. package/dist/ownership-redirect.d.ts +30 -0
  41. package/dist/ownership-redirect.js +179 -0
  42. package/dist/ownership-slices.d.ts +44 -0
  43. package/dist/ownership-slices.js +72 -0
  44. package/dist/ownership.d.ts +161 -0
  45. package/dist/ownership.js +6568 -0
  46. package/dist/ranges.d.ts +78 -0
  47. package/dist/ranges.js +263 -0
  48. package/dist/read-scan.d.ts +18 -0
  49. package/dist/read-scan.js +94 -0
  50. package/dist/read-windows.d.ts +103 -0
  51. package/dist/read-windows.js +244 -0
  52. package/dist/router-worker.d.ts +1 -0
  53. package/dist/router-worker.js +4 -0
  54. package/dist/router.d.ts +203 -0
  55. package/dist/router.js +667 -0
  56. package/dist/runs.d.ts +44 -0
  57. package/dist/runs.js +182 -0
  58. package/dist/slices-worker.d.ts +1 -0
  59. package/dist/slices-worker.js +38 -0
  60. package/dist/slices.d.ts +126 -0
  61. package/dist/slices.js +441 -0
  62. package/dist/tasks.d.ts +14 -4
  63. package/dist/tasks.js +12 -11
  64. package/dist/transaction.d.ts +10 -0
  65. package/package.json +40 -4
package/dist/memo.js ADDED
@@ -0,0 +1,250 @@
1
+ import { FootprintCache, RangeSet } from "./ranges.js";
2
+ import { writeRunsOf } from "./runs.js";
3
+ async function digest(memory, spans) {
4
+ let total = 0;
5
+ for (let i = 1; i < spans.length; i += 2)
6
+ total += spans[i];
7
+ const buffer = new Uint8Array(total);
8
+ let offset = 0;
9
+ for (let i = 0; i < spans.length; i += 2) {
10
+ buffer.set(memory.subarray(spans[i], spans[i] + spans[i + 1]), offset);
11
+ offset += spans[i + 1];
12
+ }
13
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', buffer));
14
+ return {
15
+ digest: Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join(''),
16
+ bytes: total
17
+ };
18
+ }
19
+ function spanArray(reads) {
20
+ return Uint32Array.from(RangeSet.fromAddresses(reads).spans().flat());
21
+ }
22
+ // a run-encoded result (`reads` empty, `readRuns`) is expanded so the record holds one shape
23
+ function addressForm(result) {
24
+ if (!result.readRuns && !result.writeRuns)
25
+ return result;
26
+ const reads = [...result.reads];
27
+ for (let i = 0; i < (result.readRuns?.length ?? 0); i += 2)
28
+ for (let k = 0; k < result.readRuns[i + 1]; k++)
29
+ reads.push(result.readRuns[i] + k);
30
+ const writes = [...result.writes];
31
+ let at = 0;
32
+ for (let i = 0; i < (result.writeRuns?.length ?? 0); i += 2)
33
+ for (let k = 0; k < result.writeRuns[i + 1]; k++)
34
+ writes.push([result.writeRuns[i] + k, result.writeData[at++]]);
35
+ return {
36
+ ...result,
37
+ reads,
38
+ writes,
39
+ readRuns: undefined,
40
+ writeRuns: undefined,
41
+ writeData: undefined
42
+ };
43
+ }
44
+ export class RegionMemo {
45
+ #budget;
46
+ #perKey;
47
+ #byKey = new Map();
48
+ // every entry, least recently used first
49
+ #lru = new Set();
50
+ #stats = emptyStats();
51
+ constructor(options = {}) {
52
+ this.#budget = options.bytes ?? 8 * 1048576;
53
+ this.#perKey = options.entries ?? 4;
54
+ if (!Number.isSafeInteger(this.#budget) || this.#budget < 1)
55
+ throw new RangeError('invalid memo byte budget');
56
+ if (!Number.isSafeInteger(this.#perKey) || this.#perKey < 1)
57
+ throw new RangeError('invalid memo entry limit');
58
+ }
59
+ /**
60
+ * The key for a call in a module, or undefined when an argument is not an exact integer. The
61
+ * module string is the host's identity for the tracked module; see the contract above.
62
+ */
63
+ static keyOf(module, name, args) {
64
+ for (const value of args) {
65
+ if (typeof value === 'bigint')
66
+ continue;
67
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || Object.is(value, -0))
68
+ return undefined;
69
+ }
70
+ return JSON.stringify([module, FootprintCache.key(name, args)]);
71
+ }
72
+ get stats() {
73
+ return { ...this.#stats };
74
+ }
75
+ /**
76
+ * Returns the recorded result whose read bytes equal the current bytes, or undefined. With
77
+ * `runs`, the write set comes as `writeRuns` and `writeData`, which the owner commits as
78
+ * intervals; otherwise as `[address, value]` tuples.
79
+ */
80
+ async lookup(key, memory, options = {}) {
81
+ this.#stats.lookups++;
82
+ const list = this.#byKey.get(key);
83
+ if (list)
84
+ for (const entry of [...list].reverse()) {
85
+ if (entry.memoryBytes !== memory.byteLength)
86
+ continue;
87
+ const now = await digest(memory, entry.spans);
88
+ this.#stats.hashedBytes += now.bytes;
89
+ // an entry removed while the digest ran must not be touched back into the LRU
90
+ if (!this.#lru.has(entry) || now.digest !== entry.digest)
91
+ continue;
92
+ this.#touch(entry);
93
+ this.#stats.hits++;
94
+ this.#stats.savedMs += entry.ms;
95
+ if (options.runs)
96
+ return {
97
+ result: {
98
+ value: entry.value,
99
+ reads: entry.reads.slice(),
100
+ writes: [],
101
+ writeRuns: entry.runs.slice(),
102
+ writeData: entry.runData.slice()
103
+ },
104
+ ms: entry.ms
105
+ };
106
+ entry.writes ??= Array.from(entry.writeAddresses, (address, i) => Object.freeze([address, entry.writeValues[i]]));
107
+ return {
108
+ result: {
109
+ value: entry.value,
110
+ reads: entry.reads.slice(),
111
+ // the tuples are frozen, so the copy cannot change the entry
112
+ writes: entry.writes.slice()
113
+ },
114
+ ms: entry.ms
115
+ };
116
+ }
117
+ this.#stats.misses++;
118
+ return undefined;
119
+ }
120
+ /**
121
+ * Records a clean result of an execution that started from `memory`. Returns false when the
122
+ * result is refused or already held. Throws on a read or write that the memory cannot hold.
123
+ *
124
+ * The cost estimate counts 8 bytes per read address and 40 per write (a two-element array and
125
+ * its slot), plus the hashed span table and the 32-byte digest.
126
+ */
127
+ async record(key, memory, result, ms = 0) {
128
+ result = addressForm(result);
129
+ if (result.trap !== undefined ||
130
+ result.exhausted ||
131
+ result.inconclusive ||
132
+ result.escapes?.length ||
133
+ !Number.isFinite(ms) ||
134
+ ms < 0)
135
+ return false;
136
+ for (const address of result.reads)
137
+ if (!Number.isSafeInteger(address) || address < 0 || address >= memory.byteLength)
138
+ throw new RangeError('memo read outside memory');
139
+ for (const [address, value] of result.writes)
140
+ if (!Number.isSafeInteger(address) ||
141
+ address < 0 ||
142
+ address >= memory.byteLength ||
143
+ !Number.isInteger(value) ||
144
+ value < 0 ||
145
+ value > 255)
146
+ throw new RangeError('memo write outside memory or not a byte');
147
+ const spans = spanArray(result.reads);
148
+ const seen = await digest(memory, spans);
149
+ const memoryBytes = memory.byteLength;
150
+ const list = this.#byKey.get(key) ?? [];
151
+ if (list.some((entry) => entry.memoryBytes === memoryBytes && entry.digest === seen.digest))
152
+ return false;
153
+ const reads = [...result.reads];
154
+ const writeAddresses = Uint32Array.from(result.writes, ([address]) => address);
155
+ const writeValues = Uint8Array.from(result.writes, ([, value]) => value);
156
+ const packed = writeRunsOf(result.writes);
157
+ const cost = spans.byteLength +
158
+ reads.length * 8 +
159
+ writeAddresses.length * 40 +
160
+ packed.runs.byteLength +
161
+ packed.data.byteLength +
162
+ 32;
163
+ if (cost > this.#budget)
164
+ return false;
165
+ const entry = {
166
+ key,
167
+ memoryBytes,
168
+ spans,
169
+ readBytes: seen.bytes,
170
+ digest: seen.digest,
171
+ reads,
172
+ writeAddresses,
173
+ writeValues,
174
+ runs: packed.runs,
175
+ runData: packed.data,
176
+ value: result.value,
177
+ ms,
178
+ cost
179
+ };
180
+ list.push(entry);
181
+ this.#byKey.set(key, list);
182
+ this.#lru.add(entry);
183
+ this.#stats.recorded++;
184
+ this.#stats.recordedBytes += cost;
185
+ this.#stats.storedBytes += cost;
186
+ while (list.length > this.#perKey)
187
+ this.#evict(list[0]);
188
+ while (this.#stats.storedBytes > this.#budget)
189
+ this.#evict(this.#lru.values().next().value);
190
+ return true;
191
+ }
192
+ /** Drops every entry and resets the counters. */
193
+ clear() {
194
+ this.#byKey.clear();
195
+ this.#lru.clear();
196
+ this.#stats = emptyStats();
197
+ }
198
+ /** Counts how often (key, read bytes) pairs repeat. Nothing is recorded. */
199
+ static async probe(observations) {
200
+ const counts = new Map();
201
+ let observed = 0;
202
+ for (const { key, memory, reads } of observations) {
203
+ const spans = spanArray(reads);
204
+ const seen = await digest(memory, spans);
205
+ const id = `${key}|${memory.byteLength}|${Array.from(spans).join(',')}|${seen.digest}`;
206
+ counts.set(id, (counts.get(id) ?? 0) + 1);
207
+ observed++;
208
+ }
209
+ let repeats = 0;
210
+ for (const count of counts.values())
211
+ repeats += count - 1;
212
+ return {
213
+ observations: observed,
214
+ distinct: counts.size,
215
+ repeats,
216
+ repeatRate: observed ? repeats / observed : 0
217
+ };
218
+ }
219
+ #touch(entry) {
220
+ this.#lru.delete(entry);
221
+ this.#lru.add(entry);
222
+ const list = this.#byKey.get(entry.key);
223
+ list.splice(list.indexOf(entry), 1);
224
+ list.push(entry);
225
+ }
226
+ #evict(entry) {
227
+ this.#lru.delete(entry);
228
+ const list = this.#byKey.get(entry.key);
229
+ if (list) {
230
+ list.splice(list.indexOf(entry), 1);
231
+ if (!list.length)
232
+ this.#byKey.delete(entry.key);
233
+ }
234
+ this.#stats.storedBytes -= entry.cost;
235
+ this.#stats.evictions++;
236
+ }
237
+ }
238
+ function emptyStats() {
239
+ return {
240
+ lookups: 0,
241
+ hits: 0,
242
+ misses: 0,
243
+ hashedBytes: 0,
244
+ recordedBytes: 0,
245
+ storedBytes: 0,
246
+ recorded: 0,
247
+ evictions: 0,
248
+ savedMs: 0
249
+ };
250
+ }
package/dist/node.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { PreparedProgram } from './compiler.ts';
2
2
  import type { IterationReason } from './iteration-owner.ts';
3
- import type { IterationReport } from './iteration.ts';
3
+ import type { IterationReport, IterationStallOptions } from './iteration.ts';
4
4
  /** Wraps an asynchronous host import for Wasm stack suspension. */
5
5
  export declare function suspending<Args extends unknown[], Value>(fn: (...args: Args) => Promise<Value>): WebAssembly.ImportValue;
6
6
  /** Source bytes, a compiled module, or a plan from `prepare`. A compiled module keeps its native path. */
@@ -97,6 +97,48 @@ export interface FolioOptions {
97
97
  * @since 1.0.1
98
98
  */
99
99
  adaptiveRouting?: boolean;
100
+ /**
101
+ * Undo entries per iteration the iteration route may grow its logs to when a batch exhausts the
102
+ * default capacity, retrying that batch once. Off unless set: on the padded LZ4 consumer the
103
+ * retry costs more than the dispatch gains, because the ordered validator is quadratic in the
104
+ * logged entries.
105
+ * @since 1.1.0
106
+ */
107
+ iterationLogCeiling?: number;
108
+ /**
109
+ * Learn read windows from the first batch of an iteration loop that completes without a
110
+ * conflict, so loads of the input the iterations stream through set no per-access mark. The next
111
+ * batch counts the loads on the windows, and they stay armed only if they pay. Off by
112
+ * default. A window can only cost a false conflict, never a different result.
113
+ * @since 1.1.0
114
+ */
115
+ iterationReadWindows?: boolean;
116
+ /**
117
+ * Keep a summary of which 64-word blocks of each read bitmap a read touched, so the workers scan
118
+ * those blocks and not the whole bitmap after every iteration. The conflicts found do not change.
119
+ * Costs a few executed instructions on every tracked read. Off by default.
120
+ * @since 1.1.0
121
+ */
122
+ iterationReadSummary?: boolean;
123
+ /**
124
+ * Stop an iteration batch that does not return. The worker module polls a stop word at every
125
+ * loop start, which costs a few percent of worker time on tight loops, so it is off by
126
+ * default. When a batch has run past its limit the
127
+ * workers trap, the batch rolls back from the undo logs and the loop finishes serially with
128
+ * `iteration.stopped` set to `stalled`. Needed for programs whose iterations can read state
129
+ * another iteration is changing and then loop on it, such as a linked structure that two
130
+ * iterations rewrite.
131
+ * @since 1.1.0
132
+ */
133
+ iterationStall?: boolean | IterationStallOptions;
134
+ /**
135
+ * Judge an iteration loop that is a little under the dispatch floor on one timed batch, and let
136
+ * the batches a running loop has shown decide whether what is left pays, instead of the floor
137
+ * alone. A probe that loses ends the dispatch and the loop runs serially for the next 16 calls.
138
+ * The result is the same either way; only the choice of route changes. Off by default.
139
+ * @since 1.1.0
140
+ */
141
+ iterationSecondChance?: boolean;
100
142
  }
101
143
  /** A same-process isolate group; callers give it exclusive memory access during each run. */
102
144
  export declare class Folio {
package/dist/node.js CHANGED
@@ -2,8 +2,8 @@ import { availableParallelism } from 'node:os';
2
2
  import { isArrayBuffer, isSharedArrayBuffer, isUint8Array } from 'node:util/types';
3
3
  import { Worker } from 'node:worker_threads';
4
4
  import { Coordinator } from "./coordinator.js";
5
- import { decideAdmission, decideBatch, decideCollapse } from "./iteration-admission.js";
6
- import { iterationArguments, iterationFit } from "./iteration-layout.js";
5
+ import { decideAdmission, decideBatch, decideBound, decideCollapse, decideProof, decideRemaining } from "./iteration-admission.js";
6
+ import { iterationArguments, iterationFit, iterationWindowBytes } from "./iteration-layout.js";
7
7
  import { memoryImports } from "./memory.js";
8
8
  import { numberBits, restoreNumbers } from "./values.js";
9
9
  /** Wraps an asynchronous host import for Wasm stack suspension. */
@@ -32,16 +32,38 @@ function isMemory(value) {
32
32
  }
33
33
  }
34
34
  const PAGE = 65536;
35
+ /** Calls that skip dispatch after a stop that one call recorded, before one tries again. */
36
+ const iterationReprobe = 16;
35
37
  function addCounts(total, part) {
36
38
  if (!total)
37
39
  return structuredClone(part);
38
40
  for (const key of Object.keys(part)) {
39
41
  if (key === 'stopped')
40
42
  total.stopped ??= part.stopped;
43
+ else if (key === 'windowRefused')
44
+ total.windowRefused ??= part.windowRefused;
45
+ else if (key === 'readWindowRefused')
46
+ total.readWindowRefused ??= part.readWindowRefused;
47
+ else if (key === 'readWindowGate')
48
+ total.readWindowGate ??= part.readWindowGate;
49
+ else if (key === 'readWindows') {
50
+ if (part.readWindows && total.readWindows)
51
+ total.readWindows.batches += part.readWindows.batches;
52
+ else
53
+ total.readWindows ??= part.readWindows;
54
+ }
55
+ else if (key === 'window') {
56
+ if (part.window && total.window)
57
+ total.window.batches += part.window.batches;
58
+ else
59
+ total.window ??= part.window;
60
+ }
41
61
  else if (key === 'admission')
42
62
  total.admission = part.admission ?? total.admission;
43
63
  else if (key === 'workers')
44
64
  total.workers = Math.max(total.workers, part.workers);
65
+ else if (key === 'maxLogEntries')
66
+ total.maxLogEntries = Math.max(total.maxLogEntries, part.maxLogEntries);
45
67
  else if (key === 'conflicts') {
46
68
  total.conflicts.raw += part.conflicts.raw;
47
69
  total.conflicts.war += part.conflicts.war;
@@ -89,7 +111,11 @@ async function selectIteration(program, options, size) {
89
111
  if (options.memory && !isSharedArrayBuffer(options.memory.buffer))
90
112
  return refuse('no-arena', 'the host memory is not shared');
91
113
  const start = options.memory ? options.memory.buffer.byteLength : owner.memory.initial * PAGE;
92
- const fit = iterationFit(start, { frameBytes: route.frame?.size });
114
+ const fit = iterationFit(start, {
115
+ frameBytes: route.frame?.size,
116
+ windowBytes: iterationWindowBytes,
117
+ readSummary: Boolean(options.iterationReadSummary)
118
+ });
93
119
  if (!fit)
94
120
  return refuse('no-arena', 'the arena does not fit in 65536 pages');
95
121
  if (owner.memory.maximum !== undefined && fit.pages > owner.memory.maximum)
@@ -110,7 +136,7 @@ async function selectIteration(program, options, size) {
110
136
  throw error;
111
137
  return refuse('no-arena', `memory cannot hold an arena of ${fit.bytes} bytes`);
112
138
  }
113
- return { route, owner, memory, arenaBase: fit.base, size };
139
+ return { route, verdicts: new Map(), owner, memory, arenaBase: fit.base, size };
114
140
  }
115
141
  function throwTrap(result) {
116
142
  if (!result.trap)
@@ -208,6 +234,11 @@ export class Folio {
208
234
  #minimumWork;
209
235
  #profile;
210
236
  #adaptive;
237
+ #logCeiling;
238
+ #readWindows;
239
+ #readSummary;
240
+ #stall;
241
+ #secondChance;
211
242
  #routing = new Map();
212
243
  #nextId = 0;
213
244
  #busy = false;
@@ -228,6 +259,11 @@ export class Folio {
228
259
  this.#minimumWork = options.minimumParallelWork ?? 100_000;
229
260
  this.#profile = options.profile ?? false;
230
261
  this.#adaptive = options.adaptiveRouting ?? false;
262
+ this.#logCeiling = options.iterationLogCeiling;
263
+ this.#readWindows = Boolean(options.iterationReadWindows);
264
+ this.#readSummary = Boolean(options.iterationReadSummary);
265
+ this.#stall = options.iterationStall;
266
+ this.#secondChance = Boolean(options.iterationSecondChance);
231
267
  if (!Number.isInteger(this.#fuel) || this.#fuel < 2 || this.#fuel > 2_147_483_647)
232
268
  throw new RangeError('invalid fuel');
233
269
  if (!Number.isInteger(this.#maxBytes) || this.#maxBytes < 1)
@@ -355,7 +391,15 @@ export class Folio {
355
391
  if (!runtime.promising)
356
392
  throw new Error('this runtime does not support JSPI');
357
393
  }
358
- this.#instance = new WebAssembly.Instance(executable, imports);
394
+ try {
395
+ this.#instance = new WebAssembly.Instance(executable, imports);
396
+ }
397
+ catch (error) {
398
+ if (error instanceof WebAssembly.LinkError &&
399
+ /shared state of memory/.test(error.message))
400
+ throw new TypeError('the host memory and the program memory import differ in shared state; pass a shared memory only for a program the route can run on one');
401
+ throw error;
402
+ }
359
403
  if (this.#control) {
360
404
  this.#exports = Object.create(null);
361
405
  for (const item of WebAssembly.Module.exports(native)) {
@@ -675,7 +719,12 @@ export class Folio {
675
719
  const { IterationPool } = await import("./iteration.js");
676
720
  it.pool = await IterationPool.open(it.route, it.memory, {
677
721
  arenaBase: it.arenaBase,
678
- width
722
+ windowBytes: iterationWindowBytes,
723
+ width,
724
+ ...(this.#logCeiling === undefined ? {} : { logCeiling: this.#logCeiling }),
725
+ ...(this.#readWindows ? { readWindows: true } : {}),
726
+ ...(this.#readSummary ? { readSummary: true } : {}),
727
+ ...(this.#stall ? { stall: this.#stall } : {})
679
728
  });
680
729
  }
681
730
  catch (error) {
@@ -766,6 +815,7 @@ export class Folio {
766
815
  };
767
816
  const route = it.route;
768
817
  const pool = run.pool;
818
+ const secondChance = this.#secondChance;
769
819
  const entry = {};
770
820
  it.owner.locals.forEach((local, index) => (entry[local] = values[index]));
771
821
  const trip = Number(entry[route.trip.local]) >>> 0;
@@ -773,8 +823,15 @@ export class Folio {
773
823
  return decline('trip-zero');
774
824
  if (trip < 2)
775
825
  return decline('no-admission');
776
- if (it.memory.buffer.byteLength !== pool.arena.memoryBytes)
826
+ if (it.memory.buffer.byteLength !== pool.memoryBytes)
777
827
  return decline('no-arena');
828
+ const key = `${route.owner}|${pool.width}|${this.#logCeiling ?? ''}`;
829
+ const known = it.verdicts.get(key);
830
+ if (known?.stop) {
831
+ if (known.skipped++ < iterationReprobe)
832
+ return decline(known.stop);
833
+ it.verdicts.delete(key);
834
+ }
778
835
  const frameBase = route.frame ? Number(entry[route.frame.local]) >>> 0 : 0;
779
836
  const plain = (it.plain ??= this.#plain(it));
780
837
  const replay = (k) => {
@@ -788,16 +845,35 @@ export class Folio {
788
845
  frameBase,
789
846
  entry,
790
847
  replay,
791
- admit: (ms) => decideAdmission(ms, trip, pool.width),
848
+ window: known?.window,
849
+ admit: (ms) => decideAdmission(ms, trip, pool.width, secondChance),
792
850
  loses: decideBatch,
793
- collapses: decideCollapse
851
+ collapses: decideCollapse,
852
+ hopeless: decideBound,
853
+ unproven: decideProof,
854
+ reconsider: (ms, remaining, last) => decideRemaining(ms, remaining, pool.width, secondChance ? last : undefined)
794
855
  });
795
856
  }
796
857
  finally {
797
858
  run.iteration = addCounts(run.iteration, pool.report);
798
859
  }
799
- if (pool.report.stopped)
800
- run.reason ??= pool.report.stopped;
860
+ const stopped = pool.report.stopped;
861
+ if (stopped)
862
+ run.reason ??= stopped;
863
+ const structural = stopped === 'dependency' ||
864
+ stopped === 'log-exhausted' ||
865
+ stopped === 'frame-carried dependence' ||
866
+ stopped === 'stalled';
867
+ const w = pool.report.window;
868
+ const learned = w?.source === 'discovered' && !w.batches;
869
+ if (structural && !learned)
870
+ it.verdicts.set(key, { stop: stopped, skipped: 0 });
871
+ else if (pool.report.admission?.probeLost)
872
+ it.verdicts.set(key, { stop: 'no-admission', skipped: 0 });
873
+ else if (w && (w.batches || learned))
874
+ it.verdicts.set(key, { window: { low: w.low, end: w.end }, skipped: 0 });
875
+ else if (known)
876
+ it.verdicts.delete(key);
801
877
  return 1;
802
878
  }
803
879
  // a plain instance of the worker module on the shared memory; replay runs iterations on it
@@ -0,0 +1,30 @@
1
+ import { type IterationRoute, type OwnershipPlan } from './extract.ts';
2
+ import { type OwnershipCertificate } from './ownership.ts';
3
+ export type RedirectErrorCode = 'unbound' | 'stale' | 'invalid' | 'unsupported';
4
+ export declare class OwnershipRedirectError extends Error {
5
+ readonly code: RedirectErrorCode;
6
+ constructor(code: RedirectErrorCode, detail: string);
7
+ }
8
+ export interface RedirectStats {
9
+ redirected: number;
10
+ skipped: number;
11
+ bulk: number;
12
+ straddle: number;
13
+ functions: number;
14
+ }
15
+ export interface OwnershipRedirect {
16
+ module: Uint8Array;
17
+ plan: OwnershipPlan;
18
+ stats: RedirectStats;
19
+ }
20
+ /**
21
+ * Rewrites the closure of a certified module so each window access adds a per-worker delta. The
22
+ * delta globals start at 0, so the module still runs in place. Throws `OwnershipRedirectError`
23
+ * when the certificate does not bind to the bytes or the module cannot be rewritten.
24
+ */
25
+ export declare function redirectOwnership(bytes: Uint8Array, certificate: OwnershipCertificate): OwnershipRedirect;
26
+ /** The iteration route of the redirected module, with the plan the executor needs. */
27
+ export declare function ownershipRoute(bytes: Uint8Array, certificate: OwnershipCertificate): {
28
+ route: IterationRoute;
29
+ redirect: OwnershipRedirect;
30
+ };