@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
@@ -2,7 +2,7 @@ import binaryen from 'binaryen';
2
2
  import { restoreImportOrder } from "./import-order.js";
3
3
  /** Calibrated on Apple M2 Pro; see `results/execution/admission/admission-calibration.summary.json`. */
4
4
  export const DEFAULT_MINIMUM_REGION_WORK = 200_000;
5
- export const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
5
+ const DEFAULT_ASSUMED_TRIP_COUNT = 1000;
6
6
  // a tracked load or store costs about this many plain instructions in a speculative lane
7
7
  const ACCESS_COST = 3600;
8
8
  const CALL_COST = 2;
@@ -61,7 +61,7 @@ const pureNodes = new Set([
61
61
  ]);
62
62
  const raw = binaryen;
63
63
  const numeric = new Set([binaryen.i32, binaryen.i64, binaryen.f32, binaryen.f64]);
64
- function info(expression) {
64
+ export function info(expression) {
65
65
  const id = binaryen.getExpressionId(expression);
66
66
  if (id === binaryen.NopId || id === binaryen.UnreachableId)
67
67
  return { id, type: binaryen.getExpressionType(expression) };
@@ -220,7 +220,7 @@ function countdownLocal(loop) {
220
220
  * Trip-weighted instruction and tracked-access counts of one body, calls included. A loop bounded
221
221
  * by an untouched input makes a term in that local; other unknown bounds use `assumedTrips`.
222
222
  */
223
- export function estimateTerms(body, callee, assumedTrips, inputs) {
223
+ function estimateTerms(body, callee, assumedTrips, inputs) {
224
224
  const terms = new Map();
225
225
  const add = (factor, params, compute, accesses) => {
226
226
  const key = params.join(',');
@@ -304,7 +304,7 @@ function mergeTerms(lists) {
304
304
  return [...merged.values()];
305
305
  }
306
306
  /** Numeric work with every parameter-bounded loop assumed to run `assumedTrips` times. */
307
- export function settleWork(terms, assumedTrips) {
307
+ function settleWork(terms, assumedTrips) {
308
308
  const total = { compute: 0, accesses: 0 };
309
309
  for (const term of terms) {
310
310
  const factor = Math.min(assumedTrips ** term.params.length, SCALE_LIMIT);
@@ -987,7 +987,7 @@ export function extract(original, prepareTracked, options = {}) {
987
987
  const types = operands.map((e) => info(e).type);
988
988
  if (types.some((type) => !numeric.has(type)))
989
989
  throw new Error('non-scalar helper operand');
990
- // One memory is admitted. Retain every opcode attribute; only operands become parameters.
990
+ // one memory is admitted; keep every opcode attribute and turn only operands into parameters
991
991
  const memoryKey = v.id === binaryen.LoadId || v.id === binaryen.StoreId
992
992
  ? JSON.stringify([
993
993
  types,
@@ -1200,6 +1200,63 @@ export function extract(original, prepareTracked, options = {}) {
1200
1200
  module?.dispose();
1201
1201
  }
1202
1202
  }
1203
+ // a table is shared by every worker only when nothing can change it: no instruction writes it
1204
+ // and every segment is a constant-offset list; `written` scans the module text, so call it last
1205
+ function tableShapes(m) {
1206
+ const shapes = new Map();
1207
+ let text;
1208
+ const written = () => (text ??= /\btable\.(set|grow|fill|copy|init)\b/.test(m.emitText()));
1209
+ const count = m.getNumTables();
1210
+ if (!count)
1211
+ return { shapes, written };
1212
+ const exported = new Set();
1213
+ for (let i = 0; i < m.getNumExports(); i++) {
1214
+ const e = binaryen.getExportInfo(m.getExportByIndex(i));
1215
+ if (e.kind === binaryen.ExternalTable)
1216
+ exported.add(e.value);
1217
+ }
1218
+ for (let i = 0; i < count; i++) {
1219
+ const t = binaryen.getTableInfo(m.getTableByIndex(i));
1220
+ shapes.set(t.name, {
1221
+ refusal: t.module
1222
+ ? 'imported table'
1223
+ : exported.has(t.name)
1224
+ ? 'exported table'
1225
+ : undefined,
1226
+ runs: [],
1227
+ functions: new Set()
1228
+ });
1229
+ }
1230
+ for (let i = 0; i < m.getNumElementSegments(); i++) {
1231
+ const s = binaryen.getElementSegmentInfo(m.getElementSegmentByIndex(i));
1232
+ const shape = shapes.get(s.table);
1233
+ if (!shape)
1234
+ continue;
1235
+ const offset = info(s.offset);
1236
+ if (offset.id !== binaryen.ConstId || typeof offset.value !== 'number') {
1237
+ shape.refusal ??= 'element segment offset is not a constant';
1238
+ continue;
1239
+ }
1240
+ let start = 0;
1241
+ for (let k = 0; k <= s.data.length; k++) {
1242
+ if (k < s.data.length && s.data[k])
1243
+ continue;
1244
+ if (k > start)
1245
+ shape.runs.push({
1246
+ name: `${s.name}_${shape.runs.length}`,
1247
+ offset: (offset.value >>> 0) + start,
1248
+ names: s.data.slice(start, k)
1249
+ });
1250
+ start = k + 1;
1251
+ }
1252
+ for (const name of s.data)
1253
+ if (name)
1254
+ shape.functions.add(name);
1255
+ }
1256
+ return { shapes, written };
1257
+ }
1258
+ /** Name prefix of the mutable delta globals an ownership redirect adds; the stack route sets them aside. */
1259
+ export const redirectDelta = '__folio_od';
1203
1260
  /** Computes the stack route of a module. A failure is reported in `diagnostics`, never thrown. */
1204
1261
  export function stackRoute(original, options = {}) {
1205
1262
  const { assumedTrips } = admission(options);
@@ -1208,6 +1265,7 @@ export function stackRoute(original, options = {}) {
1208
1265
  constants: [],
1209
1266
  functions: [],
1210
1267
  recursive: [],
1268
+ tables: [],
1211
1269
  work: Object.create(null),
1212
1270
  diagnostics: []
1213
1271
  };
@@ -1245,12 +1303,14 @@ export function stackRoute(original, options = {}) {
1245
1303
  : undefined
1246
1304
  });
1247
1305
  }
1306
+ const { shapes: tables, written } = tableShapes(module);
1307
+ const refusedTables = new Set();
1248
1308
  const bodies = [];
1249
1309
  for (let i = 0; i < module.getNumFunctions(); i++) {
1250
1310
  const f = binaryen.getFunctionInfo(module.getFunctionByIndex(i));
1251
1311
  if (!f.body)
1252
1312
  continue;
1253
- const body = { info: f, targets: new Set(), refs: new Set() };
1313
+ const body = { info: f, targets: new Set(), refs: new Set(), tables: new Set() };
1254
1314
  if (![...binaryen.expandType(f.params), ...f.vars].every((t) => numeric.has(t)) ||
1255
1315
  !(f.results === binaryen.none || numeric.has(f.results)))
1256
1316
  body.cause = 'non-numeric signature';
@@ -1260,6 +1320,25 @@ export function stackRoute(original, options = {}) {
1260
1320
  body.cause ??= 'unsupported expression';
1261
1321
  else if (v.id === binaryen.GlobalGetId || v.id === binaryen.GlobalSetId)
1262
1322
  body.refs.add(v.name);
1323
+ else if (v.id === binaryen.CallIndirectId) {
1324
+ const shape = tables.get(v.table);
1325
+ const refusal = shape
1326
+ ? (shape.refusal ?? (written() ? 'the module writes a table' : undefined))
1327
+ : 'no such table';
1328
+ if (!shape || refusal) {
1329
+ body.cause ??= 'indirect call';
1330
+ refusedTables.add(`${v.table}: ${refusal}`);
1331
+ }
1332
+ else {
1333
+ body.tables.add(v.table);
1334
+ // any function of the call's type in the table can run, so each must be a member
1335
+ for (const name of shape.functions) {
1336
+ const g = binaryen.getFunctionInfo(module.getFunction(name));
1337
+ if (g.params === v.params && g.results === v.results)
1338
+ body.targets.add(name);
1339
+ }
1340
+ }
1341
+ }
1263
1342
  else if (!pureNodes.has(v.id))
1264
1343
  body.cause ??= 'impure expression';
1265
1344
  if (v.isAtomic)
@@ -1280,7 +1359,13 @@ export function stackRoute(original, options = {}) {
1280
1359
  bodies.push(body);
1281
1360
  }
1282
1361
  const referenced = new Set(bodies.flatMap((body) => [...body.refs]));
1283
- const named = [...globals.keys()].filter((name) => referenced.has(name));
1362
+ const deltas = [...globals.keys()].filter((name) => name.startsWith(redirectDelta) &&
1363
+ referenced.has(name) &&
1364
+ globals.get(name).mutable &&
1365
+ !globals.get(name).refusal);
1366
+ if (deltas.length)
1367
+ route.redirect = deltas;
1368
+ const named = [...globals.keys()].filter((name) => referenced.has(name) && !deltas.includes(name));
1284
1369
  const mutable = named.filter((name) => globals.get(name).mutable);
1285
1370
  if (mutable.length > 1) {
1286
1371
  for (const name of mutable.slice(1))
@@ -1317,6 +1402,9 @@ export function stackRoute(original, options = {}) {
1317
1402
  }
1318
1403
  const inSet = bodies.filter((body) => members.has(body.info.name));
1319
1404
  route.functions = inSet.map((body) => body.info.name);
1405
+ route.tables = [...new Set(inSet.flatMap((body) => [...body.tables]))];
1406
+ for (const refusal of [...refusedTables].sort())
1407
+ route.diagnostics.push(`refused table ${refusal}`);
1320
1408
  const cyclic = recursiveFunctions(new Map(inSet.map((b) => [b.info.name, b.targets])));
1321
1409
  route.recursive = route.functions.filter((name) => cyclic.has(name));
1322
1410
  const model = workModel(new Map(inSet.map((body) => [body.info.name, body.info])), (name) => members.has(name), assumedTrips);
@@ -1343,6 +1431,7 @@ export function stackRoute(original, options = {}) {
1343
1431
  constants: [],
1344
1432
  functions: [],
1345
1433
  recursive: [],
1434
+ tables: [],
1346
1435
  work: Object.create(null),
1347
1436
  diagnostics: [
1348
1437
  `stack route unavailable: ${error instanceof Error ? error.message : String(error)}`
@@ -1378,6 +1467,7 @@ export function iterationRoute(original, route) {
1378
1467
  const stack = route.stack?.name;
1379
1468
  const constants = new Set(route.constants);
1380
1469
  const refusals = [];
1470
+ let omitted = 0;
1381
1471
  for (let i = 0; i < m.getNumFunctions(); i++) {
1382
1472
  const f = binaryen.getFunctionInfo(m.getFunctionByIndex(i));
1383
1473
  if (!f.body || !callsInLoop(f.body, members))
@@ -1387,10 +1477,15 @@ export function iterationRoute(original, route) {
1387
1477
  plan.route.diagnostics.unshift(...refusals);
1388
1478
  return plan.route;
1389
1479
  }
1390
- for (const reason of plan.refusals)
1391
- if (refusals.length < 16)
1480
+ for (const reason of plan.refusals) {
1481
+ if (refusals.length < 64)
1392
1482
  refusals.push(`refused loop in ${f.name}: ${reason}`);
1483
+ else
1484
+ omitted++;
1485
+ }
1393
1486
  }
1487
+ if (omitted)
1488
+ refusals.push(`${omitted} more refused loops not listed`);
1394
1489
  refusals.push('no loop calls into the worker set');
1395
1490
  return emptyIteration(refusals);
1396
1491
  }
@@ -1764,10 +1859,31 @@ function outlineOwner(m, f, context) {
1764
1859
  const g = binaryen.getGlobalInfo(m.getGlobal(name));
1765
1860
  w.addGlobal(name, g.type, false, w.copyExpression(g.init));
1766
1861
  }
1862
+ for (const name of context.route.redirect ?? []) {
1863
+ w.addGlobal(name, binaryen.i32, true, w.i32.const(0));
1864
+ w.addGlobalExport(name, name);
1865
+ }
1767
1866
  for (const name of context.route.functions) {
1768
1867
  const g = binaryen.getFunctionInfo(m.getFunction(name));
1769
1868
  w.addFunction(name, g.params, g.results, g.vars, w.copyExpression(g.body));
1770
1869
  }
1870
+ // same slots as the owner's table; a function outside the set gets a stub that no member
1871
+ // can reach, because the route took every function of a called type into the set
1872
+ const shapes = context.route.tables.length
1873
+ ? tableShapes(m).shapes
1874
+ : new Map();
1875
+ for (const name of context.route.tables) {
1876
+ const table = binaryen.getTableInfo(m.getTable(name));
1877
+ w.addTable(name, table.initial, table.max ?? 0xffffffff);
1878
+ for (const run of shapes.get(name).runs) {
1879
+ for (const entry of run.names)
1880
+ if (!w.getFunction(entry)) {
1881
+ const g = binaryen.getFunctionInfo(m.getFunction(entry));
1882
+ w.addFunction(entry, g.params, g.results, [], w.unreachable());
1883
+ }
1884
+ w.addActiveElementSegment(name, run.name, run.names, w.i32.const(run.offset));
1885
+ }
1886
+ }
1771
1887
  let iterate = '__folio_iterate';
1772
1888
  while (w.getFunction(iterate))
1773
1889
  iterate += '_';
@@ -1780,7 +1896,18 @@ function outlineOwner(m, f, context) {
1780
1896
  w.addGlobalExport(stack, stackExport);
1781
1897
  if (!w.validate())
1782
1898
  throw new Error('invalid iteration module');
1783
- const bytes = w.emitBinary();
1899
+ // a redirect keeps names so the stack route still sets its delta globals aside
1900
+ const named = Boolean(context.route.redirect?.length);
1901
+ const before = binaryen.getDebugInfo();
1902
+ if (named)
1903
+ binaryen.setDebugInfo(true);
1904
+ let bytes;
1905
+ try {
1906
+ bytes = w.emitBinary();
1907
+ }
1908
+ finally {
1909
+ binaryen.setDebugInfo(before);
1910
+ }
1784
1911
  new WebAssembly.Module(Uint8Array.from(bytes));
1785
1912
  const trip = entry(counter);
1786
1913
  const locals = [
@@ -0,0 +1,44 @@
1
+ import type { TaskRecord } from './types.ts';
2
+ interface FoldPart {
3
+ readonly bytes: Uint8Array;
4
+ readonly record: TaskRecord;
5
+ text(): string;
6
+ json<T = unknown>(): T;
7
+ }
8
+ interface FoldPool {
9
+ readonly width: number;
10
+ submit(name: string, input: Uint8Array): string;
11
+ join(handle: string): FoldPart;
12
+ }
13
+ /** A byte range of the input, one per task. */
14
+ export interface FoldChunk {
15
+ start: number;
16
+ end: number;
17
+ }
18
+ /** Options for `foldChunks`. */
19
+ export interface FoldOptions<State> {
20
+ /** Every chunk but the last starts and ends on a multiple of this. The default is 1. */
21
+ align?: number;
22
+ /** Explicit chunk ranges. The default splits the input into `pool.width` aligned chunks. */
23
+ chunks?: FoldChunk[];
24
+ /** Name of the task that runs one chunk. */
25
+ task(chunk: FoldChunk): string;
26
+ /** State before the first chunk. */
27
+ initial: State;
28
+ /** Folds one chunk's joined result into the state. Chunks arrive in order. */
29
+ combine(state: State, part: FoldPart, chunk: FoldChunk): State;
30
+ }
31
+ /** CRC-32 of A||B from the CRCs of A and B and the length of B. */
32
+ export declare function crc32Combine(crcA: number, crcB: number, lengthB: number): number;
33
+ /** Adler-32 of A||B from the sums of A and B and the length of B. */
34
+ export declare function adler32Combine(adlerA: number, adlerB: number, lengthB: number): number;
35
+ /** The 16-byte big-endian AES-CTR counter after `blocks` blocks, carrying through every byte. */
36
+ export declare function ctrAdvance(counter: Uint8Array, blocks: number): Uint8Array;
37
+ /** Splits `length` bytes into at most `count` ranges; all but the last are multiples of `align`. */
38
+ export declare function chunkRanges(length: number, count: number, align?: number): FoldChunk[];
39
+ /**
40
+ * Runs one task per chunk on `pool` and folds the results in order. The input is copied into each
41
+ * task (see `TaskPool.submit`), so the state is built from copies, not from the input buffer.
42
+ */
43
+ export declare function foldChunks<State>(pool: FoldPool, input: Uint8Array, options: FoldOptions<State>): State;
44
+ export {};
@@ -0,0 +1,105 @@
1
+ const CRC_POLY = 0xedb88320;
2
+ const CRC_TABLE = Uint32Array.from({ length: 256 }, (_, n) => {
3
+ let c = n;
4
+ for (let k = 0; k < 8; k++)
5
+ c = c & 1 ? (c >>> 1) ^ CRC_POLY : c >>> 1;
6
+ return c >>> 0;
7
+ });
8
+ const crcColumn = (v) => ((v >>> 8) ^ CRC_TABLE[v & 0xff]) >>> 0;
9
+ // columns of the GF(2) operator that shifts a CRC register by one zero byte
10
+ const CRC_ZERO_BYTE = Array.from({ length: 32 }, (_, k) => crcColumn((1 << k) >>> 0));
11
+ function gf2Times(matrix, vector) {
12
+ let out = 0;
13
+ for (let k = 0, v = vector >>> 0; v; k++, v >>>= 1)
14
+ if (v & 1)
15
+ out ^= matrix[k];
16
+ return out >>> 0;
17
+ }
18
+ /** CRC-32 of A||B from the CRCs of A and B and the length of B. */
19
+ export function crc32Combine(crcA, crcB, lengthB) {
20
+ if (!Number.isSafeInteger(lengthB) || lengthB < 0)
21
+ throw new RangeError('invalid length');
22
+ // crc(AB) = M^lengthB crc(A) xor crc(B), with M the one-zero-byte operator
23
+ let vector = crcA >>> 0;
24
+ let matrix = CRC_ZERO_BYTE;
25
+ for (let n = lengthB; n > 0; n = Math.floor(n / 2)) {
26
+ if (n % 2 === 1)
27
+ vector = gf2Times(matrix, vector);
28
+ matrix = matrix.map((column) => gf2Times(matrix, column));
29
+ }
30
+ return (vector ^ crcB) >>> 0;
31
+ }
32
+ const ADLER_BASE = 65521;
33
+ /** Adler-32 of A||B from the sums of A and B and the length of B. */
34
+ export function adler32Combine(adlerA, adlerB, lengthB) {
35
+ if (!Number.isSafeInteger(lengthB) || lengthB < 0)
36
+ throw new RangeError('invalid length');
37
+ const s1a = adlerA & 0xffff;
38
+ const s2a = adlerA >>> 16;
39
+ const s1b = adlerB & 0xffff;
40
+ const s2b = adlerB >>> 16;
41
+ const s1 = (s1a + s1b + ADLER_BASE - 1) % ADLER_BASE;
42
+ const s2 = (s2a +
43
+ s2b +
44
+ (((lengthB % ADLER_BASE) * ((s1a + ADLER_BASE - 1) % ADLER_BASE)) % ADLER_BASE)) %
45
+ ADLER_BASE;
46
+ return ((s2 << 16) | s1) >>> 0;
47
+ }
48
+ /** The 16-byte big-endian AES-CTR counter after `blocks` blocks, carrying through every byte. */
49
+ export function ctrAdvance(counter, blocks) {
50
+ if (counter.length !== 16)
51
+ throw new RangeError('counter must be 16 bytes');
52
+ if (!Number.isSafeInteger(blocks) || blocks < 0)
53
+ throw new RangeError('invalid block count');
54
+ const out = Uint8Array.from(counter);
55
+ let carry = blocks;
56
+ for (let i = 15; i >= 0 && carry > 0; i--) {
57
+ const sum = out[i] + (carry % 256);
58
+ out[i] = sum % 256;
59
+ carry = Math.floor(carry / 256) + Math.floor(sum / 256);
60
+ }
61
+ return out;
62
+ }
63
+ /** Splits `length` bytes into at most `count` ranges; all but the last are multiples of `align`. */
64
+ export function chunkRanges(length, count, align = 1) {
65
+ if (!Number.isSafeInteger(length) || length < 0)
66
+ throw new RangeError('invalid length');
67
+ if (!Number.isSafeInteger(count) || count < 1)
68
+ throw new RangeError('invalid chunk count');
69
+ if (!Number.isSafeInteger(align) || align < 1)
70
+ throw new RangeError('invalid alignment');
71
+ const step = Math.max(align, Math.ceil(length / count / align) * align);
72
+ const chunks = [];
73
+ for (let start = 0; start < length; start += step)
74
+ chunks.push({ start, end: Math.min(length, start + step) });
75
+ return chunks;
76
+ }
77
+ function checkChunks(chunks, length, align) {
78
+ let at = 0;
79
+ chunks.forEach((chunk, index) => {
80
+ if (chunk.start !== at || chunk.end <= chunk.start)
81
+ throw new RangeError(`chunk ${index} is not contiguous`);
82
+ const last = index === chunks.length - 1;
83
+ if (!last && chunk.end % align !== 0)
84
+ throw new RangeError(`chunk ${index} ends at ${chunk.end}, not a multiple of ${align}`);
85
+ at = chunk.end;
86
+ });
87
+ if (at !== length)
88
+ throw new RangeError(`chunks cover ${at} of ${length} bytes`);
89
+ }
90
+ /**
91
+ * Runs one task per chunk on `pool` and folds the results in order. The input is copied into each
92
+ * task (see `TaskPool.submit`), so the state is built from copies, not from the input buffer.
93
+ */
94
+ export function foldChunks(pool, input, options) {
95
+ const align = options.align ?? 1;
96
+ const chunks = options.chunks ?? chunkRanges(input.length, pool.width, align);
97
+ if (input.length)
98
+ checkChunks(chunks, input.length, align);
99
+ const handles = chunks.map((chunk) => pool.submit(options.task(chunk), input.slice(chunk.start, chunk.end)));
100
+ let state = options.initial;
101
+ chunks.forEach((chunk, index) => {
102
+ state = options.combine(state, pool.join(handles[index]), chunk);
103
+ });
104
+ return state;
105
+ }
@@ -1,5 +1,5 @@
1
1
  import binaryen from 'binaryen';
2
- export interface NativeAccess {
2
+ interface NativeAccess {
3
3
  parameter: number;
4
4
  offset: number;
5
5
  bytes: number;
@@ -10,3 +10,4 @@ export interface NativePlan {
10
10
  workParameters: number[];
11
11
  }
12
12
  export declare function nativePlan(module: binaryen.Module, fn: binaryen.FunctionRef): NativePlan | undefined;
13
+ export {};
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Run-encoded tracking: reads and writes as sorted, non-touching `[start, length]` runs in a flat
3
+ * `Uint32Array`. A run set is canonical when every length is at least 1 and each start lies past
4
+ * the end of the run before it, so `[0, 4]` followed by `[4, 4]` is not canonical.
5
+ */
6
+ /** Bytes covered by a flat run list. */
7
+ export declare function runBytes(runs: ArrayLike<number>): number;
8
+ /** Canonical runs from addresses sorted ascending; a repeated address counts once. */
9
+ export declare function runsOfSorted(addresses: ArrayLike<number>): Uint32Array;
10
+ /** Runs for written bytes given as `[address, value]` pairs in any order, with their bytes. */
11
+ export declare function writeRunsOf(pairs: readonly (readonly [number, number])[]): {
12
+ runs: Uint32Array;
13
+ data: Uint8Array;
14
+ };
15
+ /**
16
+ * Canonical runs from written pieces in any order; pieces that touch merge. Pieces must not
17
+ * overlap. The bytes are copied once, in address order.
18
+ */
19
+ export declare function packWrites(pieces: readonly (readonly [start: number, data: Uint8Array])[]): {
20
+ runs: Uint32Array;
21
+ data: Uint8Array;
22
+ };
23
+ /** Keeps the first `cap` bytes of a run list. */
24
+ export declare function capRuns(runs: Uint32Array, cap: number): Uint32Array;
25
+ /**
26
+ * Throws unless `runs` is canonical and every byte lies below `limit`. A frame decoder calls it
27
+ * on every run list it reads, so the rest of the owner can rely on the form.
28
+ */
29
+ export declare function checkRuns(runs: ArrayLike<number>, limit: number, label: string): void;
30
+ /**
31
+ * Bytes written so far in one batch, as sorted non-touching intervals. `overlaps` is the
32
+ * conflict test of the owner: true when any read run shares a byte with an interval.
33
+ */
34
+ export declare class DirtyRuns {
35
+ #private;
36
+ get count(): number;
37
+ has(address: number): boolean;
38
+ /** Adds `[start, start + length)`; intervals it touches or overlaps merge. */
39
+ add(start: number, length: number): void;
40
+ /** True when any byte of the canonical run list lies in the set. */
41
+ overlaps(runs: ArrayLike<number>): boolean;
42
+ /** Every dirty byte as one canonical run list. */
43
+ runs(): Uint32Array;
44
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Run-encoded tracking: reads and writes as sorted, non-touching `[start, length]` runs in a flat
3
+ * `Uint32Array`. A run set is canonical when every length is at least 1 and each start lies past
4
+ * the end of the run before it, so `[0, 4]` followed by `[4, 4]` is not canonical.
5
+ */
6
+ /** Bytes covered by a flat run list. */
7
+ export function runBytes(runs) {
8
+ let total = 0;
9
+ for (let i = 1; i < runs.length; i += 2)
10
+ total += runs[i];
11
+ return total;
12
+ }
13
+ /** Canonical runs from addresses sorted ascending; a repeated address counts once. */
14
+ export function runsOfSorted(addresses) {
15
+ const out = [];
16
+ let end = -1;
17
+ for (let i = 0; i < addresses.length; i++) {
18
+ const address = addresses[i];
19
+ if (address === end) {
20
+ out[out.length - 1]++;
21
+ end++;
22
+ }
23
+ else if (address > end) {
24
+ out.push(address, 1);
25
+ end = address + 1;
26
+ }
27
+ }
28
+ return Uint32Array.from(out);
29
+ }
30
+ /** Runs for written bytes given as `[address, value]` pairs in any order, with their bytes. */
31
+ export function writeRunsOf(pairs) {
32
+ const order = Uint32Array.from(pairs, (pair) => pair[0]).sort();
33
+ const values = new Map();
34
+ for (const [address, value] of pairs)
35
+ values.set(address, value);
36
+ const runs = runsOfSorted(order);
37
+ const data = new Uint8Array(runBytes(runs));
38
+ let at = 0;
39
+ for (let i = 0; i < runs.length; i += 2)
40
+ for (let k = 0; k < runs[i + 1]; k++)
41
+ data[at++] = values.get(runs[i] + k);
42
+ return { runs, data };
43
+ }
44
+ /**
45
+ * Canonical runs from written pieces in any order; pieces that touch merge. Pieces must not
46
+ * overlap. The bytes are copied once, in address order.
47
+ */
48
+ export function packWrites(pieces) {
49
+ const sorted = pieces.filter((piece) => piece[1].length).sort((a, b) => a[0] - b[0]);
50
+ const runs = [];
51
+ let total = 0;
52
+ for (const [start, data] of sorted) {
53
+ const last = runs.length - 2;
54
+ if (last >= 0 && start <= runs[last] + runs[last + 1])
55
+ runs[last + 1] = Math.max(runs[last + 1], start + data.length - runs[last]);
56
+ else
57
+ runs.push(start, data.length);
58
+ }
59
+ for (let i = 1; i < runs.length; i += 2)
60
+ total += runs[i];
61
+ const out = new Uint8Array(total);
62
+ let base = 0, run = 0;
63
+ for (const [start, data] of sorted) {
64
+ while (start >= runs[run * 2] + runs[run * 2 + 1]) {
65
+ base += runs[run * 2 + 1];
66
+ run++;
67
+ }
68
+ out.set(data, base + start - runs[run * 2]);
69
+ }
70
+ return { runs: Uint32Array.from(runs), data: out };
71
+ }
72
+ /** Keeps the first `cap` bytes of a run list. */
73
+ export function capRuns(runs, cap) {
74
+ let left = Math.max(0, cap);
75
+ for (let i = 1; i < runs.length; i += 2) {
76
+ if (runs[i] <= left) {
77
+ left -= runs[i];
78
+ continue;
79
+ }
80
+ const out = runs.slice(0, i + 1);
81
+ if (left)
82
+ out[i] = left;
83
+ else
84
+ return runs.slice(0, i - 1);
85
+ return out;
86
+ }
87
+ return runs;
88
+ }
89
+ /**
90
+ * Throws unless `runs` is canonical and every byte lies below `limit`. A frame decoder calls it
91
+ * on every run list it reads, so the rest of the owner can rely on the form.
92
+ */
93
+ export function checkRuns(runs, limit, label) {
94
+ let end = -1;
95
+ for (let i = 0; i < runs.length; i += 2) {
96
+ const start = runs[i], length = runs[i + 1];
97
+ if (length < 1 || start <= end)
98
+ throw new TypeError(`non-canonical lane ${label} runs`);
99
+ if (start + length > limit)
100
+ throw new RangeError(`lane ${label} outside arena`);
101
+ end = start + length;
102
+ }
103
+ }
104
+ /**
105
+ * Bytes written so far in one batch, as sorted non-touching intervals. `overlaps` is the
106
+ * conflict test of the owner: true when any read run shares a byte with an interval.
107
+ */
108
+ export class DirtyRuns {
109
+ // parallel arrays, ascending; end is exclusive
110
+ #starts = [];
111
+ #ends = [];
112
+ get count() {
113
+ return this.#starts.length;
114
+ }
115
+ /** First interval whose end lies past `at`. */
116
+ #after(at, from = 0) {
117
+ let low = from, high = this.#ends.length;
118
+ while (low < high) {
119
+ const mid = (low + high) >> 1;
120
+ if (this.#ends[mid] <= at)
121
+ low = mid + 1;
122
+ else
123
+ high = mid;
124
+ }
125
+ return low;
126
+ }
127
+ has(address) {
128
+ const i = this.#after(address);
129
+ return i < this.#starts.length && this.#starts[i] <= address;
130
+ }
131
+ /** Adds `[start, start + length)`; intervals it touches or overlaps merge. */
132
+ add(start, length) {
133
+ if (length < 1)
134
+ return;
135
+ let end = start + length;
136
+ // ascending writes append: the common case, since a batch walks its output forward
137
+ const top = this.#ends.length - 1;
138
+ if (top < 0 || start > this.#ends[top]) {
139
+ this.#starts.push(start);
140
+ this.#ends.push(end);
141
+ return;
142
+ }
143
+ if (start === this.#ends[top]) {
144
+ this.#ends[top] = end;
145
+ return;
146
+ }
147
+ // touching intervals merge: the first one whose end reaches start
148
+ const first = this.#after(start - 1);
149
+ let last = first;
150
+ while (last < this.#starts.length && this.#starts[last] <= end) {
151
+ end = Math.max(end, this.#ends[last]);
152
+ last++;
153
+ }
154
+ const merged = first < last ? Math.min(start, this.#starts[first]) : start;
155
+ this.#starts.splice(first, last - first, merged);
156
+ this.#ends.splice(first, last - first, end);
157
+ }
158
+ /** True when any byte of the canonical run list lies in the set. */
159
+ overlaps(runs) {
160
+ if (!this.#starts.length)
161
+ return false;
162
+ let i = 0;
163
+ for (let r = 0; r < runs.length; r += 2) {
164
+ const start = runs[r], end = start + runs[r + 1];
165
+ i = this.#after(start, i);
166
+ if (i === this.#starts.length)
167
+ return false;
168
+ if (this.#starts[i] < end)
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+ /** Every dirty byte as one canonical run list. */
174
+ runs() {
175
+ const out = new Uint32Array(this.#starts.length * 2);
176
+ this.#starts.forEach((start, i) => {
177
+ out[i * 2] = start;
178
+ out[i * 2 + 1] = this.#ends[i] - start;
179
+ });
180
+ return out;
181
+ }
182
+ }
@@ -4,9 +4,19 @@ export interface TransactionResult {
4
4
  value?: unknown;
5
5
  reads: number[];
6
6
  writes: [number, number][];
7
+ /** Run encoding: read runs as flat start, length pairs; `reads` is then empty. See `runs.ts`. */
8
+ readRuns?: Uint32Array;
9
+ /** Run encoding: write runs as flat start, length pairs; `writes` is then empty. */
10
+ writeRuns?: Uint32Array;
11
+ /** Run encoding: the bytes of every write run, back to back. */
12
+ writeData?: Uint8Array;
7
13
  trap?: string;
8
14
  errorKind?: string;
9
15
  exhausted?: boolean;
16
+ /** Ranges mode: reads of bytes that were not shipped. Informational; owners recompute it. */
17
+ escapes?: [number, number][];
18
+ /** Ranges mode: a trap or exhaustion that unshipped zeros may have caused. */
19
+ inconclusive?: boolean;
10
20
  timing?: {
11
21
  wallMs: number;
12
22
  cpuMs: number;