@gmitch215/folio 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +398 -28
  2. package/dist/affine-state.d.ts +171 -0
  3. package/dist/affine-state.js +763 -0
  4. package/dist/affine.d.ts +160 -0
  5. package/dist/affine.js +571 -0
  6. package/dist/boundaries.d.ts +59 -0
  7. package/dist/boundaries.js +127 -0
  8. package/dist/certified.d.ts +66 -0
  9. package/dist/certified.js +192 -0
  10. package/dist/certify.d.ts +98 -0
  11. package/dist/certify.js +2628 -0
  12. package/dist/context.d.ts +16 -2
  13. package/dist/context.js +60 -14
  14. package/dist/coordinator.js +50 -3
  15. package/dist/extract.d.ts +19 -0
  16. package/dist/extract.js +133 -5
  17. package/dist/fold.d.ts +32 -0
  18. package/dist/fold.js +105 -0
  19. package/dist/frames.d.ts +5 -1
  20. package/dist/frames.js +156 -9
  21. package/dist/inline.d.ts +114 -0
  22. package/dist/inline.js +276 -13
  23. package/dist/iteration-admission.d.ts +116 -7
  24. package/dist/iteration-admission.js +137 -8
  25. package/dist/iteration-layout.d.ts +60 -0
  26. package/dist/iteration-layout.js +54 -3
  27. package/dist/iteration-owner.d.ts +14 -1
  28. package/dist/iteration-owner.js +2 -2
  29. package/dist/iteration-worker.js +124 -58
  30. package/dist/iteration.d.ts +179 -13
  31. package/dist/iteration.js +845 -70
  32. package/dist/lease.d.ts +45 -0
  33. package/dist/lease.js +274 -0
  34. package/dist/managed.d.ts +72 -0
  35. package/dist/managed.js +425 -27
  36. package/dist/memo.d.ts +99 -0
  37. package/dist/memo.js +250 -0
  38. package/dist/node.d.ts +43 -1
  39. package/dist/node.js +87 -11
  40. package/dist/ownership-redirect.d.ts +30 -0
  41. package/dist/ownership-redirect.js +179 -0
  42. package/dist/ownership-slices.d.ts +44 -0
  43. package/dist/ownership-slices.js +72 -0
  44. package/dist/ownership.d.ts +161 -0
  45. package/dist/ownership.js +6568 -0
  46. package/dist/ranges.d.ts +78 -0
  47. package/dist/ranges.js +263 -0
  48. package/dist/read-scan.d.ts +18 -0
  49. package/dist/read-scan.js +94 -0
  50. package/dist/read-windows.d.ts +103 -0
  51. package/dist/read-windows.js +244 -0
  52. package/dist/router-worker.d.ts +1 -0
  53. package/dist/router-worker.js +4 -0
  54. package/dist/router.d.ts +203 -0
  55. package/dist/router.js +667 -0
  56. package/dist/runs.d.ts +44 -0
  57. package/dist/runs.js +182 -0
  58. package/dist/slices-worker.d.ts +1 -0
  59. package/dist/slices-worker.js +38 -0
  60. package/dist/slices.d.ts +126 -0
  61. package/dist/slices.js +441 -0
  62. package/dist/tasks.d.ts +14 -4
  63. package/dist/tasks.js +12 -11
  64. package/dist/transaction.d.ts +10 -0
  65. package/package.json +40 -4
package/dist/frames.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { decodeValue, encodeValue } from "./remote.js";
2
+ import { checkRuns, runBytes, runsOfSorted, writeRunsOf } from "./runs.js";
2
3
  const magic = 0x314f4c46;
3
4
  const encoder = new TextEncoder();
4
5
  const decoder = new TextDecoder('utf-8', { fatal: true });
@@ -90,13 +91,76 @@ export function validateIdentity(value) {
90
91
  value.sequence < 0)
91
92
  throw new TypeError('invalid frame identity');
92
93
  }
93
- export function encodeResults(identity, results, maximum = 0x100100000) {
94
- const length = results.reduce((sum, result) => sum + result.reads.length * 4 + result.writes.length * 8, 0);
94
+ /** Version of the run encoding of a results frame, named in the request and the response. */
95
+ export const runsVersion = 1;
96
+ /**
97
+ * Run encoding of a results frame, `runs` of the request: per result the read runs and the write
98
+ * runs as start, length pairs, then the written bytes back to back, then the escapes. Results
99
+ * that carry addresses are converted, so a lane may mix paths.
100
+ */
101
+ function encodeRunResults(identity, results, maximum) {
102
+ const parts = results.map((result) => {
103
+ const readRuns = result.readRuns ?? runsOfSorted(Uint32Array.from(result.reads).sort());
104
+ const packed = result.writeRuns
105
+ ? { runs: result.writeRuns, data: result.writeData ?? new Uint8Array() }
106
+ : writeRunsOf(result.writes);
107
+ if (packed.data.length !== runBytes(packed.runs))
108
+ throw new RangeError('write runs and write data differ');
109
+ return { result, readRuns, packed };
110
+ });
111
+ const length = parts.reduce((sum, { result, readRuns, packed }) => sum +
112
+ readRuns.length * 4 +
113
+ packed.runs.length * 4 +
114
+ packed.data.length +
115
+ (result.escapes?.length ?? 0) * 8, 0);
95
116
  if (length > 0xffffffff || length + 12 > maximum)
96
117
  throw new RangeError('result payload exceeds limit');
97
118
  const payload = new Uint8Array(length), view = new DataView(payload.buffer);
98
119
  let offset = 0;
99
- const descriptors = results.map(({ reads, writes, ...result }) => {
120
+ const put = (runs) => {
121
+ for (let i = 0; i < runs.length; i++, offset += 4)
122
+ view.setUint32(offset, runs[i], true);
123
+ };
124
+ const descriptors = parts.map(({ result, readRuns, packed }) => {
125
+ const { reads, writes, readRuns: _r, writeRuns: _w, writeData: _d, escapes, ...rest } = result;
126
+ put(readRuns);
127
+ put(packed.runs);
128
+ payload.set(packed.data, offset);
129
+ offset += packed.data.length;
130
+ for (const [start, size] of escapes ?? []) {
131
+ view.setUint32(offset, start, true);
132
+ view.setUint32(offset + 4, size, true);
133
+ offset += 8;
134
+ }
135
+ return {
136
+ ...rest,
137
+ reads: readRuns.length / 2,
138
+ writes: packed.runs.length / 2,
139
+ readBytes: runBytes(readRuns),
140
+ writeBytes: packed.data.length,
141
+ ...(escapes?.length ? { escapes: escapes.length } : {})
142
+ };
143
+ });
144
+ return encodeFrame({
145
+ session: identity.session,
146
+ epoch: identity.epoch,
147
+ sequence: identity.sequence,
148
+ runs: runsVersion,
149
+ results: descriptors
150
+ }, payload, maximum);
151
+ }
152
+ export function encodeResults(identity, results, maximum = 0x100100000, runs = false) {
153
+ if (runs)
154
+ return encodeRunResults(identity, results, maximum);
155
+ const length = results.reduce((sum, result) => sum +
156
+ result.reads.length * 4 +
157
+ result.writes.length * 8 +
158
+ (result.escapes?.length ?? 0) * 8, 0);
159
+ if (length > 0xffffffff || length + 12 > maximum)
160
+ throw new RangeError('result payload exceeds limit');
161
+ const payload = new Uint8Array(length), view = new DataView(payload.buffer);
162
+ let offset = 0;
163
+ const descriptors = results.map(({ reads, writes, escapes, ...result }) => {
100
164
  for (const address of reads) {
101
165
  view.setUint32(offset, address, true);
102
166
  offset += 4;
@@ -106,7 +170,17 @@ export function encodeResults(identity, results, maximum = 0x100100000) {
106
170
  view.setUint32(offset + 4, value, true);
107
171
  offset += 8;
108
172
  }
109
- return { ...result, reads: reads.length, writes: writes.length };
173
+ for (const [start, size] of escapes ?? []) {
174
+ view.setUint32(offset, start, true);
175
+ view.setUint32(offset + 4, size, true);
176
+ offset += 8;
177
+ }
178
+ return {
179
+ ...result,
180
+ reads: reads.length,
181
+ writes: writes.length,
182
+ ...(escapes?.length ? { escapes: escapes.length } : {})
183
+ };
110
184
  });
111
185
  return encodeFrame({
112
186
  session: identity.session,
@@ -124,17 +198,27 @@ export function decodeResults(bytes, identity, options) {
124
198
  throw new TypeError('stale lane response');
125
199
  if (!Array.isArray(header.results) || header.results.length !== options.calls)
126
200
  throw new TypeError('invalid lane result count');
201
+ if (header.runs !== undefined) {
202
+ if (header.runs !== runsVersion)
203
+ throw new TypeError('unsupported results encoding');
204
+ if (!options.runs)
205
+ throw new TypeError('unrequested run encoding');
206
+ return decodeRunResults(header.results, payload, options);
207
+ }
127
208
  let offset = 0, retained = 0;
128
209
  const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
129
- const results = header.results.map(({ reads, writes, ...result }) => {
130
- if (![reads, writes].every((n) => Number.isSafeInteger(n) && n >= 0))
210
+ const results = header.results.map(({ reads, writes, escapes = 0, ...result }) => {
211
+ if (![reads, writes, escapes].every((n) => Number.isSafeInteger(n) && n >= 0) ||
212
+ escapes > reads)
131
213
  throw new TypeError('invalid lane tracking counts');
132
214
  retained += reads + writes;
133
- if (retained > options.maxBytes + 8 || offset + reads * 4 + writes * 8 > payload.length)
215
+ if (retained > options.maxBytes + 8 ||
216
+ offset + reads * 4 + writes * 8 + escapes * 8 > payload.length)
134
217
  throw new RangeError('lane tracking exceeds limit');
135
218
  if ((result.trap !== undefined && typeof result.trap !== 'string') ||
136
219
  (result.errorKind !== undefined && typeof result.errorKind !== 'string') ||
137
- (result.exhausted !== undefined && typeof result.exhausted !== 'boolean'))
220
+ (result.exhausted !== undefined && typeof result.exhausted !== 'boolean') ||
221
+ (result.inconclusive !== undefined && typeof result.inconclusive !== 'boolean'))
138
222
  throw new TypeError('invalid lane trap');
139
223
  const readSet = [], writeSet = [];
140
224
  for (let i = 0; i < reads; i++) {
@@ -151,7 +235,70 @@ export function decodeResults(bytes, identity, options) {
151
235
  throw new RangeError('lane write outside arena');
152
236
  writeSet.push([address, value]);
153
237
  }
154
- return { ...result, reads: readSet, writes: writeSet };
238
+ const escapeSet = [];
239
+ for (let i = 0; i < escapes; i++) {
240
+ const start = view.getUint32(offset, true), size = view.getUint32(offset + 4, true);
241
+ offset += 8;
242
+ if (size < 1 || start + size > options.memoryBytes)
243
+ throw new RangeError('lane escape outside arena');
244
+ escapeSet.push([start, size]);
245
+ }
246
+ return {
247
+ ...result,
248
+ reads: readSet,
249
+ writes: writeSet,
250
+ ...(escapes ? { escapes: escapeSet } : {})
251
+ };
252
+ });
253
+ if (offset !== payload.length)
254
+ throw new TypeError('unconsumed lane payload');
255
+ return results;
256
+ }
257
+ function decodeRunResults(descriptors, payload, options) {
258
+ let offset = 0, retained = 0;
259
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
260
+ const take = (count) => {
261
+ const out = new Uint32Array(count * 2);
262
+ for (let i = 0; i < out.length; i++, offset += 4)
263
+ out[i] = view.getUint32(offset, true);
264
+ return out;
265
+ };
266
+ const results = descriptors.map(({ reads, writes, readBytes, writeBytes, escapes = 0, ...result }) => {
267
+ if (![reads, writes, readBytes, writeBytes, escapes].every((n) => Number.isSafeInteger(n) && n >= 0))
268
+ throw new TypeError('invalid lane tracking counts');
269
+ retained += readBytes + writeBytes;
270
+ if (retained > options.maxBytes + 8 ||
271
+ offset + reads * 8 + writes * 8 + writeBytes + escapes * 8 > payload.length)
272
+ throw new RangeError('lane tracking exceeds limit');
273
+ if ((result.trap !== undefined && typeof result.trap !== 'string') ||
274
+ (result.errorKind !== undefined && typeof result.errorKind !== 'string') ||
275
+ (result.exhausted !== undefined && typeof result.exhausted !== 'boolean') ||
276
+ (result.inconclusive !== undefined && typeof result.inconclusive !== 'boolean'))
277
+ throw new TypeError('invalid lane trap');
278
+ const readRuns = take(reads), writeRuns = take(writes);
279
+ checkRuns(readRuns, options.memoryBytes, 'read');
280
+ checkRuns(writeRuns, options.memoryBytes, 'write');
281
+ if (runBytes(readRuns) !== readBytes || runBytes(writeRuns) !== writeBytes)
282
+ throw new TypeError('invalid lane tracking counts');
283
+ const writeData = payload.slice(offset, offset + writeBytes);
284
+ offset += writeBytes;
285
+ const escapeSet = [];
286
+ for (let i = 0; i < escapes; i++) {
287
+ const start = view.getUint32(offset, true), size = view.getUint32(offset + 4, true);
288
+ offset += 8;
289
+ if (size < 1 || start + size > options.memoryBytes)
290
+ throw new RangeError('lane escape outside arena');
291
+ escapeSet.push([start, size]);
292
+ }
293
+ return {
294
+ ...result,
295
+ reads: [],
296
+ writes: [],
297
+ readRuns,
298
+ writeRuns,
299
+ writeData,
300
+ ...(escapes ? { escapes: escapeSet } : {})
301
+ };
155
302
  });
156
303
  if (offset !== payload.length)
157
304
  throw new TypeError('unconsumed lane payload');
package/dist/inline.d.ts CHANGED
@@ -9,6 +9,24 @@ export declare const inlineGlobals: {
9
9
  readonly frameLow: "__folio_fl";
10
10
  readonly frameSize: "__folio_fn";
11
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";
12
30
  };
13
31
  /** Bytes of one undo entry: the granule address, the stamp, then the prior bytes of the granule. */
14
32
  export declare const inlineEntryBytes: (writeGranule?: number) => number;
@@ -24,6 +42,52 @@ export interface InlineOptions {
24
42
  stack?: string;
25
43
  /** Track exposed reads of one frame region (see `lowerInline`). Default off. */
26
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;
27
91
  }
28
92
  /**
29
93
  * A second lowering, next to the host-call one in `prepare`: it marks memory accesses inline, with
@@ -61,8 +125,58 @@ export interface InlineOptions {
61
125
  * zeroes the shadow before each region. Accesses outside the region pay one compare. Stack below
62
126
  * the region is not tracked.
63
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
+ *
64
171
  * Throws for a module without exactly one memory, a 64-bit memory, an unshared memory when
65
172
  * `requireShared` is set, a start function that calls, a reserved name or an expression it does
66
173
  * not know. An imported host function that touches memory is not seen.
67
174
  */
68
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;