@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/memory.js CHANGED
@@ -1,89 +1,5 @@
1
- /** Reads imported memory limits without changing the module or compiling its functions. */
2
- export function memoryImports(bytes) {
3
- let offset = 8;
4
- const byte = () => {
5
- if (offset >= bytes.length)
6
- throw new RangeError('truncated wasm metadata');
7
- return bytes[offset++];
8
- };
9
- const unsigned = () => {
10
- let value = 0n, shift = 0n;
11
- for (let i = 0; i < 10; i++) {
12
- const part = byte();
13
- value |= BigInt(part & 127) << shift;
14
- if (!(part & 128)) {
15
- if (value > BigInt(Number.MAX_SAFE_INTEGER))
16
- throw new RangeError('memory limit exceeds JS integer precision');
17
- return Number(value);
18
- }
19
- shift += 7n;
20
- }
21
- throw new RangeError('invalid wasm integer');
22
- };
23
- const name = () => {
24
- const length = unsigned();
25
- const end = offset + length;
26
- if (end > bytes.length)
27
- throw new RangeError('truncated wasm name');
28
- const value = new TextDecoder().decode(bytes.subarray(offset, end));
29
- offset = end;
30
- return value;
31
- };
32
- const reference = () => {
33
- const type = byte();
34
- if (type === 0x63 || type === 0x64) {
35
- while (byte() & 128) { }
36
- }
37
- };
38
- while (offset < bytes.length) {
39
- const section = byte();
40
- const length = unsigned();
41
- const end = offset + length;
42
- if (end > bytes.length)
43
- throw new RangeError('truncated wasm section');
44
- if (section !== 2) {
45
- offset = end;
46
- continue;
47
- }
48
- const count = unsigned();
49
- const memories = [];
50
- for (let i = 0; i < count; i++) {
51
- const module = name(), base = name(), kind = byte();
52
- if (kind === 0)
53
- unsigned();
54
- else if (kind === 1) {
55
- reference();
56
- const flags = unsigned();
57
- unsigned();
58
- if (flags & 1)
59
- unsigned();
60
- }
61
- else if (kind === 2) {
62
- const flags = unsigned();
63
- if (flags & ~7)
64
- throw new TypeError('unsupported memory-limit metadata');
65
- const initial = unsigned(), maximum = flags & 1 ? unsigned() : undefined;
66
- memories.push({
67
- module,
68
- name: base,
69
- initial,
70
- maximum,
71
- shared: Boolean(flags & 2),
72
- memory64: Boolean(flags & 4)
73
- });
74
- }
75
- else if (kind === 3) {
76
- reference();
77
- byte();
78
- }
79
- else if (kind === 4) {
80
- byte();
81
- unsigned();
82
- }
83
- else
84
- throw new TypeError('unsupported wasm import metadata');
85
- }
86
- return memories;
87
- }
88
- return [];
89
- }
1
+ export * from "./memory/elastic-peer.js";
2
+ export * from "./memory/elastic-sql.js";
3
+ export * from "./memory/elastic.js";
4
+ export * from "./memory/growth-governor.js";
5
+ export * from "./memory/pages.js";
@@ -1,4 +1,4 @@
1
- import type { PreparedContext } from './compiler.ts';
1
+ import type { PreparedContext } from '../execution/compiler.ts';
2
2
  /** A changed memory or table size requires a newly instantiated context. */
3
3
  export declare class ContextResetError extends Error {
4
4
  /** Which binding changed size. */
@@ -17,6 +17,15 @@ export interface ContextResetReport {
17
17
  globals: number;
18
18
  /** Table slots whose reference was restored. */
19
19
  tableSlots: number;
20
+ /** Bytes inside `overwrite` ranges, neither compared nor restored. */
21
+ skippedBytes: number;
22
+ }
23
+ /** Bytes of one context memory that the caller writes completely before anything reads them. */
24
+ export interface ContextRange {
25
+ /** Index into the plan's memories. The default is 0. */
26
+ memory?: number;
27
+ offset: number;
28
+ length: number;
20
29
  }
21
30
  /**
22
31
  * Captures private Wasm state after initialization. `prepareContext` exposes hidden bindings.
@@ -28,6 +37,11 @@ export interface ContextResetReport {
28
37
  export declare class InstanceCheckpoint {
29
38
  #private;
30
39
  constructor(instance: WebAssembly.Instance, plan: PreparedContext);
31
- /** Restores all mutable bindings. `full` skips page comparison and copies every memory byte. */
32
- restore(strategy?: 'changed' | 'full'): ContextResetReport;
40
+ /**
41
+ * Restores all mutable bindings. `full` skips page comparison and copies every memory byte.
42
+ * Bytes inside `overwrite` are left as they are: the caller must write every one of them
43
+ * before the program reads it, so a task that rewrites its input region each time does not pay
44
+ * to compare and copy back the previous task's input.
45
+ */
46
+ restore(strategy?: 'changed' | 'full', overwrite?: ContextRange[]): ContextResetReport;
33
47
  }
@@ -45,8 +45,13 @@ export class InstanceCheckpoint {
45
45
  };
46
46
  });
47
47
  }
48
- /** Restores all mutable bindings. `full` skips page comparison and copies every memory byte. */
49
- restore(strategy = 'changed') {
48
+ /**
49
+ * Restores all mutable bindings. `full` skips page comparison and copies every memory byte.
50
+ * Bytes inside `overwrite` are left as they are: the caller must write every one of them
51
+ * before the program reads it, so a task that rewrites its input region each time does not pay
52
+ * to compare and copy back the previous task's input.
53
+ */
54
+ restore(strategy = 'changed', overwrite = []) {
50
55
  if (strategy !== 'changed' && strategy !== 'full')
51
56
  throw new TypeError('invalid context reset strategy');
52
57
  for (const { memory, bytes } of this.#memories)
@@ -55,27 +60,38 @@ export class InstanceCheckpoint {
55
60
  for (const { table, slots } of this.#tables)
56
61
  if (table.length !== slots.length)
57
62
  throw new ContextResetError('table-size');
63
+ const skipped = this.#ranges(overwrite);
58
64
  const report = {
59
65
  checkedBytes: 0,
60
66
  copiedBytes: 0,
61
67
  changedPages: 0,
62
68
  globals: 0,
63
- tableSlots: 0
69
+ tableSlots: 0,
70
+ skippedBytes: 0
64
71
  };
65
- for (const { memory, bytes } of this.#memories) {
72
+ this.#memories.forEach(({ memory, bytes }, index) => {
66
73
  const target = new Uint8Array(memory.buffer);
67
- for (let offset = 0; offset < bytes.length; offset += 65536) {
68
- const source = bytes.subarray(offset, offset + 65536), current = target.subarray(offset, offset + 65536);
69
- if (strategy === 'changed')
70
- report.checkedBytes += current.length;
71
- if (strategy === 'full' ||
72
- !Buffer.from(current.buffer, current.byteOffset, current.length).equals(Buffer.from(source.buffer, source.byteOffset, source.length))) {
73
- current.set(source);
74
- report.copiedBytes += current.length;
75
- report.changedPages++;
74
+ let from = 0;
75
+ for (const [start, end] of [
76
+ ...skipped[index],
77
+ [bytes.length, bytes.length]
78
+ ]) {
79
+ for (let offset = from; offset < start; offset += 65536) {
80
+ const stop = Math.min(offset + 65536, start);
81
+ const source = bytes.subarray(offset, stop), current = target.subarray(offset, stop);
82
+ if (strategy === 'changed')
83
+ report.checkedBytes += current.length;
84
+ if (strategy === 'full' ||
85
+ !Buffer.from(current.buffer, current.byteOffset, current.length).equals(Buffer.from(source.buffer, source.byteOffset, source.length))) {
86
+ current.set(source);
87
+ report.copiedBytes += current.length;
88
+ report.changedPages++;
89
+ }
76
90
  }
91
+ report.skippedBytes += end - start;
92
+ from = end;
77
93
  }
78
- }
94
+ });
79
95
  for (const { global, value } of this.#globals) {
80
96
  if (!Object.is(global.value, value)) {
81
97
  global.value = value;
@@ -90,4 +106,34 @@ export class InstanceCheckpoint {
90
106
  }
91
107
  return report;
92
108
  }
109
+ /** Validates ranges and returns, per memory, sorted and merged [start, end) pairs. */
110
+ #ranges(overwrite) {
111
+ const merged = this.#memories.map(() => []);
112
+ for (const { memory = 0, offset, length } of overwrite) {
113
+ const size = this.#memories[memory]?.bytes.length;
114
+ if (size === undefined)
115
+ throw new RangeError('overwrite range names a missing memory');
116
+ if (!Number.isSafeInteger(offset) ||
117
+ !Number.isSafeInteger(length) ||
118
+ offset < 0 ||
119
+ length < 0)
120
+ throw new RangeError('overwrite range needs a non-negative integer offset and length');
121
+ if (offset + length > size)
122
+ throw new RangeError('overwrite range exceeds the memory');
123
+ if (length)
124
+ merged[memory].push([offset, offset + length]);
125
+ }
126
+ return merged.map((pairs) => {
127
+ pairs.sort((a, b) => a[0] - b[0]);
128
+ const out = [];
129
+ for (const [start, end] of pairs) {
130
+ const last = out[out.length - 1];
131
+ if (last && start <= last[1])
132
+ last[1] = Math.max(last[1], end);
133
+ else
134
+ out.push([start, end]);
135
+ }
136
+ return out;
137
+ });
138
+ }
93
139
  }
@@ -1,4 +1,4 @@
1
- import type { FolioOptions, ProgramInput } from './node.ts';
1
+ import type { FolioOptions, ProgramInput } from './index.ts';
2
2
  /** A trusted program registered under an artifact id. */
3
3
  export interface HostArtifact {
4
4
  /** The program or prepared plan every session of this artifact runs. */
@@ -1,5 +1,5 @@
1
- import { Folio } from "./node.js";
2
- import { decodeBytes, decodeValue, encodeBytes, encodeValue } from "./remote.js";
1
+ import { decodeBytes, decodeValue, encodeBytes, encodeValue } from "../remote/index.js";
2
+ import { Folio } from "./index.js";
3
3
  class ProtocolError extends Error {
4
4
  status;
5
5
  constructor(message, status = 400) {
@@ -1,6 +1,6 @@
1
- import type { PreparedProgram } from './compiler.ts';
2
- import type { IterationReason } from './iteration-owner.ts';
3
- import type { IterationReport } from './iteration.ts';
1
+ import type { PreparedProgram } from '../execution/compiler.ts';
2
+ import type { ExecutionProfile, ExecutionReport } from '../execution/types.ts';
3
+ import type { IterationStallOptions } from '../iteration/index.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. */
@@ -19,52 +19,7 @@ export interface RunOptions {
19
19
  /** Bound participating workers without rebuilding the isolate group. */
20
20
  maximumWorkers?: number;
21
21
  }
22
- /** What a run did: results, how it was routed and what the speculation cost. */
23
- export interface ExecutionReport {
24
- /** Return values of the call, or of each call in a batch. */
25
- values: unknown[];
26
- /** Workers that executed regions; zero for a serial run. */
27
- workers: number;
28
- /** Regions discovered and dispatched. */
29
- regions: number;
30
- /** Regions that conflicted and replayed against committed state. */
31
- replayed: number;
32
- /** Regions or batches that fell back to native execution at the owner. */
33
- fallbacks: number;
34
- /** `native-shared` ran proved kernels on the shared allocation without tracking. */
35
- mode: 'serial' | 'speculative' | 'native-shared';
36
- /** Set when the control-flow extractor or the iteration route produced the regions. */
37
- extraction?: 'control-flow' | 'iteration';
38
- /** `shared` regions read the physical allocation; `snapshot` ran on a copied arena. */
39
- memoryMode?: 'shared' | 'snapshot';
40
- /** Bytes copied into the worker group for snapshot execution. */
41
- snapshotBytes?: number;
42
- /** Why a run stayed serial or left the fast path. */
43
- reason?: 'requested' | 'small-workload' | 'no-parallel-plan' | 'single-region' | 'unsupported-module' | 'dependency' | 'guard-failed' | 'snapshot-unavailable' | 'previous-conflicts' | 'opaque-input' | IterationReason;
44
- /** The iteration executor's counts, summed over the owner calls of the run. */
45
- iteration?: IterationReport;
46
- /** Present when `FolioOptions.profile` is set. */
47
- profile?: ExecutionProfile;
48
- }
49
- /** Opt-in timings. Process CPU is measured once at the coordinator, not summed from these. */
50
- export interface ExecutionProfile {
51
- /** Elapsed time of the whole run. */
52
- wallMs: number;
53
- /** Elapsed time of each region or batch observation on its worker. */
54
- workerWallMs: number[];
55
- /** Thread CPU time of each observation. */
56
- workerCpuMs: number[];
57
- /** Ordered dependency validation. */
58
- validationMs: number;
59
- /** Committing validated writes to canonical memory. */
60
- commitMs: number;
61
- /** Re-executing conflicted regions. */
62
- replayMs: number;
63
- /** Bytes tracked as read by speculative regions. */
64
- readBytes: number;
65
- /** Bytes tracked as written by speculative regions. */
66
- writeBytes: number;
67
- }
22
+ export type { ExecutionProfile, ExecutionReport };
68
23
  /** Pool construction options. */
69
24
  export interface FolioOptions {
70
25
  /**
@@ -97,6 +52,48 @@ export interface FolioOptions {
97
52
  * @since 1.0.1
98
53
  */
99
54
  adaptiveRouting?: boolean;
55
+ /**
56
+ * Undo entries per iteration the iteration route may grow its logs to when a batch exhausts the
57
+ * default capacity, retrying that batch once. Off unless set: on the padded LZ4 consumer the
58
+ * retry costs more than the dispatch gains, because the ordered validator is quadratic in the
59
+ * logged entries.
60
+ * @since 1.1.0
61
+ */
62
+ iterationLogCeiling?: number;
63
+ /**
64
+ * Learn read windows from the first batch of an iteration loop that completes without a
65
+ * conflict, so loads of the input the iterations stream through set no per-access mark. The next
66
+ * batch counts the loads on the windows, and they stay armed only if they pay. Off by
67
+ * default. A window can only cost a false conflict, never a different result.
68
+ * @since 1.1.0
69
+ */
70
+ iterationReadWindows?: boolean;
71
+ /**
72
+ * Keep a summary of which 64-word blocks of each read bitmap a read touched, so the workers scan
73
+ * those blocks and not the whole bitmap after every iteration. The conflicts found do not change.
74
+ * Costs a few executed instructions on every tracked read. Off by default.
75
+ * @since 1.1.0
76
+ */
77
+ iterationReadSummary?: boolean;
78
+ /**
79
+ * Stop an iteration batch that does not return. The worker module polls a stop word at every
80
+ * loop start, which costs a few percent of worker time on tight loops, so it is off by
81
+ * default. When a batch has run past its limit the
82
+ * workers trap, the batch rolls back from the undo logs and the loop finishes serially with
83
+ * `iteration.stopped` set to `stalled`. Needed for programs whose iterations can read state
84
+ * another iteration is changing and then loop on it, such as a linked structure that two
85
+ * iterations rewrite.
86
+ * @since 1.1.0
87
+ */
88
+ iterationStall?: boolean | IterationStallOptions;
89
+ /**
90
+ * Judge an iteration loop that is a little under the dispatch floor on one timed batch, and let
91
+ * the batches a running loop has shown decide whether what is left pays, instead of the floor
92
+ * alone. A probe that loses ends the dispatch and the loop runs serially for the next 16 calls.
93
+ * The result is the same either way; only the choice of route changes. Off by default.
94
+ * @since 1.1.0
95
+ */
96
+ iterationSecondChance?: boolean;
100
97
  }
101
98
  /** A same-process isolate group; callers give it exclusive memory access during each run. */
102
99
  export declare class Folio {
@@ -1,11 +1,11 @@
1
1
  import { availableParallelism } from 'node:os';
2
2
  import { isArrayBuffer, isSharedArrayBuffer, isUint8Array } from 'node:util/types';
3
3
  import { Worker } from 'node:worker_threads';
4
- import { Coordinator } from "./coordinator.js";
5
- import { decideAdmission, decideBatch, decideCollapse } from "./iteration-admission.js";
6
- import { iterationArguments, iterationFit } from "./iteration-layout.js";
7
- import { memoryImports } from "./memory.js";
8
- import { numberBits, restoreNumbers } from "./values.js";
4
+ import { Coordinator } from "../execution/coordinator.js";
5
+ import { decideAdmission, decideBatch, decideBound, decideCollapse, decideProof, decideRemaining } from "../iteration/admission.js";
6
+ import { memoryImports } from "../memory/imports.js";
7
+ import { iterationArguments, iterationFit, iterationWindowBytes } from "../memory/iteration-layout.js";
8
+ import { numberBits, restoreNumbers } from "../remote/values.js";
9
9
  /** Wraps an asynchronous host import for Wasm stack suspension. */
10
10
  export function suspending(fn) {
11
11
  const runtime = WebAssembly;
@@ -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;
@@ -77,7 +99,7 @@ async function selectIteration(program, options, size) {
77
99
  Object.keys(program.native ?? {}).length)
78
100
  return;
79
101
  const refuse = (reason, detail) => ({ reason, detail });
80
- const { iterationOwner } = await import("./iteration-owner.js");
102
+ const { iterationOwner } = await import("../iteration/owner.js");
81
103
  const built = iterationOwner(program.original, route, program.stackRoute?.stack?.name);
82
104
  if (!('owner' in built))
83
105
  return built;
@@ -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)
@@ -242,7 +278,7 @@ export class Folio {
242
278
  const candidate = new WebAssembly.Module(Uint8Array.from(control.coordinator));
243
279
  const originalImports = WebAssembly.Module.imports(native);
244
280
  const retainedImports = WebAssembly.Module.imports(candidate).filter((item) => item.module !== control.namespace);
245
- // Binding accessors are effects too: retain the original engine lookup sequence.
281
+ // binding accessors are effects too, so keep the engine's lookup order
246
282
  if (JSON.stringify(originalImports) === JSON.stringify(retainedImports)) {
247
283
  this.#control = control;
248
284
  executable = candidate;
@@ -268,8 +304,8 @@ export class Folio {
268
304
  const automatic = new Map();
269
305
  let controlBindings;
270
306
  let iterationBindings;
271
- // Resolve bindings when the engine asks for them, in its original order.
272
- // Enumerating/spreading caller namespaces would invoke accessors early or twice.
307
+ // resolve bindings when the engine asks, in its order
308
+ // spreading caller namespaces would run their accessors early or twice
273
309
  const imports = new Proxy(Object.create(null), {
274
310
  get: (_, module) => {
275
311
  if (this.#control && module === this.#control.namespace) {
@@ -345,9 +381,8 @@ export class Folio {
345
381
  });
346
382
  }
347
383
  });
348
- // JSPI Promise resolution can assimilate an externref Promise result.
349
- // Only explicitly asynchronous entries get that ABI; ordinary exports
350
- // retain their native identity and return-value semantics.
384
+ // jspi promise resolution can assimilate an externref promise result, so only
385
+ // explicitly asynchronous entries get that abi; other exports keep their identity
351
386
  const promising = options.promising ?? [];
352
387
  for (const name of promising) {
353
388
  if (!WebAssembly.Module.exports(native).some((value) => value.name === name && value.kind === 'function'))
@@ -355,7 +390,15 @@ export class Folio {
355
390
  if (!runtime.promising)
356
391
  throw new Error('this runtime does not support JSPI');
357
392
  }
358
- this.#instance = new WebAssembly.Instance(executable, imports);
393
+ try {
394
+ this.#instance = new WebAssembly.Instance(executable, imports);
395
+ }
396
+ catch (error) {
397
+ if (error instanceof WebAssembly.LinkError &&
398
+ /shared state of memory/.test(error.message))
399
+ 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');
400
+ throw error;
401
+ }
359
402
  if (this.#control) {
360
403
  this.#exports = Object.create(null);
361
404
  for (const item of WebAssembly.Module.exports(native)) {
@@ -411,7 +454,7 @@ export class Folio {
411
454
  reasons: ['compiled module has no inspectable source bytes']
412
455
  }
413
456
  : isUint8Array(input) || isArrayBuffer(input)
414
- ? (await import("./compiler.js")).prepare(isUint8Array(input) ? input : new Uint8Array(input), {
457
+ ? (await import("../execution/compiler.js")).prepare(isUint8Array(input) ? input : new Uint8Array(input), {
415
458
  minimumRegionWork: options.minimumRegionWork,
416
459
  assumedTripCount: options.assumedTripCount
417
460
  })
@@ -672,10 +715,15 @@ export class Folio {
672
715
  await it.pool?.close();
673
716
  it.pool = undefined;
674
717
  try {
675
- const { IterationPool } = await import("./iteration.js");
718
+ const { IterationPool } = await import("../iteration/index.js");
676
719
  it.pool = await IterationPool.open(it.route, it.memory, {
677
720
  arenaBase: it.arenaBase,
678
- width
721
+ windowBytes: iterationWindowBytes,
722
+ width,
723
+ ...(this.#logCeiling === undefined ? {} : { logCeiling: this.#logCeiling }),
724
+ ...(this.#readWindows ? { readWindows: true } : {}),
725
+ ...(this.#readSummary ? { readSummary: true } : {}),
726
+ ...(this.#stall ? { stall: this.#stall } : {})
679
727
  });
680
728
  }
681
729
  catch (error) {
@@ -754,7 +802,7 @@ export class Folio {
754
802
  report.reason = run.reason ?? 'no-parallel-plan';
755
803
  return report;
756
804
  }
757
- // the host function the owner's loop calls: 1 when every iteration ran, 0 to run the loop itself
805
+ // host call the owner's loop makes: 1 when every iteration ran, 0 to run the loop here
758
806
  #iterate(values) {
759
807
  const it = this.#iteration;
760
808
  const run = it.run;
@@ -766,6 +814,7 @@ export class Folio {
766
814
  };
767
815
  const route = it.route;
768
816
  const pool = run.pool;
817
+ const secondChance = this.#secondChance;
769
818
  const entry = {};
770
819
  it.owner.locals.forEach((local, index) => (entry[local] = values[index]));
771
820
  const trip = Number(entry[route.trip.local]) >>> 0;
@@ -773,8 +822,15 @@ export class Folio {
773
822
  return decline('trip-zero');
774
823
  if (trip < 2)
775
824
  return decline('no-admission');
776
- if (it.memory.buffer.byteLength !== pool.arena.memoryBytes)
825
+ if (it.memory.buffer.byteLength !== pool.memoryBytes)
777
826
  return decline('no-arena');
827
+ const key = `${route.owner}|${pool.width}|${this.#logCeiling ?? ''}`;
828
+ const known = it.verdicts.get(key);
829
+ if (known?.stop) {
830
+ if (known.skipped++ < iterationReprobe)
831
+ return decline(known.stop);
832
+ it.verdicts.delete(key);
833
+ }
778
834
  const frameBase = route.frame ? Number(entry[route.frame.local]) >>> 0 : 0;
779
835
  const plain = (it.plain ??= this.#plain(it));
780
836
  const replay = (k) => {
@@ -788,16 +844,35 @@ export class Folio {
788
844
  frameBase,
789
845
  entry,
790
846
  replay,
791
- admit: (ms) => decideAdmission(ms, trip, pool.width),
847
+ window: known?.window,
848
+ admit: (ms) => decideAdmission(ms, trip, pool.width, secondChance),
792
849
  loses: decideBatch,
793
- collapses: decideCollapse
850
+ collapses: decideCollapse,
851
+ hopeless: decideBound,
852
+ unproven: decideProof,
853
+ reconsider: (ms, remaining, last) => decideRemaining(ms, remaining, pool.width, secondChance ? last : undefined)
794
854
  });
795
855
  }
796
856
  finally {
797
857
  run.iteration = addCounts(run.iteration, pool.report);
798
858
  }
799
- if (pool.report.stopped)
800
- run.reason ??= pool.report.stopped;
859
+ const stopped = pool.report.stopped;
860
+ if (stopped)
861
+ run.reason ??= stopped;
862
+ const structural = stopped === 'dependency' ||
863
+ stopped === 'log-exhausted' ||
864
+ stopped === 'frame-carried dependence' ||
865
+ stopped === 'stalled';
866
+ const w = pool.report.window;
867
+ const learned = w?.source === 'discovered' && !w.batches;
868
+ if (structural && !learned)
869
+ it.verdicts.set(key, { stop: stopped, skipped: 0 });
870
+ else if (pool.report.admission?.probeLost)
871
+ it.verdicts.set(key, { stop: 'no-admission', skipped: 0 });
872
+ else if (w && (w.batches || learned))
873
+ it.verdicts.set(key, { window: { low: w.low, end: w.end }, skipped: 0 });
874
+ else if (known)
875
+ it.verdicts.delete(key);
801
876
  return 1;
802
877
  }
803
878
  // a plain instance of the worker module on the shared memory; replay runs iterations on it
@@ -868,8 +943,8 @@ export class Folio {
868
943
  failed = true;
869
944
  failure = error;
870
945
  }
871
- // If the original coordinator traps first, pending preceding regions still
872
- // own the earlier effects/trap in program order.
946
+ // if the original coordinator traps first, pending regions still own the
947
+ // earlier effects and the trap in program order
873
948
  await coordinator.flush();
874
949
  if (failed)
875
950
  throw failure;