@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,182 @@
1
+ /** Names of the exported mutable i32 globals the inline lowering adds, plus the stack export. */
2
+ export declare const inlineGlobals: {
3
+ readonly readBitmap: "__folio_rb";
4
+ readonly writeBitmap: "__folio_wb";
5
+ readonly logPointer: "__folio_lp";
6
+ readonly logLimit: "__folio_ll";
7
+ readonly stampAddress: "__folio_sa";
8
+ readonly stackPointer: "__folio_sp";
9
+ readonly frameLow: "__folio_fl";
10
+ readonly frameSize: "__folio_fn";
11
+ readonly frameShadow: "__folio_fs";
12
+ readonly exemptLow: "__folio_xl";
13
+ readonly exemptEnd: "__folio_xe";
14
+ readonly slotLow: "__folio_sl";
15
+ readonly slotEnd: "__folio_se";
16
+ readonly arenaLow: "__folio_al";
17
+ readonly arenaEnd: "__folio_ae";
18
+ readonly violation: "__folio_xv";
19
+ readonly windowLow: "__folio_wl";
20
+ readonly windowEnd: "__folio_we";
21
+ readonly windowDelta: "__folio_wd";
22
+ readonly readWindow0Low: "__folio_r0l";
23
+ readonly readWindow0Span: "__folio_r0m";
24
+ readonly readWindow1Low: "__folio_r1l";
25
+ readonly readWindow1Span: "__folio_r1m";
26
+ readonly readSummary: "__folio_rs";
27
+ readonly readHits: "__folio_ch";
28
+ readonly readMisses: "__folio_cm";
29
+ readonly readExempt: "__folio_ce";
30
+ };
31
+ /** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
32
+ export declare const inlineEntryBytes: (writeGranule?: number) => number;
33
+ /** Options for `lowerInline`. */
34
+ export interface InlineOptions {
35
+ /** Read granule in bytes, a power of two from 16 to 4096. Default 64. */
36
+ readGranule?: number;
37
+ /** Write and undo granule in bytes, a power of two from 16 to 256. Default 32. */
38
+ writeGranule?: number;
39
+ /** Refuse a memory that is not shared. Pass false to lower a module for one thread. Default true. */
40
+ requireShared?: boolean;
41
+ /** The mutable i32 global exported as `__folio_sp`. Default: the one `stackRoute` names, if any. */
42
+ stack?: string;
43
+ /** Track exposed reads of one frame region (see `lowerInline`). Default off. */
44
+ frame?: boolean;
45
+ /** Leave one private stack window untracked and trap on another slot (see `lowerInline`). Default off. */
46
+ slot?: boolean;
47
+ /**
48
+ * Rebase accesses to one address window onto a slot-private copy (see `lowerInline`). Turns
49
+ * `frame` on, and `slot` when there is a stack global. Default off.
50
+ */
51
+ window?: boolean;
52
+ /**
53
+ * Trap an access that overlaps the window `[__folio_al, __folio_ae)`, with no stack global
54
+ * needed and no exempt or own window. For a lane whose arena sits above the program memory.
55
+ * Default off.
56
+ */
57
+ guard?: boolean;
58
+ /**
59
+ * Count a fuel unit at every function entry and loop start, as the host-call lowering does:
60
+ * `__folio_set_fuel(n)` sets the budget and `folio.exhausted` is called when it reaches 0.
61
+ * Default off.
62
+ */
63
+ fuel?: boolean;
64
+ /**
65
+ * Poll the i32 at `__folio_sa + 4` at every loop start and trap with `unreachable` when it is
66
+ * not zero, so the host can stop an iteration that does not return. Function entries are not
67
+ * polled: a call cycle runs out of stack and traps by itself. Default off.
68
+ */
69
+ stop?: boolean;
70
+ /**
71
+ * Read windows, 0 to 2: a load of at most 8 bytes that lies inside one sets no read mark and
72
+ * runs none of the slot or frame checks (see `lowerInline`). Default 0.
73
+ */
74
+ readWindows?: number;
75
+ /**
76
+ * Bytes of the read summary, a power of two from 1 to 32768, or 0 for none (see `lowerInline`).
77
+ * Default 0.
78
+ */
79
+ readSummary?: number;
80
+ /**
81
+ * With read windows, count the loads of at most 8 bytes by where they land: `__folio_ch` inside
82
+ * a window, `__folio_cm` outside every window and tracked, `__folio_ce` in the exempt window.
83
+ * The owner resets them. Default off.
84
+ */
85
+ readCount?: boolean;
86
+ /**
87
+ * With read windows, test the exempt window before the windows instead of after them. An exempt
88
+ * load then costs what it does with no windows and a hit costs 10 instructions more. Default off.
89
+ */
90
+ exemptFirst?: boolean;
91
+ }
92
+ /**
93
+ * A second lowering, next to the host-call one in `prepare`: it marks memory accesses inline, with
94
+ * no host call and no added import, so a region can be validated after it ran. Nothing in
95
+ * `prepare` calls it yet and its output is not a `PreparedProgram` field.
96
+ *
97
+ * State lives in mutable i32 globals the owner exports and sets before each region; all start at
98
+ * 0, which traps on the first access. `__folio_rb` and `__folio_wb` are the bases of the read and
99
+ * write bitmaps, `__folio_lp` and `__folio_ll` the undo log pointer and limit, `__folio_sa` the
100
+ * address of a shared i32 stamp counter (4-byte aligned). The stack pointer global is exported as
101
+ * `__folio_sp` when the module has one. A bitmap has one bit per granule: granule `g`, with
102
+ * `g = address >> log2(granule)`, is bit `g & 7` of byte `base + (g >> 3)`. The bitmaps are
103
+ * private to a region and the owner clears them between regions.
104
+ *
105
+ * Every load, store, atomic access and SIMD load marks its read granule, and an access that
106
+ * crosses a boundary marks both. A store, a SIMD lane store and the destination of `memory.copy`,
107
+ * `memory.fill` and `memory.init` mark write granules; atomic accesses mark both sets; the source
108
+ * of `memory.copy` marks read granules. The first write to a write granule appends an undo entry
109
+ * at `__folio_lp`: the granule address (u32), a stamp from an atomic add on `__folio_sa` taken
110
+ * after the prior bytes were copied and before the write, then the prior bytes of the granule.
111
+ * `__folio_lp` then advances by `inlineEntryBytes(writeGranule)`; an entry that would pass
112
+ * `__folio_ll` traps with `unreachable`. The start function is not lowered.
113
+ *
114
+ * With `frame: true` the module also tracks one frame region, for a stack frame whose bytes an
115
+ * iteration may read after an earlier iteration wrote them. The owner sets `__folio_fl` (low
116
+ * address), `__folio_fn` (size in bytes) and `__folio_fs` (shadow base) before a region; with
117
+ * `__folio_fn` at 0 nothing is tracked. An access that overlaps the region is checked against a
118
+ * shadow of one written bit per frame byte, `4 * ceil(size / 32)` bytes with the bits of frame
119
+ * granule `g` (32 bytes) in the i32 at `__folio_fs + 4 * g`, then 4 pad bytes, then the exposed
120
+ * bits laid out the same way, then 4 more pad bytes. A store sets written bits after its value is
121
+ * computed; a load sets the exposed bit of each byte it reads whose written bit is clear, so a
122
+ * region reports exactly the frame bytes it read before it wrote them.
123
+ * `memory.copy`, `memory.fill` and `memory.init` set or check the exact byte range, an atomic
124
+ * read-modify-write checks then sets, and any other atomic access or SIMD load checks. The owner
125
+ * zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
126
+ * the region is not tracked.
127
+ *
128
+ * With `slot: true` and a stack global, the owner also sets three address windows before a region:
129
+ * the exempt window `[__folio_xl, __folio_xe)`, the whole private slot `[__folio_sl, __folio_se)`
130
+ * and the arena of all slots `[__folio_al, __folio_ae)`. An access inside the exempt window sets no
131
+ * mark and logs no undo entry. An access that overlaps the arena but does not lie inside the own
132
+ * slot stores its address in `__folio_xv` and traps with `unreachable`, because another iteration
133
+ * owns those bytes. Every other access is tracked as before, so the exempt window must not contain
134
+ * the tracked frame; an access that crosses the window edge is tracked. `memory.copy`,
135
+ * `memory.fill` and `memory.init` apply the same tests to the whole range, and a range counts as
136
+ * inside only when every byte is. The exempt bytes are not restored by a rollback, so the owner
137
+ * must treat the window as dead after the region.
138
+ *
139
+ * With `readWindows: n` the owner also sets, per window `i` below `n`, `__folio_r<i>l` (first byte)
140
+ * and `__folio_r<i>m` (window size minus 7, or 0 for no window) before a region, and marks every
141
+ * read granule that the window touches in the read bitmap itself. A plain, non-atomic load or SIMD
142
+ * load of at most 8 bytes whose address `a` satisfies `a - low < size - 7` lies wholly inside the
143
+ * window, so its read mark is already set: it sets no mark and skips the slot, arena and frame
144
+ * checks. Every other access, a store, an atomic, a wider load, a load that crosses a window edge
145
+ * and every bulk operation, is tracked as before. The window must lie outside the arena of all
146
+ * slots and the owner frame region, which is what those checks would have found; a false conflict
147
+ * is possible only for a granule of the window that another iteration writes and this one does
148
+ * not read. The exempt window is tested first, so an exempt load executes what it does without
149
+ * windows; the guards of the windows run only for a load outside it. With `readCount` the lowering
150
+ * also counts those loads by where they land (`__folio_ch`, `__folio_cm`, `__folio_ce`).
151
+ *
152
+ * With `readSummary: n` every read mark also sets one byte of the summary at `__folio_rs`, before
153
+ * the bit it summarizes. The byte is `(a >> (log2(readGranule) + 11)) & (n - 1)` for address `a`,
154
+ * one byte per 64 words of the read bitmap. A bitmap word is never non-zero while its summary byte
155
+ * is zero, so a scan may skip the blocks whose byte is zero. The owner sets the bytes of any
156
+ * granule it marks itself, a read window for one, and clears a byte only when it clears the words
157
+ * of its block. An address past the memory wraps to a byte that covers other words, which only
158
+ * adds blocks to scan. The owner must also set `n` large enough that every address of the memory
159
+ * has its own byte, or the scan visits blocks it need not.
160
+ *
161
+ * With `window: true` (which implies `frame`, and `slot` when there is a stack global) the owner also sets `__folio_wl` and
162
+ * `__folio_we`, a window of the address space, and `__folio_wd`, the distance from it to a private
163
+ * copy that lies inside the tracked frame region. A load, store, atomic or SIMD access that lies in
164
+ * the window runs on the copy (`address + __folio_wd`), a bulk operation does the same when its
165
+ * whole range is inside, and an access or range that crosses the window edge traps with
166
+ * `unreachable`. Accesses in the tracked frame region, the copy included, set no bitmap mark and
167
+ * log no undo entry: their only record is the frame shadow, whose exposed bits the owner
168
+ * validates, and the copy is discarded or committed byte by byte from the written bits. With the
169
+ * window empty (`__folio_we` at 0) nothing is rebased.
170
+ *
171
+ * Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
172
+ * `requireShared` is set, a start function that calls, a reserved name or an expression it does
173
+ * not know. An imported host function that touches memory is not seen.
174
+ */
175
+ export declare function lowerInline(bytes: Uint8Array, options?: InlineOptions): Uint8Array;
176
+ /**
177
+ * The module a managed lane runs with inline tracking: `lowerInline` with fuel and the arena
178
+ * guard on, and the memory import widened to the largest maximum so a lane can place the marks
179
+ * and the undo log above the program memory. Build time only; the input is the control plan's
180
+ * `workerOriginal`.
181
+ */
182
+ export declare function inlineLane(workerOriginal: Uint8Array): Uint8Array;
@@ -1,12 +1,6 @@
1
1
  import binaryen from 'binaryen';
2
- import { stackRoute } from "./extract.js";
3
- const info = (expression) => {
4
- const id = binaryen.getExpressionId(expression);
5
- if (id === binaryen.UnreachableId || id === binaryen.NopId) {
6
- return { id, type: binaryen.getExpressionType(expression) };
7
- }
8
- return binaryen.getExpressionInfo(expression);
9
- };
2
+ import { info, stackRoute } from "../execution/extract.js";
3
+ import { importedMemory, shareMemory } from "./owner.js";
10
4
  // #region inline tracking lowering
11
5
  const capi = binaryen;
12
6
  /** Names of the exported mutable i32 globals the inline lowering adds, plus the stack export. */
@@ -19,11 +13,32 @@ export const inlineGlobals = {
19
13
  stackPointer: '__folio_sp',
20
14
  frameLow: '__folio_fl',
21
15
  frameSize: '__folio_fn',
22
- frameShadow: '__folio_fs'
16
+ frameShadow: '__folio_fs',
17
+ exemptLow: '__folio_xl',
18
+ exemptEnd: '__folio_xe',
19
+ slotLow: '__folio_sl',
20
+ slotEnd: '__folio_se',
21
+ arenaLow: '__folio_al',
22
+ arenaEnd: '__folio_ae',
23
+ violation: '__folio_xv',
24
+ windowLow: '__folio_wl',
25
+ windowEnd: '__folio_we',
26
+ windowDelta: '__folio_wd',
27
+ readWindow0Low: '__folio_r0l',
28
+ readWindow0Span: '__folio_r0m',
29
+ readWindow1Low: '__folio_r1l',
30
+ readWindow1Span: '__folio_r1m',
31
+ readSummary: '__folio_rs',
32
+ readHits: '__folio_ch',
33
+ readMisses: '__folio_cm',
34
+ readExempt: '__folio_ce'
23
35
  };
24
36
  /** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
25
37
  export const inlineEntryBytes = (writeGranule = 32) => 8 + writeGranule;
26
38
  const inlineHelpers = [
39
+ '__folio_x_trap',
40
+ '__folio_x_r_range',
41
+ '__folio_x_w_range',
27
42
  '__folio_r_mark',
28
43
  '__folio_w_mark',
29
44
  '__folio_w_set',
@@ -33,7 +48,8 @@ const inlineHelpers = [
33
48
  '__folio_f_r',
34
49
  '__folio_f_w',
35
50
  '__folio_f_rr',
36
- '__folio_f_rw'
51
+ '__folio_f_rw',
52
+ '__folio_w_rebase'
37
53
  ];
38
54
  const inlineLeaves = new Set([
39
55
  binaryen.ConstId,
@@ -195,6 +211,49 @@ function memoryCount(bytes, native) {
195
211
  * zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
196
212
  * the region is not tracked.
197
213
  *
214
+ * With `slot: true` and a stack global, the owner also sets three address windows before a region:
215
+ * the exempt window `[__folio_xl, __folio_xe)`, the whole private slot `[__folio_sl, __folio_se)`
216
+ * and the arena of all slots `[__folio_al, __folio_ae)`. An access inside the exempt window sets no
217
+ * mark and logs no undo entry. An access that overlaps the arena but does not lie inside the own
218
+ * slot stores its address in `__folio_xv` and traps with `unreachable`, because another iteration
219
+ * owns those bytes. Every other access is tracked as before, so the exempt window must not contain
220
+ * the tracked frame; an access that crosses the window edge is tracked. `memory.copy`,
221
+ * `memory.fill` and `memory.init` apply the same tests to the whole range, and a range counts as
222
+ * inside only when every byte is. The exempt bytes are not restored by a rollback, so the owner
223
+ * must treat the window as dead after the region.
224
+ *
225
+ * With `readWindows: n` the owner also sets, per window `i` below `n`, `__folio_r<i>l` (first byte)
226
+ * and `__folio_r<i>m` (window size minus 7, or 0 for no window) before a region, and marks every
227
+ * read granule that the window touches in the read bitmap itself. A plain, non-atomic load or SIMD
228
+ * load of at most 8 bytes whose address `a` satisfies `a - low < size - 7` lies wholly inside the
229
+ * window, so its read mark is already set: it sets no mark and skips the slot, arena and frame
230
+ * checks. Every other access, a store, an atomic, a wider load, a load that crosses a window edge
231
+ * and every bulk operation, is tracked as before. The window must lie outside the arena of all
232
+ * slots and the owner frame region, which is what those checks would have found; a false conflict
233
+ * is possible only for a granule of the window that another iteration writes and this one does
234
+ * not read. The exempt window is tested first, so an exempt load executes what it does without
235
+ * windows; the guards of the windows run only for a load outside it. With `readCount` the lowering
236
+ * also counts those loads by where they land (`__folio_ch`, `__folio_cm`, `__folio_ce`).
237
+ *
238
+ * With `readSummary: n` every read mark also sets one byte of the summary at `__folio_rs`, before
239
+ * the bit it summarizes. The byte is `(a >> (log2(readGranule) + 11)) & (n - 1)` for address `a`,
240
+ * one byte per 64 words of the read bitmap. A bitmap word is never non-zero while its summary byte
241
+ * is zero, so a scan may skip the blocks whose byte is zero. The owner sets the bytes of any
242
+ * granule it marks itself, a read window for one, and clears a byte only when it clears the words
243
+ * of its block. An address past the memory wraps to a byte that covers other words, which only
244
+ * adds blocks to scan. The owner must also set `n` large enough that every address of the memory
245
+ * has its own byte, or the scan visits blocks it need not.
246
+ *
247
+ * With `window: true` (which implies `frame`, and `slot` when there is a stack global) the owner also sets `__folio_wl` and
248
+ * `__folio_we`, a window of the address space, and `__folio_wd`, the distance from it to a private
249
+ * copy that lies inside the tracked frame region. A load, store, atomic or SIMD access that lies in
250
+ * the window runs on the copy (`address + __folio_wd`), a bulk operation does the same when its
251
+ * whole range is inside, and an access or range that crosses the window edge traps with
252
+ * `unreachable`. Accesses in the tracked frame region, the copy included, set no bitmap mark and
253
+ * log no undo entry: their only record is the frame shadow, whose exposed bits the owner
254
+ * validates, and the copy is discarded or committed byte by byte from the written bits. With the
255
+ * window empty (`__folio_we` at 0) nothing is rebased.
256
+ *
198
257
  * Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
199
258
  * `requireShared` is set, a start function that calls, a reserved name or an expression it does
200
259
  * not know. An imported host function that touches memory is not seen.
@@ -203,6 +262,12 @@ export function lowerInline(bytes, options = {}) {
203
262
  const rg = granuleShift(options.readGranule, 64, 16, 4096);
204
263
  const wg = granuleShift(options.writeGranule, 32, 16, 256);
205
264
  const entry = inlineEntryBytes(1 << wg);
265
+ const readWindows = options.readWindows ?? 0;
266
+ if (!Number.isInteger(readWindows) || readWindows < 0 || readWindows > 2)
267
+ throw new RangeError('read windows must be 0, 1 or 2');
268
+ const summary = options.readSummary ?? 0;
269
+ if (!Number.isInteger(summary) || summary < 0 || summary > 32768 || summary & (summary - 1))
270
+ throw new RangeError('read summary must be 0 or a power of two up to 32768');
206
271
  const original = Uint8Array.from(bytes);
207
272
  const native = new WebAssembly.Module(original);
208
273
  if (memoryCount(original, native) !== 1)
@@ -218,7 +283,12 @@ export function lowerInline(bytes, options = {}) {
218
283
  throw new Error('memory64 is not supported');
219
284
  if ((options.requireShared ?? true) && !memory.shared)
220
285
  throw new Error('shared memory required; pass requireShared: false for one thread');
221
- const reserved = [...Object.values(inlineGlobals), ...inlineHelpers];
286
+ const fuel = Boolean(options.fuel);
287
+ const reserved = [
288
+ ...Object.values(inlineGlobals),
289
+ ...inlineHelpers,
290
+ ...(fuel ? ['__folio_fuel', '__folio_exhausted', '__folio_set_fuel'] : [])
291
+ ];
222
292
  if (reserved.some((name) => m.getGlobal(name) || m.getFunction(name) || m.getExport(name)))
223
293
  throw new Error('reserved function name');
224
294
  if (stack !== undefined) {
@@ -227,7 +297,17 @@ export function lowerInline(bytes, options = {}) {
227
297
  if (!shape || !shape.mutable || shape.type !== binaryen.i32 || shape.module)
228
298
  throw new Error(`stack global ${stack} is not a defined mutable i32`);
229
299
  }
230
- const frame = Boolean(options.frame);
300
+ const window = Boolean(options.window);
301
+ const frame = Boolean(options.frame) || window;
302
+ const slot = ((Boolean(options.slot) || window) && stack !== undefined) || Boolean(options.guard);
303
+ const { exemptLow: xl, exemptEnd: xe, slotLow: sl, slotEnd: se } = inlineGlobals;
304
+ const { arenaLow: al, arenaEnd: ae, violation: xv } = inlineGlobals;
305
+ const { windowLow: wl, windowEnd: we, windowDelta: wd } = inlineGlobals;
306
+ const { readWindow0Low: r0l, readWindow0Span: r0m } = inlineGlobals;
307
+ const { readWindow1Low: r1l, readWindow1Span: r1m } = inlineGlobals;
308
+ const rs = inlineGlobals.readSummary;
309
+ const { readHits: ch, readMisses: cm, readExempt: ce } = inlineGlobals;
310
+ const counting = Boolean(options.readCount) && readWindows > 0;
231
311
  const rb = inlineGlobals.readBitmap, wb = inlineGlobals.writeBitmap, lp = inlineGlobals.logPointer, ll = inlineGlobals.logLimit, sa = inlineGlobals.stampAddress, fl = inlineGlobals.frameLow, fn = inlineGlobals.frameSize, fs = inlineGlobals.frameShadow;
232
312
  const i32 = binaryen.i32, none = binaryen.none;
233
313
  const c = (value) => m.i32.const(value | 0);
@@ -237,13 +317,32 @@ export function lowerInline(bytes, options = {}) {
237
317
  const bitOf = (address, shift) => m.i32.shl(c(1), m.i32.and(m.i32.shr_u(address(), c(shift)), c(7)));
238
318
  const byteOf = (base, address, shift) => m.i32.add(g(base), m.i32.shr_u(address(), c(shift + 3)));
239
319
  const setBit = (base, address, shift) => m.i32.store8(0, 1, byteOf(base, address, shift), m.i32.or(m.i32.load8_u(0, 1, byteOf(base, address, shift)), bitOf(address, shift)));
320
+ // the summary byte goes first, so the bit is never set without it
321
+ const markRead = (address) => summary
322
+ ? m.block(null, [
323
+ m.i32.store8(0, 1, m.i32.add(g(rs), m.i32.and(m.i32.shr_u(address(), c(rg + 11)), c(summary - 1))), c(1)),
324
+ setBit(rb, address, rg)
325
+ ], none)
326
+ : setBit(rb, address, rg);
240
327
  const unmarked = (address) => m.i32.eqz(m.i32.and(m.i32.load8_u(0, 1, byteOf(wb, address, wg)), bitOf(address, wg)));
241
328
  // does an access of `width` bytes at the address overlap the frame region
242
329
  const inFrame = (address, width) => width === 1
243
330
  ? m.i32.lt_u(m.i32.sub(address(), g(fl)), g(fn))
244
331
  : m.i32.lt_u(m.i32.add(m.i32.sub(address(), g(fl)), c(width - 1)), m.i32.add(g(fn), c(width - 1)));
245
332
  const frameCall = (name, address, width) => m.if(inFrame(address, width), call(name, address(), c(width)));
333
+ // does [address, address + width) lie inside the window named by two globals
334
+ const within = (low, end, address, width) => m.i32.and(m.i32.ge_u(address(), g(low)), m.i32.le_u(m.i32.add(address(), width), g(end)));
335
+ // does [address, address + width) overlap the arena of all slots
336
+ const overlapsArena = (address, width) => m.i32.and(m.i32.lt_u(address(), g(ae)), m.i32.gt_u(m.i32.add(address(), width), g(al)));
337
+ // does [address, address + width) lie inside the tracked frame region
338
+ const inRegion = (address, width) => m.i32.and(m.i32.ge_u(address(), g(fl)), m.i32.le_u(m.i32.add(address(), typeof width === 'number' ? c(width) : width()), m.i32.add(g(fl), g(fn))));
246
339
  const hold = (local, value) => m.block(null, [m.local.set(local, value), l(local)], i32);
340
+ const tick = () => m.block(null, [
341
+ m.global.set('__folio_fuel', m.i32.sub(g('__folio_fuel'), c(1))),
342
+ m.if(m.i32.le_s(g('__folio_fuel'), c(0)), m.call('__folio_exhausted', [], none))
343
+ ], none);
344
+ const stop = Boolean(options.stop);
345
+ const poll = () => m.if(m.i32.atomic.load(4, g(sa)), m.unreachable());
247
346
  const startRef = m.getStart();
248
347
  const start = startRef ? binaryen.getFunctionInfo(startRef).name : undefined;
249
348
  const callsOut = (expression) => {
@@ -288,19 +387,60 @@ export function lowerInline(bytes, options = {}) {
288
387
  m.local.set(t, ptr),
289
388
  m.local.set(u, offset ? m.i32.add(l(t), c(offset)) : l(t))
290
389
  ];
390
+ const tracked = [];
291
391
  const crosses = (shift, mark) => m.if(m.i32.gt_u(m.i32.and(l(u), c((1 << shift) - 1)), c((1 << shift) - width)), call(mark, m.i32.add(l(u), c(width - 1))));
292
392
  if (read) {
293
- steps.push(setBit(rb, () => l(u), rg));
393
+ tracked.push(markRead(() => l(u)));
294
394
  if (width > 1)
295
- steps.push(crosses(rg, '__folio_r_mark'));
395
+ tracked.push(crosses(rg, '__folio_r_mark'));
296
396
  }
297
397
  if (write) {
298
- steps.push(m.if(unmarked(() => l(u)), call('__folio_w_set', l(u))));
398
+ tracked.push(m.if(unmarked(() => l(u)), call('__folio_w_set', l(u))));
299
399
  if (width > 1)
300
- steps.push(crosses(wg, '__folio_w_mark'));
400
+ tracked.push(crosses(wg, '__folio_w_mark'));
301
401
  }
402
+ const marks = tracked.splice(0);
403
+ if (window)
404
+ tracked.push(m.if(m.i32.eqz(inRegion(() => l(u), width)), m.block(null, marks, none)));
405
+ else
406
+ tracked.push(...marks);
302
407
  if (frame && checks)
303
- steps.push(frameCall('__folio_f_r', () => l(u), width));
408
+ tracked.push(frameCall('__folio_f_r', () => l(u), width));
409
+ if (window)
410
+ steps.push(m.if(m.i32.and(m.i32.lt_u(l(u), g(we)), m.i32.gt_u(m.i32.add(l(u), c(width)), g(wl))), m.if(within(wl, we, () => l(u), c(width)), m.block(null, [
411
+ m.local.set(t, m.i32.add(l(t), g(wd))),
412
+ m.local.set(u, m.i32.add(l(u), g(wd)))
413
+ ], none), m.unreachable())));
414
+ const windowed = readWindows > 0 && read && !write && width <= 8;
415
+ const bump = (name) => m.global.set(name, m.i32.add(g(name), c(1)));
416
+ // a load that misses every window is tracked, and counted as a miss when counting
417
+ const miss = (inner) => m.block(null, counting ? [bump(cm), ...inner] : inner, none);
418
+ // a hit inside a window the owner marked in full skips every other step
419
+ const chained = (tail) => {
420
+ let chain = tail;
421
+ for (let w = readWindows - 1; w >= 0; w--) {
422
+ const [low, span] = w === 0 ? [r0l, r0m] : [r1l, r1m];
423
+ chain = m.if(m.i32.lt_u(m.i32.sub(l(u), g(low)), g(span)), counting ? bump(ch) : m.nop(), chain);
424
+ }
425
+ return chain;
426
+ };
427
+ if (slot) {
428
+ const inner = [
429
+ m.if(overlapsArena(() => l(u), c(width)), m.if(m.i32.eqz(within(sl, se, () => l(u), c(width))), call('__folio_x_trap', l(u)))),
430
+ ...tracked
431
+ ];
432
+ const exempt = (tail) => m.if(within(xl, xe, () => l(u), c(width)), windowed && counting ? bump(ce) : m.nop(), tail);
433
+ // the exempt window first, or the windows first: a hit then skips the exempt check
434
+ // and an exempt load pays the guards
435
+ if (!windowed)
436
+ steps.push(exempt(m.block(null, inner, none)));
437
+ else if (options.exemptFirst)
438
+ steps.push(exempt(chained(miss(inner))));
439
+ else
440
+ steps.push(chained(exempt(miss(inner))));
441
+ }
442
+ else
443
+ steps.push(...(windowed ? [chained(miss(tracked))] : tracked));
304
444
  if (saved !== undefined)
305
445
  steps.push(m.local.set(saved, l(u)));
306
446
  steps.push(l(t));
@@ -310,7 +450,43 @@ export function lowerInline(bytes, options = {}) {
310
450
  const v = info(e);
311
451
  for (const child of inlineChildren(v))
312
452
  visit(child);
453
+ if (window &&
454
+ (v.id === binaryen.MemoryCopyId ||
455
+ v.id === binaryen.MemoryFillId ||
456
+ v.id === binaryen.MemoryInitId)) {
457
+ // the destination operand evaluates all three, rebases the ranges and marks them;
458
+ // the other operands then read the locals back
459
+ const [td, tm, tn] = vars(3);
460
+ const copy = v.id === binaryen.MemoryCopyId;
461
+ const kind = copy ? 'Copy' : v.id === binaryen.MemoryFillId ? 'Fill' : 'Init';
462
+ const middle = copy ? v.source : kind === 'Fill' ? v.value : v.offset;
463
+ const rebase = (local) => m.local.set(local, m.call('__folio_w_rebase', [l(local), l(tn)], i32));
464
+ const api = capi;
465
+ api[`_BinaryenMemory${kind}SetDest`](e, m.block(null, [
466
+ m.local.set(td, v.dest),
467
+ m.local.set(tm, middle),
468
+ m.local.set(tn, v.size),
469
+ rebase(td),
470
+ ...(copy
471
+ ? [
472
+ rebase(tm),
473
+ call('__folio_x_r_range', l(tm), l(tn)),
474
+ call('__folio_f_rr', l(tm), l(tn))
475
+ ]
476
+ : []),
477
+ call('__folio_x_w_range', l(td), l(tn)),
478
+ call('__folio_f_rw', l(td), l(tn)),
479
+ l(td)
480
+ ], i32));
481
+ api[`_BinaryenMemory${kind}Set${copy ? 'Source' : kind === 'Fill' ? 'Value' : 'Offset'}`](e, l(tm));
482
+ api[`_BinaryenMemory${kind}SetSize`](e, l(tn));
483
+ return;
484
+ }
313
485
  switch (v.id) {
486
+ case binaryen.LoopId:
487
+ if (fuel || stop)
488
+ capi._BinaryenLoopSetBody(e, m.block(null, [...(fuel ? [tick()] : []), ...(stop ? [poll()] : []), v.body], binaryen.getExpressionType(v.body)));
489
+ break;
314
490
  case binaryen.LoadId:
315
491
  capi._BinaryenLoadSetPtr(e, access(v.ptr, v.offset, v.bytes, true, Boolean(v.isAtomic), true));
316
492
  break;
@@ -358,8 +534,8 @@ export function lowerInline(bytes, options = {}) {
358
534
  capi._BinaryenMemoryCopySetSource(e, hold(ts, v.source));
359
535
  capi._BinaryenMemoryCopySetSize(e, m.block(null, [
360
536
  m.local.set(tn, v.size),
361
- call('__folio_r_range', l(ts), l(tn)),
362
- call('__folio_w_range', l(td), l(tn)),
537
+ call(slot ? '__folio_x_r_range' : '__folio_r_range', l(ts), l(tn)),
538
+ call(slot ? '__folio_x_w_range' : '__folio_w_range', l(td), l(tn)),
363
539
  ...(frame
364
540
  ? [
365
541
  call('__folio_f_rr', l(ts), l(tn)),
@@ -377,7 +553,7 @@ export function lowerInline(bytes, options = {}) {
377
553
  capi[fill ? '_BinaryenMemoryFillSetDest' : '_BinaryenMemoryInitSetDest'](e, hold(td, v.dest));
378
554
  capi[fill ? '_BinaryenMemoryFillSetSize' : '_BinaryenMemoryInitSetSize'](e, m.block(null, [
379
555
  m.local.set(tn, v.size),
380
- call('__folio_w_range', l(td), l(tn)),
556
+ call(slot ? '__folio_x_w_range' : '__folio_w_range', l(td), l(tn)),
381
557
  ...(frame ? [call('__folio_f_rw', l(td), l(tn))] : []),
382
558
  l(tn)
383
559
  ], i32));
@@ -386,6 +562,14 @@ export function lowerInline(bytes, options = {}) {
386
562
  }
387
563
  };
388
564
  visit(body);
565
+ if (fuel)
566
+ capi._BinaryenFunctionSetBody(f, m.block(null, [tick(), body], binaryen.getExpressionType(body)));
567
+ }
568
+ if (fuel) {
569
+ m.addGlobal('__folio_fuel', i32, true, c(0));
570
+ m.addFunctionImport('__folio_exhausted', 'folio', 'exhausted', none, none);
571
+ m.addFunction('__folio_set_fuel', i32, none, [], m.global.set('__folio_fuel', l(0)));
572
+ m.addFunctionExport('__folio_set_fuel', '__folio_set_fuel');
389
573
  }
390
574
  for (const name of [rb, wb, lp, ll, sa]) {
391
575
  m.addGlobal(name, i32, true, c(0));
@@ -396,6 +580,34 @@ export function lowerInline(bytes, options = {}) {
396
580
  m.addGlobal(name, i32, true, c(0));
397
581
  m.addGlobalExport(name, name);
398
582
  }
583
+ if (slot || window)
584
+ for (const name of [xl, xe, sl, se, al, ae, xv]) {
585
+ m.addGlobal(name, i32, true, c(0));
586
+ m.addGlobalExport(name, name);
587
+ }
588
+ if (window)
589
+ for (const name of [wl, we, wd]) {
590
+ m.addGlobal(name, i32, true, c(0));
591
+ m.addGlobalExport(name, name);
592
+ }
593
+ for (const [index, pair] of [
594
+ [r0l, r0m],
595
+ [r1l, r1m]
596
+ ].entries())
597
+ if (index < readWindows)
598
+ for (const name of pair) {
599
+ m.addGlobal(name, i32, true, c(0));
600
+ m.addGlobalExport(name, name);
601
+ }
602
+ if (summary) {
603
+ m.addGlobal(rs, i32, true, c(0));
604
+ m.addGlobalExport(rs, rs);
605
+ }
606
+ if (counting)
607
+ for (const name of [ch, cm, ce]) {
608
+ m.addGlobal(name, i32, true, c(0));
609
+ m.addGlobalExport(name, name);
610
+ }
399
611
  if (stack !== undefined)
400
612
  m.addGlobalExport(stack, inlineGlobals.stackPointer);
401
613
  const pair = binaryen.createType([i32, i32]);
@@ -467,7 +679,7 @@ export function lowerInline(bytes, options = {}) {
467
679
  bulk('__folio_f_rr', true);
468
680
  bulk('__folio_f_rw', false);
469
681
  };
470
- m.addFunction('__folio_r_mark', i32, none, [], setBit(rb, () => l(0), rg));
682
+ m.addFunction('__folio_r_mark', i32, none, [], markRead(() => l(0)));
471
683
  m.addFunction('__folio_undo', i32, none, [i32], m.block(null, [
472
684
  m.if(m.i32.gt_u(m.i32.add(g(lp), c(entry)), g(ll)), m.unreachable()),
473
685
  m.local.set(1, g(lp)),
@@ -492,6 +704,35 @@ export function lowerInline(bytes, options = {}) {
492
704
  range('__folio_w_range', wg, '__folio_w_mark');
493
705
  if (frame)
494
706
  addFrameHelpers();
707
+ if (slot || window) {
708
+ m.addFunction('__folio_x_trap', i32, none, [], m.block(null, [m.global.set(xv, l(0)), m.unreachable()], none));
709
+ // params a, n; the range is tracked unless it lies in the exempt window
710
+ const exempt = (name, tracked) => m.addFunction(name, pair, none, [i32], m.if(l(1), m.block(null, [
711
+ m.local.set(2, m.i32.add(l(0), l(1))),
712
+ m.if(m.i32.eqz(m.i32.and(m.i32.ge_u(l(0), g(xl)), m.i32.le_u(l(2), g(xe)))), m.block(null, [
713
+ m.if(m.i32.and(m.i32.lt_u(l(0), g(ae)), m.i32.gt_u(l(2), g(al))), m.if(m.i32.eqz(m.i32.and(m.i32.ge_u(l(0), g(sl)), m.i32.le_u(l(2), g(se)))), call('__folio_x_trap', l(0)))),
714
+ window
715
+ ? m.if(m.i32.eqz(inRegion(() => l(0), () => l(1))), call(tracked, l(0), l(1)))
716
+ : call(tracked, l(0), l(1))
717
+ ], none))
718
+ ], none)));
719
+ exempt('__folio_x_r_range', '__folio_r_range');
720
+ exempt('__folio_x_w_range', '__folio_w_range');
721
+ }
722
+ if (window) {
723
+ // params a, n, result the address a bulk range runs at: inside the window it moves to the
724
+ // copy, across its edge it traps
725
+ m.addFunction('__folio_w_rebase', pair, i32, [i32], m.block(null, [
726
+ m.if(m.i32.eqz(l(1)), m.return(l(0))),
727
+ m.local.set(2, m.i32.add(l(0), l(1))),
728
+ m.if(m.i32.lt_u(l(2), l(0)), m.return(l(0))),
729
+ m.if(m.i32.and(m.i32.lt_u(l(0), g(we)), m.i32.gt_u(l(2), g(wl))), m.block(null, [
730
+ m.if(m.i32.and(m.i32.ge_u(l(0), g(wl)), m.i32.le_u(l(2), g(we))), m.return(m.i32.add(l(0), g(wd)))),
731
+ m.unreachable()
732
+ ], none)),
733
+ l(0)
734
+ ], i32));
735
+ }
495
736
  if (!m.validate())
496
737
  throw new Error('invalid inline lowering');
497
738
  return m.emitBinary();
@@ -501,3 +742,18 @@ export function lowerInline(bytes, options = {}) {
501
742
  }
502
743
  }
503
744
  // #endregion
745
+ // #region lane module
746
+ /**
747
+ * The module a managed lane runs with inline tracking: `lowerInline` with fuel and the arena
748
+ * guard on, and the memory import widened to the largest maximum so a lane can place the marks
749
+ * and the undo log above the program memory. Build time only; the input is the control plan's
750
+ * `workerOriginal`.
751
+ */
752
+ export function inlineLane(workerOriginal) {
753
+ const lowered = lowerInline(workerOriginal, { fuel: true, guard: true });
754
+ const memories = importedMemory(lowered);
755
+ if (memories.length !== 1)
756
+ throw new Error('exactly one imported memory required');
757
+ return shareMemory(lowered, memories[0]);
758
+ }
759
+ // #endregion
@@ -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';
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;
@@ -18,6 +18,19 @@ export interface IterationOwner {
18
18
  maximum?: number;
19
19
  };
20
20
  }
21
+ /** Reads the one imported memory's limits from the import section. */
22
+ export declare function importedMemory(bytes: Uint8Array): {
23
+ module: string;
24
+ name: string;
25
+ flags: number;
26
+ initial: number;
27
+ maximum?: number;
28
+ limits: [number, number];
29
+ header: number;
30
+ body: [number, number];
31
+ }[];
32
+ /** Rewrites the memory import limits to shared with the largest maximum. */
33
+ export declare function shareMemory(bytes: Uint8Array, memory: ReturnType<typeof importedMemory>[number]): Uint8Array<ArrayBuffer>;
21
34
  /**
22
35
  * Builds the owner module of an iteration route: the memory import is shared, and the one loop
23
36
  * of the owner function becomes `if (iterate(entry locals...)) { final values } else { the loop }`.