@gmitch215/folio 1.1.0 → 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 (122) hide show
  1. package/README.md +78 -810
  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} +5 -5
  14. package/dist/{extract.d.ts → execution/extract.d.ts} +3 -13
  15. package/dist/{extract.js → execution/extract.js} +7 -8
  16. package/dist/{fold.d.ts → execution/fold.d.ts} +15 -3
  17. package/dist/{guards.d.ts → execution/guards.d.ts} +2 -1
  18. package/dist/execution/types.d.ts +221 -0
  19. package/dist/{affine-state.d.ts → folds/affine-state.d.ts} +18 -47
  20. package/dist/{affine-state.js → folds/affine-state.js} +18 -44
  21. package/dist/{affine.d.ts → folds/affine.d.ts} +12 -24
  22. package/dist/{affine.js → folds/affine.js} +8 -17
  23. package/dist/{boundaries.d.ts → folds/boundaries.d.ts} +7 -18
  24. package/dist/{boundaries.js → folds/boundaries.js} +5 -13
  25. package/dist/{certified.d.ts → folds/certified.d.ts} +13 -24
  26. package/dist/{certified.js → folds/certified.js} +12 -26
  27. package/dist/{certify.d.ts → folds/certify.d.ts} +11 -22
  28. package/dist/{certify.js → folds/certify.js} +24 -41
  29. package/dist/{memo.d.ts → footprints/memo.d.ts} +8 -33
  30. package/dist/{memo.js → footprints/memo.js} +8 -2
  31. package/dist/{ranges.js → footprints/ranges.js} +1 -1
  32. package/dist/{read-scan.js → footprints/read-scan.js} +1 -1
  33. package/dist/{read-windows.d.ts → footprints/read-windows.d.ts} +6 -32
  34. package/dist/{read-windows.js → footprints/read-windows.js} +8 -7
  35. package/dist/index.d.ts +16 -4
  36. package/dist/index.js +14 -2
  37. package/dist/{iteration-admission.d.ts → iteration/admission.d.ts} +2 -38
  38. package/dist/{iteration.d.ts → iteration/index.d.ts} +8 -98
  39. package/dist/{iteration.js → iteration/index.js} +28 -28
  40. package/dist/{inline.js → iteration/inline.js} +2 -9
  41. package/dist/{iteration-owner.d.ts → iteration/owner.d.ts} +3 -3
  42. package/dist/{iteration-owner.js → iteration/owner.js} +4 -3
  43. package/dist/{iteration-worker.js → iteration/worker.js} +3 -3
  44. package/dist/{managed.d.ts → managed/index.d.ts} +3 -3
  45. package/dist/{managed.js → managed/index.js} +7 -9
  46. package/dist/managed/outbox.d.ts +128 -0
  47. package/dist/managed/outbox.js +156 -0
  48. package/dist/managed/pool.d.ts +221 -0
  49. package/dist/managed/pool.js +310 -0
  50. package/dist/managed/tasks.d.ts +154 -0
  51. package/dist/managed/tasks.js +183 -0
  52. package/dist/{bake.d.ts → memory/bake.d.ts} +12 -6
  53. package/dist/{bake.js → memory/bake.js} +9 -7
  54. package/dist/memory/continuation.d.ts +141 -0
  55. package/dist/memory/continuation.js +495 -0
  56. package/dist/memory/elastic-peer.d.ts +20 -0
  57. package/dist/memory/elastic-peer.js +39 -0
  58. package/dist/memory/elastic-sql.d.ts +11 -0
  59. package/dist/memory/elastic-sql.js +35 -0
  60. package/dist/memory/elastic.d.ts +130 -0
  61. package/dist/memory/elastic.js +475 -0
  62. package/dist/memory/growth-governor.d.ts +16 -0
  63. package/dist/memory/growth-governor.js +42 -0
  64. package/dist/memory/imports.d.ts +10 -0
  65. package/dist/memory/imports.js +89 -0
  66. package/dist/{iteration-layout.d.ts → memory/iteration-layout.d.ts} +1 -1
  67. package/dist/{pages.d.ts → memory/pages.d.ts} +3 -3
  68. package/dist/memory.d.ts +5 -10
  69. package/dist/memory.js +5 -89
  70. package/dist/{context.d.ts → node/context.d.ts} +1 -1
  71. package/dist/{host.d.ts → node/host.d.ts} +1 -1
  72. package/dist/{host.js → node/host.js} +2 -2
  73. package/dist/{node.d.ts → node/index.d.ts} +4 -49
  74. package/dist/{node.js → node/index.js} +16 -17
  75. package/dist/{tasks.d.ts → node/tasks.d.ts} +2 -13
  76. package/dist/{worker.js → node/worker.js} +2 -2
  77. package/dist/{ownership.js → ownership/index.js} +7 -10
  78. package/dist/{ownership-redirect.d.ts → ownership/redirect.d.ts} +2 -2
  79. package/dist/{ownership-redirect.js → ownership/redirect.js} +2 -2
  80. package/dist/{ownership-slices.d.ts → ownership/slices.d.ts} +3 -3
  81. package/dist/{ownership-slices.js → ownership/slices.js} +3 -3
  82. package/dist/{frames.d.ts → remote/frames.d.ts} +1 -1
  83. package/dist/{frames.js → remote/frames.js} +2 -2
  84. package/dist/{remote.d.ts → remote/index.d.ts} +7 -2
  85. package/dist/{remote.js → remote/index.js} +7 -2
  86. package/dist/{router.d.ts → routing/index.d.ts} +3 -3
  87. package/dist/{router.js → routing/index.js} +19 -15
  88. package/dist/{router-worker.js → routing/worker.js} +1 -1
  89. package/dist/{slices.d.ts → slices/index.d.ts} +2 -2
  90. package/dist/{slices.js → slices/index.js} +5 -5
  91. package/dist/slices/worker.d.ts +1 -0
  92. package/dist/{slices-worker.js → slices/worker.js} +2 -2
  93. package/dist/workers.d.ts +5 -0
  94. package/dist/workers.js +5 -0
  95. package/package.json +30 -80
  96. /package/dist/{browser-worker.d.ts → browser/worker.d.ts} +0 -0
  97. /package/dist/{browser-worker.js → browser/worker.js} +0 -0
  98. /package/dist/{fold.js → execution/fold.js} +0 -0
  99. /package/dist/{guards.js → execution/guards.js} +0 -0
  100. /package/dist/{import-order.d.ts → execution/import-order.d.ts} +0 -0
  101. /package/dist/{import-order.js → execution/import-order.js} +0 -0
  102. /package/dist/{runs.d.ts → execution/runs.d.ts} +0 -0
  103. /package/dist/{runs.js → execution/runs.js} +0 -0
  104. /package/dist/{transaction.d.ts → execution/transaction.d.ts} +0 -0
  105. /package/dist/{transaction.js → execution/transaction.js} +0 -0
  106. /package/dist/{iteration-worker.d.ts → execution/types.js} +0 -0
  107. /package/dist/{ranges.d.ts → footprints/ranges.d.ts} +0 -0
  108. /package/dist/{read-scan.d.ts → footprints/read-scan.d.ts} +0 -0
  109. /package/dist/{iteration-admission.js → iteration/admission.js} +0 -0
  110. /package/dist/{inline.d.ts → iteration/inline.d.ts} +0 -0
  111. /package/dist/{worker.d.ts → iteration/worker.d.ts} +0 -0
  112. /package/dist/{iteration-layout.js → memory/iteration-layout.js} +0 -0
  113. /package/dist/{lease.d.ts → memory/lease.d.ts} +0 -0
  114. /package/dist/{lease.js → memory/lease.js} +0 -0
  115. /package/dist/{pages.js → memory/pages.js} +0 -0
  116. /package/dist/{context.js → node/context.js} +0 -0
  117. /package/dist/{tasks.js → node/tasks.js} +0 -0
  118. /package/dist/{router-worker.d.ts → node/worker.d.ts} +0 -0
  119. /package/dist/{ownership.d.ts → ownership/index.d.ts} +0 -0
  120. /package/dist/{values.d.ts → remote/values.d.ts} +0 -0
  121. /package/dist/{values.js → remote/values.js} +0 -0
  122. /package/dist/{slices-worker.d.ts → routing/worker.d.ts} +0 -0
package/dist/index.d.ts CHANGED
@@ -1,4 +1,16 @@
1
- export { prepare } from './compiler.ts';
2
- export type { LoopPlan, PreparedProgram } from './compiler.ts';
3
- export { Folio, suspending } from './node.ts';
4
- export type { Call, ExecutionProfile, ExecutionReport, FolioOptions, ProgramInput, RunOptions } from './node.ts';
1
+ export { prepare, prepareContext } from './execution/compiler.ts';
2
+ export type { LoopPlan, PrepareOptions, PreparedContext, PreparedProgram } from './execution/compiler.ts';
3
+ export * from './execution/fold.ts';
4
+ export * from './folds/affine.ts';
5
+ export * from './folds/certified.ts';
6
+ export * from './folds/certify.ts';
7
+ export * from './node/context.ts';
8
+ export * from './node/host.ts';
9
+ export { Folio, suspending } from './node/index.ts';
10
+ export type { Call, ExecutionProfile, ExecutionReport, FolioOptions, ProgramInput, RunOptions } from './node/index.ts';
11
+ export * from './node/tasks.ts';
12
+ export * from './ownership/index.ts';
13
+ export * from './ownership/redirect.ts';
14
+ export * from './ownership/slices.ts';
15
+ export * from './routing/index.ts';
16
+ export * from './slices/index.ts';
package/dist/index.js CHANGED
@@ -1,2 +1,14 @@
1
- export { prepare } from "./compiler.js";
2
- export { Folio, suspending } from "./node.js";
1
+ export { prepare, prepareContext } from "./execution/compiler.js";
2
+ export * from "./execution/fold.js";
3
+ export * from "./folds/affine.js";
4
+ export * from "./folds/certified.js";
5
+ export * from "./folds/certify.js";
6
+ export * from "./node/context.js";
7
+ export * from "./node/host.js";
8
+ export { Folio, suspending } from "./node/index.js";
9
+ export * from "./node/tasks.js";
10
+ export * from "./ownership/index.js";
11
+ export * from "./ownership/redirect.js";
12
+ export * from "./ownership/slices.js";
13
+ export * from "./routing/index.js";
14
+ export * from "./slices/index.js";
@@ -1,41 +1,5 @@
1
- /** Why the rest of a loop ran serially after the pooled path was tried or refused. */
2
- export type IterationStop = 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'dependency' | 'stalled';
3
- /** What the admission decision saw and chose for one owner call's loop. */
4
- export interface IterationAdmission {
5
- /** Time of iteration 0 on the owner thread, on a plain instance and the real frame. */
6
- plainIterationMs: number;
7
- /** Serial time of the iterations after iteration 0, from `plainIterationMs`. */
8
- remainingSerialMs: number;
9
- /** The least remaining serial time worth dispatching: `fixedMs * margin`. */
10
- floorMs: number;
11
- /** The decision before the first dispatch. A later stop is `IterationReport.stopped`. */
12
- admitted: boolean;
13
- /** Wall of the last batch, dispatch to the end of its replays. */
14
- batchWallMs?: number;
15
- /** The serial time of the iterations of that batch, from the online estimate. */
16
- batchSerialMs?: number;
17
- /** The latest estimate of serial time per iteration, from iteration 0, replays or workers. */
18
- estimateMs?: number;
19
- /** Set when a refused loop was admitted after timed serial iterations; the iteration index. */
20
- readmittedAt?: number;
21
- /** Admitted as a probe: under the floor, over `probeFraction` of it, one timed batch decides. */
22
- probe?: boolean;
23
- /** The probe batch did not beat the serial time of its iterations, and the dispatch ended. */
24
- probeLost?: boolean;
25
- /** One entry per batch, only under `admissionSeam.trace`. */
26
- trace?: AdmissionStep[];
27
- }
28
- /** What the estimate and the batch rule saw after one batch. @internal */
29
- export interface AdmissionStep {
30
- first: number;
31
- count: number;
32
- windows: boolean;
33
- trackedMeanMs: number;
34
- kappa?: number;
35
- estimateMs: number;
36
- wallMs: number;
37
- serialMs: number;
38
- }
1
+ import type { AdmissionStep, IterationAdmission, IterationStop } from '../execution/types.ts';
2
+ export type { AdmissionStep, IterationAdmission, IterationStop };
39
3
  /** The constants of the decision. A re-calibration changes these and nothing else. */
40
4
  export interface IterationAdmissionConstants {
41
5
  /** Wall of the pooled path that does not shrink with the loop: dispatch, join, validation. */
@@ -1,9 +1,10 @@
1
- import type { IterationRoute } from './extract.ts';
2
- import { type IterationAdmission, type IterationStop } from './iteration-admission.ts';
3
- import { type IterationArena, type IterationArenaOptions, type IterationWindow } from './iteration-layout.ts';
4
- import { type IterationReadWindows, type ReadWindowCounts } from './read-windows.ts';
5
- export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from './iteration-layout.ts';
6
- export type { IterationArena, IterationArenaOptions, IterationWindow } from './iteration-layout.ts';
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';
7
8
  /** Pool construction options. */
8
9
  export interface IterationPoolOptions extends IterationArenaOptions {
9
10
  /** Start of the arena, 64-byte aligned, in memory the caller keeps free while the pool is open. */
@@ -107,98 +108,7 @@ export interface IterationJob {
107
108
  count: number;
108
109
  }) => boolean;
109
110
  }
110
- /** What a run did. `regions`, `replayed`, `fallbacks` and `workers` parallel `ExecutionReport`. */
111
- export interface IterationReport {
112
- /** Workers that took part. */
113
- workers: number;
114
- /** Iterations run on workers, the regions of this mode. */
115
- regions: number;
116
- /** Dispatched iterations that were rolled back and rerun serially at the owner. */
117
- replayed: number;
118
- /** Iterations whose writes were undone before the rerun. */
119
- rolledBack: number;
120
- /** Batches whose first failure was a trap or an exhausted undo log, not a dependency. */
121
- fallbacks: number;
122
- /** Iterations that trapped on a worker. */
123
- traps: number;
124
- /** Iterations that exhausted their undo log. */
125
- exhausted: number;
126
- /** Iterations that trapped on an access to another iteration's stack slot. */
127
- violations: number;
128
- /** Batches in which the stall guard fired. */
129
- stalls: number;
130
- /** Iterations the stall word stopped, rolled back and rerun serially. */
131
- stalledIterations: number;
132
- batches: number;
133
- failedBatches: number;
134
- undoEntries: number;
135
- /** The most undo entries one completed iteration logged. */
136
- maxLogEntries: number;
137
- /** Times a batch that exhausted its log was retried with the grown log. */
138
- logGrowths: number;
139
- /** Iterations rolled back and dispatched again by such a retry. They are not in `regions`. */
140
- retried: number;
141
- /** Ordered iteration pairs by hazard. */
142
- conflicts: {
143
- raw: number;
144
- war: number;
145
- waw: number;
146
- frame: number;
147
- };
148
- /** From posting a batch to the last worker reply. */
149
- dispatchMs: number;
150
- validationMs: number;
151
- rollbackMs: number;
152
- replayMs: number;
153
- /** Wasm time inside workers, summed. */
154
- workerRunMs: number;
155
- /** Bitmap scan and clear time inside workers, summed. */
156
- workerScanMs: number;
157
- /** Time the workers spent marking read windows before their iterations, summed. */
158
- workerMarkMs: number;
159
- /** Read bitmap words the workers scanned, summed. */
160
- workerScanWords: number;
161
- /** Read bitmap words they found non-zero. */
162
- workerScanSet: number;
163
- /**
164
- * Iterations the owner ran as the serial program without dispatching them: iteration 0, the
165
- * rest of a loop after a stop, or all of them when admission refused the loop.
166
- */
167
- serial: number;
168
- /** What ended the dispatch early, or why admission refused the loop. */
169
- stopped?: IterationStop;
170
- /** What the admission callback saw and chose; set when the job had one. */
171
- admission?: IterationAdmission;
172
- /** Frame conflicts that fell in a window's bytes; they are also in `conflicts.frame`. */
173
- windowConflicts: number;
174
- /** The window the batches ran on, if any, and where it came from. */
175
- window?: {
176
- low: number;
177
- end: number;
178
- source: 'given' | 'discovered';
179
- /** Batches dispatched on it. */
180
- batches: number;
181
- };
182
- /** Why a window that was offered or found was not used. */
183
- windowRefused?: string;
184
- /** The read windows learned from the first clean batch, with the batches that ran on them. */
185
- readWindows?: IterationReadWindows & {
186
- batches: number;
187
- learnedFrom: number;
188
- };
189
- /** Why read windows were not learned, or were dropped after a batch on them conflicted. */
190
- readWindowRefused?: string;
191
- /** What the counted batch on the read windows saw, and whether they were armed for the loop. */
192
- readWindowGate?: {
193
- iterations: number;
194
- counts: ReadWindowCounts;
195
- saved: number;
196
- spent: number;
197
- /** which check the armed module runs first for a load of at most 8 bytes */
198
- order: 'window' | 'exempt';
199
- armed: boolean;
200
- };
201
- }
111
+ export type { IterationReport };
202
112
  /** What a worker returns for one iteration. */
203
113
  export interface IterationOutcome {
204
114
  index: number;
@@ -1,11 +1,11 @@
1
1
  import { availableParallelism } from 'node:os';
2
2
  import { isSharedArrayBuffer } from 'node:util/types';
3
3
  import { MessageChannel, Worker, receiveMessageOnPort } from 'node:worker_threads';
4
+ import { learnReadWindows, readWindowsClear, readWindowsPay } from "../footprints/read-windows.js";
5
+ import { iterationArena, iterationEntryBytes, iterationGranules, iterationShadowCopies, iterationWindowCopy } from "../memory/iteration-layout.js";
6
+ import { admissionSeam, batchBound, probeEstimate, projectBatch, refineEstimate } from "./admission.js";
4
7
  import { inlineGlobals, lowerInline } from "./inline.js";
5
- import { admissionSeam, batchBound, probeEstimate, projectBatch, refineEstimate } from "./iteration-admission.js";
6
- import { iterationArena, iterationEntryBytes, iterationGranules, iterationShadowCopies, iterationWindowCopy } from "./iteration-layout.js";
7
- import { learnReadWindows, readWindowsClear, readWindowsPay } from "./read-windows.js";
8
- export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from "./iteration-layout.js";
8
+ export { iterationArena, iterationArenaBytes, iterationArguments, iterationEntryBytes, iterationFit, iterationFrameShadow, iterationGranules, iterationLogCeiling, iterationWindowBytes, iterationWindowCopy } from "../memory/iteration-layout.js";
9
9
  const newReport = (workers) => ({
10
10
  workers,
11
11
  regions: 0,
@@ -36,12 +36,12 @@ const newReport = (workers) => ({
36
36
  serial: 0,
37
37
  windowConflicts: 0
38
38
  });
39
- const shift = Math.log2(iterationGranules.read / iterationGranules.write);
39
+ const writeToReadShift = Math.log2(iterationGranules.read / iterationGranules.write);
40
40
  // sorted write granules against sorted read runs
41
41
  function hitsReads(writes, runs) {
42
42
  let p = 0;
43
43
  for (let i = 0; i < writes.length; i++) {
44
- const g = writes[i] >> shift;
44
+ const g = writes[i] >> writeToReadShift;
45
45
  while (p < runs.length && runs[p] + runs[p + 1] <= g)
46
46
  p += 2;
47
47
  if (p >= runs.length)
@@ -449,7 +449,7 @@ export class IterationPool {
449
449
  await Promise.all(Array.from({ length: width }, () => {
450
450
  const channel = new MessageChannel();
451
451
  const signal = new SharedArrayBuffer(4);
452
- const worker = new Worker(new URL(`./iteration-worker.${extension}`, import.meta.url), {
452
+ const worker = new Worker(new URL(`./worker.${extension}`, import.meta.url), {
453
453
  workerData: {
454
454
  module,
455
455
  memory,
@@ -829,18 +829,18 @@ export class IterationPool {
829
829
  }
830
830
  }
831
831
  const wallMs = performance.now() - t0;
832
+ const tracked = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
832
833
  if (job.admit) {
833
834
  // the workers' own time per completed iteration, scaled to serial time
834
- estimate = refineEstimate(estimate, outcomes.filter((o) => o.status === 0).map((o) => o.runMs), Boolean(usedRw));
835
+ estimate = refineEstimate(estimate, tracked, Boolean(usedRw));
835
836
  }
836
837
  const serialMs = count * perMs();
837
838
  if (report.admission && admissionSeam.trace) {
838
- const ran = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
839
839
  (report.admission.trace ??= []).push({
840
840
  first,
841
841
  count,
842
842
  windows: Boolean(usedRw),
843
- trackedMeanMs: ran.reduce((a, b) => a + b, 0) / (ran.length || 1),
843
+ trackedMeanMs: tracked.reduce((a, b) => a + b, 0) / (tracked.length || 1),
844
844
  kappa: usedRw ? estimate.kappaWindows : estimate.kappa,
845
845
  estimateMs: estimate.estimateMs,
846
846
  wallMs,
@@ -860,7 +860,6 @@ export class IterationPool {
860
860
  // tracking cost bounds the speedup whatever the dispatch costs; read windows learned by
861
861
  // this batch will change that cost, so their first batch decides
862
862
  const windowsNext = Boolean(rw) && report.readWindows?.batches === 0;
863
- const tracked = outcomes.filter((o) => o.status === 0).map((o) => o.runMs);
864
863
  if (windowsNext &&
865
864
  job.admit &&
866
865
  job.hopeless &&
@@ -1114,33 +1113,34 @@ export class IterationPool {
1114
1113
  return `the window of ${bytes} bytes is over ${A.windowBytes}`;
1115
1114
  if (window.end > this.#memoryBytes)
1116
1115
  return 'the window passes the end of memory';
1117
- const meets = (low, end) => window.low < end && window.end > low;
1118
- if (meets(A.base, A.base + A.bytes))
1119
- return 'the window overlaps the arena';
1120
- if (this.#grown &&
1121
- meets(this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
1122
- return 'the window overlaps the grown logs';
1123
- if (A.frameBytes && meets(frameBase, frameBase + A.frameBytes))
1124
- return 'the window overlaps the owner frame';
1116
+ const overlap = this.#overlap(window, frameBase, 'the window');
1117
+ if (overlap)
1118
+ return overlap;
1125
1119
  if (A.slotBytes - A.frameBytes - bytes - 64 < windowStackBytes)
1126
1120
  return `the window leaves less than ${windowStackBytes} bytes of stack in a slot`;
1127
1121
  }
1128
1122
  // why the certified windows cannot be privatized for this call, or undefined when they can
1129
1123
  #refuseOwnership(plan, frameBase) {
1130
- const A = this.arena;
1131
- const meets = (w, low, end) => w.low < end && w.end > low;
1132
1124
  for (const w of plan.windows) {
1133
1125
  if (w.end > this.#memoryBytes)
1134
1126
  return 'a certified window passes the end of memory';
1135
- if (meets(w, A.base, A.base + A.bytes))
1136
- return 'a certified window overlaps the arena';
1137
- if (this.#grown &&
1138
- meets(w, this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
1139
- return 'a certified window overlaps the grown logs';
1140
- if (A.frameBytes && meets(w, frameBase, frameBase + A.frameBytes))
1141
- return 'a certified window overlaps the owner frame';
1127
+ const overlap = this.#overlap(w, frameBase, 'a certified window');
1128
+ if (overlap)
1129
+ return overlap;
1142
1130
  }
1143
1131
  }
1132
+ // the arena, the grown logs and the owner frame, in that order
1133
+ #overlap(window, frameBase, subject) {
1134
+ const A = this.arena;
1135
+ const meets = (low, end) => window.low < end && window.end > low;
1136
+ if (meets(A.base, A.base + A.bytes))
1137
+ return `${subject} overlaps the arena`;
1138
+ if (this.#grown &&
1139
+ meets(this.#grown.base, this.#grown.base + this.#grown.inFlight * this.#grown.bytes))
1140
+ return `${subject} overlaps the grown logs`;
1141
+ if (A.frameBytes && meets(frameBase, frameBase + A.frameBytes))
1142
+ return `${subject} overlaps the owner frame`;
1143
+ }
1144
1144
  // address ranges a read window must stay out of: the arena and the grown logs
1145
1145
  #forbidden() {
1146
1146
  const A = this.arena;
@@ -1,13 +1,6 @@
1
1
  import binaryen from 'binaryen';
2
- import { stackRoute } from "./extract.js";
3
- import { importedMemory, shareMemory } from "./iteration-owner.js";
4
- const info = (expression) => {
5
- const id = binaryen.getExpressionId(expression);
6
- if (id === binaryen.UnreachableId || id === binaryen.NopId) {
7
- return { id, type: binaryen.getExpressionType(expression) };
8
- }
9
- return binaryen.getExpressionInfo(expression);
10
- };
2
+ import { info, stackRoute } from "../execution/extract.js";
3
+ import { importedMemory, shareMemory } from "./owner.js";
11
4
  // #region inline tracking lowering
12
5
  const capi = binaryen;
13
6
  /** Names of the exported mutable i32 globals the inline lowering adds, plus the stack export. */
@@ -1,6 +1,6 @@
1
- import type { IterationRoute } from './extract.ts';
2
- /** Why the iteration route is not used, in `ExecutionReport.reason`. */
3
- export type IterationReason = 'no-arena' | 'memory-size-observed' | 'import-order' | 'workers-unavailable' | 'trip-zero' | 'no-admission' | 'log-exhausted' | 'frame-carried dependence' | 'stalled';
1
+ import type { IterationRoute } from '../execution/extract.ts';
2
+ import type { IterationReason } from '../execution/types.ts';
3
+ export type { IterationReason };
4
4
  /** The owner module with its loop handed to `iterate`, and what the host needs to bind it. */
5
5
  export interface IterationOwner {
6
6
  module: Uint8Array;
@@ -1,5 +1,5 @@
1
1
  import binaryen from 'binaryen';
2
- import { restoreImportOrder } from "./import-order.js";
2
+ import { restoreImportOrder } from "../execution/import-order.js";
3
3
  const PAGE_LIMIT = 65536;
4
4
  function uleb(value) {
5
5
  const out = [];
@@ -110,6 +110,7 @@ export function shareMemory(bytes, memory) {
110
110
  ]);
111
111
  }
112
112
  const refusal = (reason, detail) => ({ reason, detail });
113
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
113
114
  /**
114
115
  * Builds the owner module of an iteration route: the memory import is shared, and the one loop
115
116
  * of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.
@@ -196,7 +197,7 @@ export function iterationOwner(original, route, stack) {
196
197
  bytes = restoreImportOrder(m.emitBinary(), imports);
197
198
  }
198
199
  catch (error) {
199
- return refusal('import-order', `import order cannot be kept: ${error instanceof Error ? error.message : String(error)}`);
200
+ return refusal('import-order', `import order cannot be kept: ${messageOf(error)}`);
200
201
  }
201
202
  new WebAssembly.Module(Uint8Array.from(bytes));
202
203
  return {
@@ -215,7 +216,7 @@ export function iterationOwner(original, route, stack) {
215
216
  };
216
217
  }
217
218
  catch (error) {
218
- return refusal('no-arena', `iteration owner unavailable: ${error instanceof Error ? error.message : String(error)}`);
219
+ return refusal('no-arena', `iteration owner unavailable: ${messageOf(error)}`);
219
220
  }
220
221
  finally {
221
222
  module?.dispose();
@@ -1,7 +1,7 @@
1
1
  import { parentPort, workerData } from 'node:worker_threads';
2
- import { iterationArguments, iterationEntryBytes, iterationShadowCopies, iterationWindowCopy } from "./iteration-layout.js";
3
- import { markReadSummary, scanReads } from "./read-scan.js";
4
- import { markReadWindow, readWindowsAt } from "./read-windows.js";
2
+ import { markReadSummary, scanReads } from "../footprints/read-scan.js";
3
+ import { markReadWindow, readWindowsAt } from "../footprints/read-windows.js";
4
+ import { iterationArguments, iterationEntryBytes, iterationShadowCopies, iterationWindowCopy } from "../memory/iteration-layout.js";
5
5
  const { module, memory, arena, globals, iterate, locals, frameSize, port, signal, control, ownership } = workerData;
6
6
  const L = arena;
7
7
  const ENTRY = iterationEntryBytes;
@@ -1,6 +1,6 @@
1
- import type { ControlPlan } from './extract.ts';
2
- import type { MemoryImport } from './memory.ts';
3
- import type { ExecutionReport } from './node.ts';
1
+ import type { ControlPlan } from '../execution/extract.ts';
2
+ import type { ExecutionReport } from '../execution/types.ts';
3
+ import type { MemoryImport } from '../memory/imports.ts';
4
4
  /** Precompiled modules for the managed backend. Nothing is compiled at request time. */
5
5
  export interface ManagedArtifact {
6
6
  /** The source program; serial and fallback execution use it unchanged. */
@@ -1,10 +1,10 @@
1
- import { Coordinator } from "./coordinator.js";
2
- import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, runsVersion, snapshotLength, validateIdentity } from "./frames.js";
3
- import { iterationArena, iterationEntryBytes, iterationFit } from "./iteration-layout.js";
4
- import { RegionMemo } from "./memo.js";
5
- import { clearRanges, decodeRanges, encodeRangesFrame, escapes, FootprintCache, rangePage, RangeSet, restoreRanges, resultEscapes } from "./ranges.js";
6
- import { capRuns, packWrites } from "./runs.js";
7
- import { SpeculationLimit, transaction } from "./transaction.js";
1
+ import { Coordinator } from "../execution/coordinator.js";
2
+ import { capRuns, packWrites } from "../execution/runs.js";
3
+ import { SpeculationLimit, transaction } from "../execution/transaction.js";
4
+ import { RegionMemo } from "../footprints/memo.js";
5
+ import { clearRanges, decodeRanges, encodeRangesFrame, escapes, FootprintCache, rangePage, RangeSet, restoreRanges, resultEscapes } from "../footprints/ranges.js";
6
+ import { iterationArena, iterationEntryBytes, iterationFit } from "../memory/iteration-layout.js";
7
+ import { decodeFrame, decodeResults, encodeFrame, encodeResults, encodeSnapshot, restoreSnapshot, runsVersion, snapshotLength, validateIdentity } from "../remote/frames.js";
8
8
  // the exported globals of the inline lowering, as named by `inlineGlobals` in inline.ts
9
9
  const markGlobals = {
10
10
  readBitmap: '__folio_rb',
@@ -366,7 +366,6 @@ export class ManagedFolio {
366
366
  exports;
367
367
  /** Optimization refusals and fallbacks seen so far. */
368
368
  diagnostics = [];
369
- #artifact;
370
369
  #lanes;
371
370
  #instance;
372
371
  #serial = new WebAssembly.Global({ value: 'i32', mutable: true }, 1);
@@ -399,7 +398,6 @@ export class ManagedFolio {
399
398
  this.#memo = new RegionMemo(options.memo);
400
399
  this.#memoModule = moduleIdentity(artifact.transactional ?? artifact.original);
401
400
  }
402
- this.#artifact = artifact;
403
401
  this.#snapshotEncoding = options.snapshotEncoding ?? 'dense';
404
402
  if (!['auto', 'dense'].includes(this.#snapshotEncoding))
405
403
  throw new TypeError('invalid snapshot encoding');
@@ -0,0 +1,128 @@
1
+ import type { SqlStorage } from '../memory/continuation.ts';
2
+ import type { ReplayPolicies, TaskRow, TaskValue } from './tasks.ts';
3
+ import { TaskTable } from './tasks.ts';
4
+ /** Thrown by an effect to end its row as `failed` with no retry. */
5
+ export declare class PermanentError extends Error {
6
+ constructor(message: string, options?: {
7
+ cause?: unknown;
8
+ });
9
+ }
10
+ /** What an effect receives for one attempt. */
11
+ export interface OutboxContext {
12
+ /** The row id. */
13
+ id: string;
14
+ /** The kind the row was enqueued with. */
15
+ kind: string;
16
+ /** The claim number of this attempt; a replay gets the next one. */
17
+ attempt: number;
18
+ /**
19
+ * The idempotency key. It is the row id and is the same on every attempt, so use it as the
20
+ * `Message-ID` of a mail or the `Idempotency-Key` header of a request.
21
+ */
22
+ key: string;
23
+ /** The arguments as enqueued, text or bytes. */
24
+ args: TaskValue;
25
+ }
26
+ /**
27
+ * Runs the effect of one row. Return its result, or nothing, or a promise of either. Throw a
28
+ * `PermanentError` when it can never succeed, and any other error when it did not happen and
29
+ * trying again is safe.
30
+ */
31
+ export type OutboxEffect = (context: OutboxContext) => void | TaskValue | Promise<void | TaskValue>;
32
+ /** A row to enqueue. Pass `args` or `argsJson`, not both. */
33
+ export interface OutboxItem {
34
+ /** Unique id, which is also the idempotency key. Rows run in the byte order of the id. */
35
+ id: string;
36
+ /** The kind of effect, such as `mail` or `http`. It picks the replay policy. */
37
+ kind: string;
38
+ /** The arguments, text or bytes. */
39
+ args?: TaskValue;
40
+ /** Serialized with `JSON.stringify` into `args`. */
41
+ argsJson?: unknown;
42
+ }
43
+ /** Time for the outbox. */
44
+ export interface OutboxClock {
45
+ /** Milliseconds on any clock the outbox and its readers agree on. */
46
+ now(): number;
47
+ }
48
+ /** What one `drain` did. */
49
+ export interface OutboxReport {
50
+ /** Rows whose effect finished and whose result was written. */
51
+ done: number;
52
+ /** Rows ended as `failed` by a `PermanentError`, by their last attempt or by an exhausted lease. */
53
+ failed: number;
54
+ /** Rows whose effect threw and that wait for another attempt. */
55
+ retried: number;
56
+ /** Rows ended as `failed` because their lease ended and their kind is `report`. */
57
+ reported: number;
58
+ }
59
+ /** What `resume` returns. */
60
+ export interface OutboxResume extends OutboxReport {
61
+ /** When to call `resume` again, at least 5 s ahead. Unset when no row is open. */
62
+ wake?: number;
63
+ }
64
+ /** Options for `Outbox`. */
65
+ export interface OutboxOptions {
66
+ /** Runs the effect of a row. */
67
+ effect: OutboxEffect;
68
+ /**
69
+ * What to do with a row whose lease ended while it ran, by kind. `resend` runs the effect
70
+ * again. `report` ends the row as `failed` and never runs it again. A kind that is not listed
71
+ * is `report`.
72
+ */
73
+ policies?: ReplayPolicies;
74
+ /**
75
+ * Resolves once every earlier write survives a reset; pass `() => ctx.storage.sync()` inside a
76
+ * Durable Object. Awaited after an enqueue, after a claim before the effect, after a
77
+ * completion and after a failure. Without it the outbox trusts the storage to be durable at
78
+ * each await.
79
+ */
80
+ flush?: () => Promise<void>;
81
+ /** Time source. Defaults to `Date.now`. */
82
+ clock?: OutboxClock;
83
+ /** Lease of a claim, in milliseconds. Default 15,000, minimum 5,000. An effect that awaits renews it. */
84
+ leaseMs?: number;
85
+ /** Executions a row may start before it fails. Default 3. */
86
+ maxAttempts?: number;
87
+ /** Rows run at once by `drain`. Default 1. */
88
+ width?: number;
89
+ /** SQL identifier of the table. Default `folio_tasks`. */
90
+ table?: string;
91
+ }
92
+ /**
93
+ * A durable outbox for effects that must not be lost or repeated without notice: mail, outbound
94
+ * requests, Redis commands, cron units. Rows live in the task table of the object's own SQLite.
95
+ *
96
+ * Each row goes through four steps in this order: claim, flush, effect, complete, flush. The
97
+ * flush after the claim is what gives `report` its meaning. A reset after it leaves a running
98
+ * row that a successor knows may have run its effect, and the successor ends it as `failed`
99
+ * instead of running it again. A reset before it loses the claim, and nothing ran. The flush
100
+ * after the completion keeps a finished effect from being replayed after a reset.
101
+ *
102
+ * So a `resend` kind runs its effect at least once and a `report` kind at most once. A reported
103
+ * row is the operator's: it is final, and sending the effect again means a new id.
104
+ */
105
+ export declare class Outbox {
106
+ #private;
107
+ /** The task table, for callers that read rows directly. */
108
+ readonly table: TaskTable;
109
+ constructor(sql: SqlStorage, options: OutboxOptions);
110
+ /**
111
+ * Adds rows and returns how many were new, once they are flushed. An id that exists is
112
+ * ignored, so repeating an enqueue that failed is safe.
113
+ */
114
+ enqueue(items: readonly OutboxItem[]): Promise<number>;
115
+ /**
116
+ * Runs every row that is ready, `width` at a time, and returns what happened. A row whose
117
+ * effect threw waits for the next `drain` instead of running again at once. Rows whose lease
118
+ * ended are replayed or reported by their kind first.
119
+ */
120
+ drain(): Promise<OutboxReport>;
121
+ /**
122
+ * One pass for an alarm: `drain`, then when to call again. `wake` is at least 5 s ahead and
123
+ * never before the soonest lease ends, and it is unset when no row is open.
124
+ */
125
+ resume(): Promise<OutboxResume>;
126
+ /** Every row in id order, whatever its state. */
127
+ results(): TaskRow[];
128
+ }