@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
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Fitted on a Mac sweep of `scripts/research/iteration-admission.ts` and checked on the rig at widths
3
+ * 8 and 4; a re-calibration updates only these two numbers.
4
+ *
5
+ * `fixedMs` 2 is the smallest value at which no cell of the Mac sweep (18 cells, 4 KiB to 4 MiB
6
+ * by 8 to 128 iterations, width 8) dispatched and lost. The pooled wall minus the batch time
7
+ * measured 0.1 to 2.9 ms there with the input copy left out of the timing; the prototype's rows
8
+ * bracket 3 to 8 ms but include that copy. The loop is not worth dispatching when the serial time
9
+ * of its remaining iterations is below `fixedMs * margin`.
10
+ *
11
+ * `margin` 1.25 is the speedup a batch has to show over the serial time of its iterations for
12
+ * the loop to keep dispatching. A batch that misses it twice in a row ends the dispatch, and so
13
+ * does one batch whose wall passes `batchCollapse` times that serial time.
14
+ */
15
+ export const iterationAdmissionConstants = {
16
+ fixedMs: 2,
17
+ margin: 1.25
18
+ };
19
+ /**
20
+ * With the second chance on, a loop whose remaining serial time is under the floor but over this
21
+ * fraction of it is admitted as a probe: its first timed batch has to beat the serial time of its
22
+ * iterations by the margin, or the dispatch ends there. The floor was fitted on a build with the
23
+ * full read scan and no read windows, so it is the least certain number in the decision.
24
+ */
25
+ export const probeFraction = 0.5;
26
+ /**
27
+ * Decides before the first dispatch from the measured serial time of iteration 0, which has
28
+ * already run. Admits when at least two iterations are left for at least two workers and their
29
+ * serial time exceeds `fixedMs * margin`. Whether dispatch pays is then checked per batch.
30
+ */
31
+ export function admitIteration({ plainIterationMs: t0, trip, width, constants = iterationAdmissionConstants, secondChance = false }) {
32
+ const remaining = trip - 1;
33
+ const remainingSerialMs = remaining * t0;
34
+ const floorMs = constants.fixedMs * constants.margin;
35
+ const able = Number.isFinite(t0) && remaining >= 2 && width >= 2;
36
+ const admitted = able && remainingSerialMs > floorMs;
37
+ if (secondChance && able && !admitted && remainingSerialMs > floorMs * probeFraction)
38
+ return { plainIterationMs: t0, remainingSerialMs, floorMs, admitted: true, probe: true };
39
+ return { plainIterationMs: t0, remainingSerialMs, floorMs, admitted };
40
+ }
41
+ /** True when a batch did not beat the serial time of its iterations by the margin. */
42
+ export function batchLoses(batchWallMs, batchSerialMs, constants = iterationAdmissionConstants) {
43
+ return batchWallMs * constants.margin > batchSerialMs;
44
+ }
45
+ /** Batch wall over serial time past which one batch is a verdict, with no second batch to confirm. */
46
+ export const batchCollapse = 1.5;
47
+ /** True when a batch took clearly longer than the serial time of its iterations. */
48
+ export function batchCollapses(batchWallMs, batchSerialMs) {
49
+ return batchWallMs > batchSerialMs * batchCollapse;
50
+ }
51
+ /**
52
+ * Test and sweep seam, module state and not an option. `scale` multiplies the measured time of
53
+ * iteration 0 before the first decision and `batchScale` the wall of each batch before the batch
54
+ * rule, and divides the bound of a batch; `force` admits any loop with an iteration left after
55
+ * iteration 0 and never stops on the batch rule or the bound. The structural stops
56
+ * (`log-exhausted`, `frame-carried dependence`, `dependency`) are not affected. `trace` records
57
+ * one entry per batch in the admission report. `gate` false keeps read windows armed whatever the
58
+ * counted batch says, so a sweep can compare the two.
59
+ * @internal
60
+ */
61
+ export const admissionSeam = {
62
+ scale: 1,
63
+ batchScale: 1,
64
+ force: false,
65
+ trace: false,
66
+ gate: true,
67
+ estimator: 'median'
68
+ };
69
+ /**
70
+ * The serial estimate the probe holds after a block: the lower of the last two block means, the
71
+ * median of every block mean so far, or the mean of every probed iteration.
72
+ * @internal
73
+ */
74
+ export function probeEstimate(kind, last, per, means, mean) {
75
+ if (kind === 'mean')
76
+ return mean;
77
+ if (kind === 'min')
78
+ return Math.min(last, per);
79
+ const sorted = [...means].sort((x, y) => x - y);
80
+ if (kind === 'q75')
81
+ return sorted[Math.min(sorted.length - 1, Math.ceil(0.75 * sorted.length) - 1)];
82
+ const mid = sorted.length >> 1;
83
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
84
+ }
85
+ /** `admitIteration` through the seam; what the host function calls. */
86
+ export function decideAdmission(plainIterationMs, trip, width, secondChance = false) {
87
+ const decision = admitIteration({
88
+ plainIterationMs: plainIterationMs * admissionSeam.scale,
89
+ trip,
90
+ width,
91
+ secondChance
92
+ });
93
+ if (admissionSeam.force && trip >= 2 && width >= 2)
94
+ decision.admitted = true;
95
+ return decision;
96
+ }
97
+ /**
98
+ * Updates the estimate from the worker-side times of the iterations a batch completed, with no
99
+ * host call per iteration. The first batch fixes `kappa` as the serial estimate over the least
100
+ * tracked time, at most 1 because a tracked iteration is never faster than a plain one. The least
101
+ * time, not the median, because the iteration that the estimate came from may be the smallest of
102
+ * a batch that is mostly large, and the median would then read its size as the tracking cost. The
103
+ * estimate is then the mean tracked time times `kappa`: a batch of iterations dearer than the
104
+ * earlier estimate raises it, and a batch of cheaper ones lowers it. When the first iteration was
105
+ * larger than every iteration of the batch, `kappa` is capped and the estimate is the tracked
106
+ * mean, an upper bound on the serial time. Times of zero or less are ignored. A batch on read
107
+ * windows is cheaper to track than the first, so it has its own scale, fitted the same way to the
108
+ * same reference the first time one runs; the unwindowed scale would read its time as serial time.
109
+ */
110
+ export function refineEstimate(before, trackedMs, windows = false) {
111
+ const ran = trackedMs.filter((ms) => ms > 0);
112
+ if (!ran.length)
113
+ return before;
114
+ const referenceMs = before.referenceMs ?? before.estimateMs;
115
+ const learned = windows ? before.kappaWindows : before.kappa;
116
+ const kappa = learned ?? Math.min(1, referenceMs / Math.min(...ran));
117
+ return {
118
+ kappa: windows ? before.kappa : kappa,
119
+ kappaWindows: windows ? kappa : before.kappaWindows,
120
+ referenceMs,
121
+ estimateMs: (kappa * ran.reduce((sum, ms) => sum + ms, 0)) / ran.length
122
+ };
123
+ }
124
+ /**
125
+ * Whether `remaining` more iterations at `perIterationMs` each are worth dispatching, through the
126
+ * seam. The pool asks it with the online estimate before each batch after the first and after the
127
+ * timed serial blocks of a refused loop.
128
+ *
129
+ * With `last`, the wall and size of the last timed batch, a loop under the floor still goes on
130
+ * when the batches it has seen say so: the pooled cost of what is left is the batch wall times the
131
+ * batches that cover it, and that times the margin has to be under their serial time. The floor
132
+ * prices the wake-up and the learning batch, which a loop that is running has already paid.
133
+ */
134
+ export function decideRemaining(perIterationMs, remaining, width, last) {
135
+ if (decideAdmission(perIterationMs, remaining + 1, width).admitted)
136
+ return true;
137
+ if (!last || remaining < 2 || width < 2 || !(last.count > 0))
138
+ return false;
139
+ const pooled = Math.ceil(remaining / last.count) * last.wallMs * admissionSeam.batchScale;
140
+ return remaining * perIterationMs > pooled * iterationAdmissionConstants.margin;
141
+ }
142
+ /** `batchLoses` through the seam; what the host function passes the pool. */
143
+ export function decideBatch(batchWallMs, batchSerialMs) {
144
+ if (admissionSeam.force)
145
+ return false;
146
+ return batchLoses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
147
+ }
148
+ /** `batchCollapses` through the seam; what the host function passes the pool. */
149
+ export function decideCollapse(batchWallMs, batchSerialMs) {
150
+ if (admissionSeam.force)
151
+ return false;
152
+ return batchCollapses(batchWallMs * admissionSeam.batchScale, batchSerialMs);
153
+ }
154
+ /** Speedup below which a batch cannot pay even with free dispatch, validation and joins. */
155
+ export const boundFloor = 1;
156
+ /**
157
+ * The best speedup a batch could reach: the serial time of the iterations it completed over the
158
+ * time `width` workers need for them at the tracked time they showed. Wake, join and validation
159
+ * only add to the wall, so a bound under one means the loop cannot win at this tracking cost.
160
+ */
161
+ export function batchBound(perIterationMs, trackedMs, width) {
162
+ const ran = trackedMs.filter((ms) => ms > 0);
163
+ if (!ran.length || !(perIterationMs > 0) || width < 1)
164
+ return Infinity;
165
+ const mean = ran.reduce((sum, ms) => sum + ms, 0) / ran.length;
166
+ return (ran.length * perIterationMs) / (Math.ceil(ran.length / width) * mean);
167
+ }
168
+ /**
169
+ * A loop whose first batch bounds the speedup above this has tracking cost to spare: realized
170
+ * speedups ran at about half the bound (aes-ctr 1.2 of 2.3, lz4-compress 1.2 of 2.4,
171
+ * aes-cbc-decrypt 1.2 of 2.0 on the Mac sweep), so such a loop goes on to full batches on its
172
+ * read windows. A loop under it gets one short batch on them first.
173
+ */
174
+ export const proofBound = 2;
175
+ /** True when the bound of a batch is under `boundFloor`, through the seam; what the host passes. */
176
+ export function decideBound(bound) {
177
+ if (admissionSeam.force)
178
+ return false;
179
+ return bound / admissionSeam.batchScale < boundFloor;
180
+ }
181
+ /**
182
+ * The wall and the serial time of the next batch of `next` iterations, from a batch that ran. Its
183
+ * wall minus the time its workers needed for the iterations it completed is the cost that does
184
+ * not shrink with the batch: wake, join and validation. The next batch pays that plus the
185
+ * workers' share of its own iterations. Validation grows with the batch, so the wall comes out
186
+ * low and a projected loss is a loss.
187
+ */
188
+ export function projectBatch(wallMs, trackedMs, perIterationMs, next, width) {
189
+ const ran = trackedMs.filter((ms) => ms > 0);
190
+ if (!ran.length || !(perIterationMs > 0) || next < 1 || width < 1)
191
+ return undefined;
192
+ const mean = ran.reduce((sum, ms) => sum + ms, 0) / ran.length;
193
+ const fixed = Math.max(0, wallMs - Math.ceil(ran.length / width) * mean);
194
+ return { wallMs: Math.ceil(next / width) * mean + fixed, serialMs: next * perIterationMs };
195
+ }
196
+ /** True when a bound is low enough that the first batch on read windows should be a short one. */
197
+ export function decideProof(bound) {
198
+ if (admissionSeam.force)
199
+ return false;
200
+ return bound / admissionSeam.batchScale < proofBound;
201
+ }
@@ -0,0 +1,239 @@
1
+ import type { IterationRoute } from '../execution/extract.ts';
2
+ import type { IterationReport } from '../execution/types.ts';
3
+ import { type ReadWindowCounts } from '../footprints/read-windows.ts';
4
+ import { type IterationArena, type IterationArenaOptions, type IterationWindow } from '../memory/iteration-layout.ts';
5
+ import { type IterationAdmission } from './admission.ts';
6
+ export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from '../memory/iteration-layout.ts';
7
+ export type { IterationArena, IterationArenaOptions, IterationWindow } from '../memory/iteration-layout.ts';
8
+ /** Pool construction options. */
9
+ export interface IterationPoolOptions extends IterationArenaOptions {
10
+ /** Start of the arena, 64-byte aligned, in memory the caller keeps free while the pool is open. */
11
+ arenaBase: number;
12
+ /** Workers; defaults to up to four. */
13
+ width?: number;
14
+ /**
15
+ * Undo entries per iteration of the log a batch is retried with after its log is exhausted.
16
+ * Defaults to `logCapacity`, which leaves the retry off; `iterationLogCeiling` is the grown size the tests use.
17
+ */
18
+ logCeiling?: number;
19
+ /**
20
+ * Learn read windows from the first batch that completes without a conflict: a load that falls
21
+ * in a window sets no mark and skips the slot and frame checks, because the worker marked the
22
+ * whole window before the iteration. The next full batch runs on a lowering that counts its
23
+ * loads, and the windows stay armed for the rest of the call only if the counts say they pay
24
+ * (`readWindowsPay`). Off by default.
25
+ */
26
+ readWindows?: boolean;
27
+ /**
28
+ * Keep a summary byte per 64 words of every read bitmap, set by each read mark, so a worker scans
29
+ * only the blocks a read touched. The scan result is the same as the full scan. Off by default.
30
+ */
31
+ readSummary?: boolean;
32
+ /**
33
+ * Guard a batch against an iteration that never returns. The worker module polls a stop word at
34
+ * every loop start. When the owner has waited past the limit it sets the word: every iteration
35
+ * in flight traps, is rolled back from the undo logs and rerun serially in order, and the loop
36
+ * ends with `stopped: 'stalled'`. Off by default; `true` takes the defaults of
37
+ * `IterationStallOptions`.
38
+ */
39
+ stall?: boolean | IterationStallOptions;
40
+ }
41
+ /** The wait before the stall guard stops a batch: `floorMs` plus `factor` times its serial estimate. */
42
+ export interface IterationStallOptions {
43
+ /**
44
+ * Times the serial time of the iterations one worker runs in a batch. Default 50, above the
45
+ * slowdown of tracked code over plain code by an order of magnitude.
46
+ */
47
+ factor?: number;
48
+ /** Least wait in ms, which also covers waking the workers and compiling the first iteration. Default 2000. */
49
+ floorMs?: number;
50
+ }
51
+ /** One owner call's loop. */
52
+ export interface IterationJob {
53
+ /** Iterations to run. An entry value of zero runs 2^32 times in the program; refuse that upstream. */
54
+ trip: number;
55
+ /** The owner's frame local after its prologue; the image at `[frameBase, frameBase + size)` is copied. */
56
+ frameBase: number;
57
+ /** Loop-entry value of every local in `route.locals` that has an `argument`, except the frame. */
58
+ entry: Readonly<Record<number, number | bigint>>;
59
+ /** Runs iteration `k` serially on the owner frame. A throw is the program's trap. */
60
+ replay(k: number): void;
61
+ /** Test hook: `reverse` makes one worker run a batch last to first. Default `forward`. */
62
+ schedule?: 'forward' | 'reverse';
63
+ /** Test hook, unsound: validation checks to leave out. */
64
+ skip?: readonly ('raw' | 'war' | 'waw' | 'frame')[];
65
+ /**
66
+ * A window an earlier call learned: the batches start on slot-private copies of it. Ignored when
67
+ * the arena reserves no window bytes or the window does not fit this call (see `report.window`).
68
+ */
69
+ window?: IterationWindow;
70
+ /** Whether a batch that conflicts may name a window and go on with it. Default true. */
71
+ discover?: boolean;
72
+ /**
73
+ * Runs iteration 0 through `replay` on the owner thread first and times it. That is the serial
74
+ * program's first iteration, so its writes stay and the batches cover iterations 1 to `trip - 1`
75
+ * from the owner frame it leaves. Called once with the time of that iteration, before anything
76
+ * is dispatched. A refusal runs the other iterations through `replay` and dispatches nothing.
77
+ * Without `admit` every iteration is dispatched.
78
+ */
79
+ admit?: (plainIterationMs: number) => IterationAdmission;
80
+ /**
81
+ * Called after each batch that leaves iterations behind, with its wall (dispatch, validation,
82
+ * rollback and replay) and the serial time of its iterations at the time of iteration 0. True
83
+ * ends the dispatch and runs the rest through `replay`. Only used with `admit`.
84
+ */
85
+ loses?: (batchWallMs: number, batchSerialMs: number) => boolean;
86
+ /** Like `loses`, for a batch slow enough that a second batch is not needed to confirm it. */
87
+ collapses?: (batchWallMs: number, batchSerialMs: number) => boolean;
88
+ /**
89
+ * Called after each batch with the best speedup its workers could reach at the tracked time
90
+ * they showed. True ends the dispatch: no later batch could pay at this tracking cost. Only
91
+ * used with `admit`.
92
+ */
93
+ hopeless?: (bound: number) => boolean;
94
+ /**
95
+ * Called with the bound of the first batch when read windows were learned from it. True makes
96
+ * the first batch on them one iteration per worker, which `hopeless` and the projection of the
97
+ * next batch then judge. Only used with `admit` and `hopeless`.
98
+ */
99
+ unproven?: (bound: number) => boolean;
100
+ /**
101
+ * Whether `remaining` more iterations at `perIterationMs` of serial time each are worth
102
+ * dispatching. Asked with the online estimate before each batch after the first, where false ends
103
+ * the dispatch, and after the timed serial blocks of a refused loop, where true starts it. Only
104
+ * used with `admit`.
105
+ */
106
+ reconsider?: (perIterationMs: number, remaining: number, last?: {
107
+ wallMs: number;
108
+ count: number;
109
+ }) => boolean;
110
+ }
111
+ export type { IterationReport };
112
+ /** What a worker returns for one iteration. */
113
+ export interface IterationOutcome {
114
+ index: number;
115
+ /** 0 ran, 1 trapped, 2 undo log exhausted, 3 stopped by the stall word */
116
+ status: number;
117
+ entries: number;
118
+ /** wall time of the iteration inside the worker, on the tracked module */
119
+ runMs: number;
120
+ /** sorted write granules (32 bytes) from the undo log */
121
+ written: Int32Array;
122
+ /** [start, length] runs of read granules (64 bytes) */
123
+ reads: Int32Array;
124
+ /** written bit per frame byte, one i32 per 32-byte frame granule; empty when nothing was written */
125
+ frameWritten: Uint32Array;
126
+ /** bit per frame byte the iteration read before writing it, same layout; empty when none */
127
+ frameExposed: Uint32Array;
128
+ /** position in the batch of the first slot this iteration reached outside its own, or -1 */
129
+ touched?: number;
130
+ /** loads of at most 8 bytes by where they landed, from the counting module only */
131
+ counts?: ReadWindowCounts;
132
+ }
133
+ type Verdict = {
134
+ first: number;
135
+ firstFailure: number;
136
+ frameFirst: number;
137
+ conflicts: {
138
+ raw: number;
139
+ war: number;
140
+ waw: number;
141
+ frame: number;
142
+ };
143
+ /** Frame conflicts that fall in the first `windowWords` words; set only when that was asked for. */
144
+ window?: number;
145
+ };
146
+ type VerdictInput = Pick<IterationOutcome, 'status' | 'written' | 'reads'> & Partial<Pick<IterationOutcome, 'frameWritten' | 'frameExposed' | 'touched'>>;
147
+ type Skip = readonly ('raw' | 'war' | 'waw' | 'frame')[];
148
+ /** Ordered pairs by hazard and the first iteration that cannot keep its writes, or -1. */
149
+ interface MemoryConflicts {
150
+ raw: number;
151
+ war: number;
152
+ waw: number;
153
+ first: number;
154
+ }
155
+ /** The pairwise form: every ordered pair against every other. Any batch size; the reference. @internal */
156
+ export declare function pairwiseConflicts(outcomes: readonly VerdictInput[], skip: Skip): MemoryConflicts;
157
+ /**
158
+ * `pairwiseConflicts` in time linear in the sizes of the sets, for at most 32 outcomes: one table
159
+ * from write granule to the bit set of the iterations that wrote it, then each read granule looks
160
+ * its two write granules up. A pair counts once however many granules it shares, so the counts
161
+ * equal the pairwise form's. @internal
162
+ */
163
+ export declare function tabledConflicts(outcomes: readonly VerdictInput[], skip: Skip): MemoryConflicts;
164
+ /**
165
+ * Index of the first outcome that cannot keep its writes, or -1. Writes land in place, so every
166
+ * ordered pair is checked three ways: RAW marks the reader, WAR the earlier reader, WAW the earlier
167
+ * writer. A fourth check covers the frame, which each iteration owns as a private copy: an
168
+ * iteration fails when it read a frame byte before writing it that an earlier iteration wrote, and
169
+ * counts once. Works on the returned lists, never on dense bitmaps. A batch of at most 32 goes
170
+ * through `tabledConflicts`, a larger one through the pairwise form.
171
+ *
172
+ * `windowWords` is the number of leading frame words that belong to slot-private windows; the
173
+ * result then also counts, as `window`, the frame conflicts that fall in them.
174
+ */
175
+ export declare function iterationVerdict(outcomes: readonly VerdictInput[], skip?: Skip, windowWords?: number): Verdict;
176
+ /**
177
+ * The window a failed batch suggests: the span of the write granules that at least half of its
178
+ * iterations wrote, rounded out to 64 bytes. That is where iterations share a location they write
179
+ * every time, a scratch buffer, a context or an allocator's cursor, and `cap` bytes is the most a
180
+ * pool holds. Half and not two, because iterations that race on a shared context also write wild
181
+ * granules (a length read mid-update indexes anywhere), and those are rarely written twice. Whether
182
+ * the iterations write the window before they read it is not asked here: a window that is wrong
183
+ * only fails validation on the next batch.
184
+ */
185
+ export declare function discoverWindow(outcomes: readonly Pick<IterationOutcome, 'written'>[], cap: number): {
186
+ window?: IterationWindow;
187
+ reason?: string;
188
+ granules: number;
189
+ };
190
+ /**
191
+ * Runs the loop of one owner call on worker threads. Each iteration gets a private stack slot and
192
+ * tracks its reads and writes inline. The owner validates a batch in order, rolls back the first
193
+ * failing iteration and every later one from the undo logs, and replays them through `replay`.
194
+ * The arena belongs to the pool until `close`.
195
+ *
196
+ * Each iteration runs on a private copy of the owner frame, taken from the owner frame when its
197
+ * batch is dispatched. The lowered module tracks the frame: a written bit per frame byte, and an
198
+ * exposed bit per 32-byte frame granule that the iteration read before it wrote the byte. An
199
+ * iteration fails validation, like a RAW pair, when it has an exposed granule that an earlier
200
+ * iteration of the same batch wrote (`conflicts.frame`); it and every later one in the batch roll
201
+ * back and replay. After a batch validates, each kept
202
+ * iteration's written frame bytes are copied into the owner frame in order, so the next batch
203
+ * starts from the serial frame and a replay runs on it. The guarantee: a read of an owner frame
204
+ * byte that the same iteration has not written yet, with a write by an earlier iteration of the
205
+ * batch to that byte, is detected, and an earlier batch's writes are seen through the copy.
206
+ * Excluded: a read of stack below the frame (callee frames, indeterminate before the callee writes
207
+ * them) is not tracked, and imported host functions that touch memory are not seen. The shadow
208
+ * is byte-exact for scalar accesses and ranges; a conservative read would only add reports.
209
+ *
210
+ * The callee stack of an iteration, the part of its slot below the frame copy, sets no marks and
211
+ * logs no undo entries, and a rollback does not restore it. An access that reaches another slot
212
+ * of the arena traps; the iteration fails with the owner of that slot, so both and every later one
213
+ * replay (`violations` counts them). A program that reads callee stack before writing it sees
214
+ * what an earlier iteration in that slot left, a rolled back one included.
215
+ *
216
+ * With `admit`, iteration 0 runs first on the owner and the batches cover the rest. Dispatch
217
+ * stops after a batch that exhausted an undo log, had a frame conflict, replayed more than half of
218
+ * its iterations, or (with `loses` and `collapses`) two batches in a row did not beat the serial
219
+ * time of their iterations or one took far longer than it; the rest of the loop runs through
220
+ * `replay` and `report.stopped` names the reason. Once an iteration fails, the workers start no
221
+ * further iteration of that batch, because it and every later one replay anyway.
222
+ */
223
+ export declare class IterationPool {
224
+ #private;
225
+ readonly arena: IterationArena;
226
+ readonly width: number;
227
+ private constructor();
228
+ /** Bytes of memory the pool expects: the arena's memory plus any pages its grown log added. */
229
+ get memoryBytes(): number;
230
+ /** The report of the last run, also after a run that threw. */
231
+ get report(): IterationReport;
232
+ /** Lowers the route's worker module inline and starts `width` workers over `memory`. */
233
+ static open(route: IterationRoute, memory: WebAssembly.Memory, options: IterationPoolOptions): Promise<IterationPool>;
234
+ /** Runs the loop to completion with ordered validation. Blocks the calling thread. */
235
+ run(job: IterationJob): IterationReport;
236
+ /** Stops the workers. Safe to call twice. */
237
+ close(): Promise<void>;
238
+ [Symbol.asyncDispose](): Promise<void>;
239
+ }