@elaraai/e3-web 0.0.0-stage → 1.0.86

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 (303) hide show
  1. package/LICENSE.md +54 -0
  2. package/README.md +395 -2
  3. package/dist/src/app.d.ts +91 -0
  4. package/dist/src/app.d.ts.map +1 -0
  5. package/dist/src/app.js +112 -0
  6. package/dist/src/app.js.map +1 -0
  7. package/dist/src/bridge/bridge.spec.d.ts +6 -0
  8. package/dist/src/bridge/bridge.spec.d.ts.map +1 -0
  9. package/dist/src/bridge/bridge.spec.js +56 -0
  10. package/dist/src/bridge/bridge.spec.js.map +1 -0
  11. package/dist/src/bridge/page.d.ts +149 -0
  12. package/dist/src/bridge/page.d.ts.map +1 -0
  13. package/dist/src/bridge/page.js +328 -0
  14. package/dist/src/bridge/page.js.map +1 -0
  15. package/dist/src/bridge/protocol.d.ts +181 -0
  16. package/dist/src/bridge/protocol.d.ts.map +1 -0
  17. package/dist/src/bridge/protocol.js +113 -0
  18. package/dist/src/bridge/protocol.js.map +1 -0
  19. package/dist/src/bridge/worker.d.ts +124 -0
  20. package/dist/src/bridge/worker.d.ts.map +1 -0
  21. package/dist/src/bridge/worker.js +185 -0
  22. package/dist/src/bridge/worker.js.map +1 -0
  23. package/dist/src/browser/bridge.page.d.ts +12 -0
  24. package/dist/src/browser/bridge.page.d.ts.map +1 -0
  25. package/dist/src/browser/bridge.page.js +79 -0
  26. package/dist/src/browser/bridge.page.js.map +1 -0
  27. package/dist/src/browser/bridge.spec.d.ts +6 -0
  28. package/dist/src/browser/bridge.spec.d.ts.map +1 -0
  29. package/dist/src/browser/bridge.spec.js +105 -0
  30. package/dist/src/browser/bridge.spec.js.map +1 -0
  31. package/dist/src/browser/bridge.worker.d.ts +6 -0
  32. package/dist/src/browser/bridge.worker.d.ts.map +1 -0
  33. package/dist/src/browser/bridge.worker.js +35 -0
  34. package/dist/src/browser/bridge.worker.js.map +1 -0
  35. package/dist/src/browser/compliance.d.ts +68 -0
  36. package/dist/src/browser/compliance.d.ts.map +1 -0
  37. package/dist/src/browser/compliance.js +30 -0
  38. package/dist/src/browser/compliance.js.map +1 -0
  39. package/dist/src/browser/compliance.page.d.ts +6 -0
  40. package/dist/src/browser/compliance.page.d.ts.map +1 -0
  41. package/dist/src/browser/compliance.page.js +204 -0
  42. package/dist/src/browser/compliance.page.js.map +1 -0
  43. package/dist/src/browser/compliance.spec.d.ts +6 -0
  44. package/dist/src/browser/compliance.spec.d.ts.map +1 -0
  45. package/dist/src/browser/compliance.spec.js +147 -0
  46. package/dist/src/browser/compliance.spec.js.map +1 -0
  47. package/dist/src/browser/e3-api-1.spec.d.ts +6 -0
  48. package/dist/src/browser/e3-api-1.spec.d.ts.map +1 -0
  49. package/dist/src/browser/e3-api-1.spec.js +12 -0
  50. package/dist/src/browser/e3-api-1.spec.js.map +1 -0
  51. package/dist/src/browser/e3-api-2.spec.d.ts +6 -0
  52. package/dist/src/browser/e3-api-2.spec.d.ts.map +1 -0
  53. package/dist/src/browser/e3-api-2.spec.js +12 -0
  54. package/dist/src/browser/e3-api-2.spec.js.map +1 -0
  55. package/dist/src/browser/e3-api-3.spec.d.ts +6 -0
  56. package/dist/src/browser/e3-api-3.spec.d.ts.map +1 -0
  57. package/dist/src/browser/e3-api-3.spec.js +12 -0
  58. package/dist/src/browser/e3-api-3.spec.js.map +1 -0
  59. package/dist/src/browser/e3-api-parts.spec.d.ts +6 -0
  60. package/dist/src/browser/e3-api-parts.spec.d.ts.map +1 -0
  61. package/dist/src/browser/e3-api-parts.spec.js +45 -0
  62. package/dist/src/browser/e3-api-parts.spec.js.map +1 -0
  63. package/dist/src/browser/e3-api.d.ts +28 -0
  64. package/dist/src/browser/e3-api.d.ts.map +1 -0
  65. package/dist/src/browser/e3-api.js +144 -0
  66. package/dist/src/browser/e3-api.js.map +1 -0
  67. package/dist/src/browser/e3-client.worker.d.ts +6 -0
  68. package/dist/src/browser/e3-client.worker.d.ts.map +1 -0
  69. package/dist/src/browser/e3-client.worker.js +19 -0
  70. package/dist/src/browser/e3-client.worker.js.map +1 -0
  71. package/dist/src/browser/e3-forward.d.ts +27 -0
  72. package/dist/src/browser/e3-forward.d.ts.map +1 -0
  73. package/dist/src/browser/e3-forward.js +81 -0
  74. package/dist/src/browser/e3-forward.js.map +1 -0
  75. package/dist/src/browser/e3-forward.spec.d.ts +6 -0
  76. package/dist/src/browser/e3-forward.spec.d.ts.map +1 -0
  77. package/dist/src/browser/e3-forward.spec.js +84 -0
  78. package/dist/src/browser/e3-forward.spec.js.map +1 -0
  79. package/dist/src/browser/e3-port.worker.d.ts +6 -0
  80. package/dist/src/browser/e3-port.worker.d.ts.map +1 -0
  81. package/dist/src/browser/e3-port.worker.js +21 -0
  82. package/dist/src/browser/e3-port.worker.js.map +1 -0
  83. package/dist/src/browser/e3-unit.worker.d.ts +6 -0
  84. package/dist/src/browser/e3-unit.worker.d.ts.map +1 -0
  85. package/dist/src/browser/e3-unit.worker.js +18 -0
  86. package/dist/src/browser/e3-unit.worker.js.map +1 -0
  87. package/dist/src/browser/e3-wire.d.ts +43 -0
  88. package/dist/src/browser/e3-wire.d.ts.map +1 -0
  89. package/dist/src/browser/e3-wire.js +32 -0
  90. package/dist/src/browser/e3-wire.js.map +1 -0
  91. package/dist/src/browser/e3.page.d.ts +21 -0
  92. package/dist/src/browser/e3.page.d.ts.map +1 -0
  93. package/dist/src/browser/e3.page.js +119 -0
  94. package/dist/src/browser/e3.page.js.map +1 -0
  95. package/dist/src/browser/e3.spec.d.ts +6 -0
  96. package/dist/src/browser/e3.spec.d.ts.map +1 -0
  97. package/dist/src/browser/e3.spec.js +358 -0
  98. package/dist/src/browser/e3.spec.js.map +1 -0
  99. package/dist/src/browser/e3.worker.d.ts +6 -0
  100. package/dist/src/browser/e3.worker.d.ts.map +1 -0
  101. package/dist/src/browser/e3.worker.js +38 -0
  102. package/dist/src/browser/e3.worker.js.map +1 -0
  103. package/dist/src/browser/harness.d.ts +175 -0
  104. package/dist/src/browser/harness.d.ts.map +1 -0
  105. package/dist/src/browser/harness.js +375 -0
  106. package/dist/src/browser/harness.js.map +1 -0
  107. package/dist/src/browser/page.d.ts +47 -0
  108. package/dist/src/browser/page.d.ts.map +1 -0
  109. package/dist/src/browser/page.js +47 -0
  110. package/dist/src/browser/page.js.map +1 -0
  111. package/dist/src/browser/repository.page.d.ts +85 -0
  112. package/dist/src/browser/repository.page.d.ts.map +1 -0
  113. package/dist/src/browser/repository.page.js +271 -0
  114. package/dist/src/browser/repository.page.js.map +1 -0
  115. package/dist/src/browser/runner.page.d.ts +6 -0
  116. package/dist/src/browser/runner.page.d.ts.map +1 -0
  117. package/dist/src/browser/runner.page.js +62 -0
  118. package/dist/src/browser/runner.page.js.map +1 -0
  119. package/dist/src/browser/runner.spec.d.ts +6 -0
  120. package/dist/src/browser/runner.spec.d.ts.map +1 -0
  121. package/dist/src/browser/runner.spec.js +46 -0
  122. package/dist/src/browser/runner.spec.js.map +1 -0
  123. package/dist/src/browser/storage.page.d.ts +6 -0
  124. package/dist/src/browser/storage.page.d.ts.map +1 -0
  125. package/dist/src/browser/storage.page.js +289 -0
  126. package/dist/src/browser/storage.page.js.map +1 -0
  127. package/dist/src/browser/storage.spec.d.ts +6 -0
  128. package/dist/src/browser/storage.spec.d.ts.map +1 -0
  129. package/dist/src/browser/storage.spec.js +211 -0
  130. package/dist/src/browser/storage.spec.js.map +1 -0
  131. package/dist/src/browser/unit.worker.d.ts +6 -0
  132. package/dist/src/browser/unit.worker.d.ts.map +1 -0
  133. package/dist/src/browser/unit.worker.js +17 -0
  134. package/dist/src/browser/unit.worker.js.map +1 -0
  135. package/dist/src/execution/WebTaskRunner.d.ts +159 -0
  136. package/dist/src/execution/WebTaskRunner.d.ts.map +1 -0
  137. package/dist/src/execution/WebTaskRunner.js +581 -0
  138. package/dist/src/execution/WebTaskRunner.js.map +1 -0
  139. package/dist/src/execution/WebTaskRunner.spec.d.ts +6 -0
  140. package/dist/src/execution/WebTaskRunner.spec.d.ts.map +1 -0
  141. package/dist/src/execution/WebTaskRunner.spec.js +91 -0
  142. package/dist/src/execution/WebTaskRunner.spec.js.map +1 -0
  143. package/dist/src/execution/e3-platform.d.ts +41 -0
  144. package/dist/src/execution/e3-platform.d.ts.map +1 -0
  145. package/dist/src/execution/e3-platform.js +52 -0
  146. package/dist/src/execution/e3-platform.js.map +1 -0
  147. package/dist/src/execution/in-process.d.ts +32 -0
  148. package/dist/src/execution/in-process.d.ts.map +1 -0
  149. package/dist/src/execution/in-process.js +89 -0
  150. package/dist/src/execution/in-process.js.map +1 -0
  151. package/dist/src/execution/pool.d.ts +172 -0
  152. package/dist/src/execution/pool.d.ts.map +1 -0
  153. package/dist/src/execution/pool.js +352 -0
  154. package/dist/src/execution/pool.js.map +1 -0
  155. package/dist/src/execution/pool.spec.d.ts +6 -0
  156. package/dist/src/execution/pool.spec.d.ts.map +1 -0
  157. package/dist/src/execution/pool.spec.js +252 -0
  158. package/dist/src/execution/pool.spec.js.map +1 -0
  159. package/dist/src/execution/protocol.d.ts +108 -0
  160. package/dist/src/execution/protocol.d.ts.map +1 -0
  161. package/dist/src/execution/protocol.js +27 -0
  162. package/dist/src/execution/protocol.js.map +1 -0
  163. package/dist/src/execution/unit-server.d.ts +131 -0
  164. package/dist/src/execution/unit-server.d.ts.map +1 -0
  165. package/dist/src/execution/unit-server.js +142 -0
  166. package/dist/src/execution/unit-server.js.map +1 -0
  167. package/dist/src/index.d.ts +39 -0
  168. package/dist/src/index.d.ts.map +1 -0
  169. package/dist/src/index.js +37 -0
  170. package/dist/src/index.js.map +1 -0
  171. package/dist/src/index.spec.d.ts +6 -0
  172. package/dist/src/index.spec.d.ts.map +1 -0
  173. package/dist/src/index.spec.js +212 -0
  174. package/dist/src/index.spec.js.map +1 -0
  175. package/dist/src/node.d.ts +12 -0
  176. package/dist/src/node.d.ts.map +1 -0
  177. package/dist/src/node.js +12 -0
  178. package/dist/src/node.js.map +1 -0
  179. package/dist/src/storage/WebStateStore.d.ts +64 -0
  180. package/dist/src/storage/WebStateStore.d.ts.map +1 -0
  181. package/dist/src/storage/WebStateStore.js +237 -0
  182. package/dist/src/storage/WebStateStore.js.map +1 -0
  183. package/dist/src/storage/WebStorage.d.ts +225 -0
  184. package/dist/src/storage/WebStorage.d.ts.map +1 -0
  185. package/dist/src/storage/WebStorage.js +1462 -0
  186. package/dist/src/storage/WebStorage.js.map +1 -0
  187. package/dist/src/storage/adapters.d.ts +610 -0
  188. package/dist/src/storage/adapters.d.ts.map +1 -0
  189. package/dist/src/storage/adapters.js +246 -0
  190. package/dist/src/storage/adapters.js.map +1 -0
  191. package/dist/src/storage/indexeddb.d.ts +93 -0
  192. package/dist/src/storage/indexeddb.d.ts.map +1 -0
  193. package/dist/src/storage/indexeddb.js +384 -0
  194. package/dist/src/storage/indexeddb.js.map +1 -0
  195. package/dist/src/storage/indexeddb.spec.d.ts +6 -0
  196. package/dist/src/storage/indexeddb.spec.d.ts.map +1 -0
  197. package/dist/src/storage/indexeddb.spec.js +77 -0
  198. package/dist/src/storage/indexeddb.spec.js.map +1 -0
  199. package/dist/src/storage/memory.d.ts +275 -0
  200. package/dist/src/storage/memory.d.ts.map +1 -0
  201. package/dist/src/storage/memory.js +724 -0
  202. package/dist/src/storage/memory.js.map +1 -0
  203. package/dist/src/storage/memory.spec.d.ts +6 -0
  204. package/dist/src/storage/memory.spec.d.ts.map +1 -0
  205. package/dist/src/storage/memory.spec.js +71 -0
  206. package/dist/src/storage/memory.spec.js.map +1 -0
  207. package/dist/src/storage/node-files.d.ts +38 -0
  208. package/dist/src/storage/node-files.d.ts.map +1 -0
  209. package/dist/src/storage/node-files.js +148 -0
  210. package/dist/src/storage/node-files.js.map +1 -0
  211. package/dist/src/storage/node-files.spec.d.ts +6 -0
  212. package/dist/src/storage/node-files.spec.d.ts.map +1 -0
  213. package/dist/src/storage/node-files.spec.js +40 -0
  214. package/dist/src/storage/node-files.spec.js.map +1 -0
  215. package/dist/src/storage/opfs.d.ts +145 -0
  216. package/dist/src/storage/opfs.d.ts.map +1 -0
  217. package/dist/src/storage/opfs.js +514 -0
  218. package/dist/src/storage/opfs.js.map +1 -0
  219. package/dist/src/storage/opfs.spec.d.ts +6 -0
  220. package/dist/src/storage/opfs.spec.d.ts.map +1 -0
  221. package/dist/src/storage/opfs.spec.js +51 -0
  222. package/dist/src/storage/opfs.spec.js.map +1 -0
  223. package/dist/src/storage/record-keys.d.ts +78 -0
  224. package/dist/src/storage/record-keys.d.ts.map +1 -0
  225. package/dist/src/storage/record-keys.js +71 -0
  226. package/dist/src/storage/record-keys.js.map +1 -0
  227. package/dist/src/storage/stores.spec.d.ts +6 -0
  228. package/dist/src/storage/stores.spec.d.ts.map +1 -0
  229. package/dist/src/storage/stores.spec.js +326 -0
  230. package/dist/src/storage/stores.spec.js.map +1 -0
  231. package/dist/src/storage/web-locks.d.ts +103 -0
  232. package/dist/src/storage/web-locks.d.ts.map +1 -0
  233. package/dist/src/storage/web-locks.js +228 -0
  234. package/dist/src/storage/web-locks.js.map +1 -0
  235. package/dist/src/testing/adapter-contract.d.ts +116 -0
  236. package/dist/src/testing/adapter-contract.d.ts.map +1 -0
  237. package/dist/src/testing/adapter-contract.js +769 -0
  238. package/dist/src/testing/adapter-contract.js.map +1 -0
  239. package/dist/src/testing/assert.d.ts +75 -0
  240. package/dist/src/testing/assert.d.ts.map +1 -0
  241. package/dist/src/testing/assert.js +146 -0
  242. package/dist/src/testing/assert.js.map +1 -0
  243. package/dist/src/testing/assert.spec.d.ts +6 -0
  244. package/dist/src/testing/assert.spec.d.ts.map +1 -0
  245. package/dist/src/testing/assert.spec.js +62 -0
  246. package/dist/src/testing/assert.spec.js.map +1 -0
  247. package/dist/src/testing/bridge-contract.d.ts +55 -0
  248. package/dist/src/testing/bridge-contract.d.ts.map +1 -0
  249. package/dist/src/testing/bridge-contract.js +376 -0
  250. package/dist/src/testing/bridge-contract.js.map +1 -0
  251. package/dist/src/testing/bridge-handler.d.ts +35 -0
  252. package/dist/src/testing/bridge-handler.d.ts.map +1 -0
  253. package/dist/src/testing/bridge-handler.js +108 -0
  254. package/dist/src/testing/bridge-handler.js.map +1 -0
  255. package/dist/src/testing/callers.d.ts +29 -0
  256. package/dist/src/testing/callers.d.ts.map +1 -0
  257. package/dist/src/testing/callers.js +24 -0
  258. package/dist/src/testing/callers.js.map +1 -0
  259. package/dist/src/testing/e3-fixtures.d.ts +38 -0
  260. package/dist/src/testing/e3-fixtures.d.ts.map +1 -0
  261. package/dist/src/testing/e3-fixtures.js +126 -0
  262. package/dist/src/testing/e3-fixtures.js.map +1 -0
  263. package/dist/src/testing/hold-platform.d.ts +33 -0
  264. package/dist/src/testing/hold-platform.d.ts.map +1 -0
  265. package/dist/src/testing/hold-platform.js +41 -0
  266. package/dist/src/testing/hold-platform.js.map +1 -0
  267. package/dist/src/testing/runner-cases.d.ts +112 -0
  268. package/dist/src/testing/runner-cases.d.ts.map +1 -0
  269. package/dist/src/testing/runner-cases.js +959 -0
  270. package/dist/src/testing/runner-cases.js.map +1 -0
  271. package/dist/src/testing/runner-fixtures.d.ts +13 -0
  272. package/dist/src/testing/runner-fixtures.d.ts.map +1 -0
  273. package/dist/src/testing/runner-fixtures.js +173 -0
  274. package/dist/src/testing/runner-fixtures.js.map +1 -0
  275. package/dist/src/testing/test-platform.d.ts +73 -0
  276. package/dist/src/testing/test-platform.d.ts.map +1 -0
  277. package/dist/src/testing/test-platform.js +143 -0
  278. package/dist/src/testing/test-platform.js.map +1 -0
  279. package/dist/src/transfer/WebTransferBackend.d.ts +780 -0
  280. package/dist/src/transfer/WebTransferBackend.d.ts.map +1 -0
  281. package/dist/src/transfer/WebTransferBackend.js +1140 -0
  282. package/dist/src/transfer/WebTransferBackend.js.map +1 -0
  283. package/dist/src/transfer/WebTransferBackend.spec.d.ts +6 -0
  284. package/dist/src/transfer/WebTransferBackend.spec.d.ts.map +1 -0
  285. package/dist/src/transfer/WebTransferBackend.spec.js +582 -0
  286. package/dist/src/transfer/WebTransferBackend.spec.js.map +1 -0
  287. package/dist/src/transfer/endpoints.d.ts +46 -0
  288. package/dist/src/transfer/endpoints.d.ts.map +1 -0
  289. package/dist/src/transfer/endpoints.js +157 -0
  290. package/dist/src/transfer/endpoints.js.map +1 -0
  291. package/dist/src/units.d.ts +51 -0
  292. package/dist/src/units.d.ts.map +1 -0
  293. package/dist/src/units.js +74 -0
  294. package/dist/src/units.js.map +1 -0
  295. package/dist/src/worker.d.ts +126 -0
  296. package/dist/src/worker.d.ts.map +1 -0
  297. package/dist/src/worker.js +186 -0
  298. package/dist/src/worker.js.map +1 -0
  299. package/dist/src/worker.spec.d.ts +6 -0
  300. package/dist/src/worker.spec.d.ts.map +1 -0
  301. package/dist/src/worker.spec.js +195 -0
  302. package/dist/src/worker.spec.js.map +1 -0
  303. package/package.json +76 -3
@@ -0,0 +1,959 @@
1
+ /**
2
+ * Copyright (c) 2025 Elara AI Pty Ltd
3
+ * Licensed under BSL 1.1. See LICENSE for details.
4
+ */
5
+ /**
6
+ * `WebTaskRunner`'s cases: what it does, whichever workers its units run on.
7
+ *
8
+ * A case is a plain function over a setup, asserting with `./assert.js`, as
9
+ * the adapters' contract is, so it runs where its workers are: in Node over the
10
+ * in-process workers and the adapters in memory, and in a Chromium page over
11
+ * Web Workers, IndexedDB, OPFS and Web Locks, where the page runs it by name.
12
+ *
13
+ * The tasks a case runs are the fixture package's (`runner-fixtures.ts`),
14
+ * which e3's SDK authored and `e3.export` wrote, handed to the setup as data:
15
+ * its objects and its package ref, installed in the case's repository. The
16
+ * programs a call runs are written here, in East.
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+ import { ArrayType, DictType, East, FunctionType, IntegerType, NullType, SetType, SortedMap, SortedSet, StringType, compareFor, decodeBeast2For, encodeBeast2For, encodeBeast2PagedFor, encodeEastIR, equalFor, none, printFor, some, toEastTypeValue, variant, } from '@elaraai/east';
21
+ import { ExecutionOwnerType, decodeTaskObject, manifestByteSize, manifestElementCount, } from '@elaraai/e3-types';
22
+ import { ExecutionAttempt, datasetWrite, inputsHash, intakeDelivery, mergeTreeGroups, mergeTreeLevels, oneShotExecute, packageRead, pieceSizes, planPieces, readDatasetWhole, readManifest, readRecordState, readTestPieceBytesFrom, recordIndexNames, recordMutate, splitCallPrepare, splitCallRun, uuidv7, workspaceCreate, workspaceDeploy, workspaceSetDataset, } from '@elaraai/e3-core/portable';
23
+ import { Console } from '@elaraai/east-web-std';
24
+ import { DEFAULT_WHOLE_INTAKE_LIMIT, NO_COMMANDS, WEB_RUNNER, WebTaskRunner, } from '../execution/WebTaskRunner.js';
25
+ import { UnitPool } from '../execution/pool.js';
26
+ import { AssertionError, deepEqual, equal, ok, rejects } from './assert.js';
27
+ import { TEST_PLATFORM, test_exit, test_host_echo, test_wait, testHost } from './test-platform.js';
28
+ // =============================================================================
29
+ // The fixtures
30
+ // =============================================================================
31
+ /** The fixture package's name and version. */
32
+ export const FIXTURE_PACKAGE = 'web_runner';
33
+ export const FIXTURE_VERSION = '1.0.0';
34
+ /** Bytes as base64, a chunk of characters at a time. */
35
+ function toBase64(bytes) {
36
+ let text = '';
37
+ for (let at = 0; at < bytes.length; at += 8192)
38
+ text += String.fromCharCode(...bytes.subarray(at, at + 8192));
39
+ return btoa(text);
40
+ }
41
+ /** Base64 as its bytes. */
42
+ function fromBase64(text) {
43
+ return Uint8Array.from(atob(text), (character) => character.charCodeAt(0));
44
+ }
45
+ /**
46
+ * The fixtures as a page is handed them.
47
+ *
48
+ * @param fixtures - The fixtures
49
+ * @returns Their wire form
50
+ */
51
+ export function fixturesToWire(fixtures) {
52
+ return { objects: fixtures.objects.map(([hash, bytes]) => [hash, toBase64(bytes)]), packageHash: fixtures.packageHash };
53
+ }
54
+ /**
55
+ * The fixtures a page was handed.
56
+ *
57
+ * @param wire - Their wire form
58
+ * @returns The fixtures
59
+ */
60
+ export function fixturesFromWire(wire) {
61
+ return { objects: wire.objects.map(([hash, text]) => [hash, fromBase64(text)]), packageHash: wire.packageHash };
62
+ }
63
+ // =============================================================================
64
+ // Setups
65
+ // =============================================================================
66
+ /** The repository a case runs in. */
67
+ const REPO = 'default';
68
+ /** The workspace a case deploys the fixture package to. */
69
+ const WORKSPACE = 'main';
70
+ /**
71
+ * Installs the fixture package in a repository: its objects, and its ref.
72
+ *
73
+ * @param storage - The storage
74
+ * @param repo - The repository
75
+ * @param fixtures - The fixture package
76
+ * @throws {Error} When an object is not the bytes its hash names.
77
+ */
78
+ async function installFixtures(storage, repo, fixtures) {
79
+ for (const [hash, bytes] of fixtures.objects) {
80
+ const stored = await storage.objects.write(repo, bytes);
81
+ if (stored !== hash)
82
+ throw new Error(`the fixture object ${hash} holds bytes whose hash is ${stored}`);
83
+ }
84
+ await storage.refs.packageWrite(repo, FIXTURE_PACKAGE, FIXTURE_VERSION, fixtures.packageHash);
85
+ }
86
+ /**
87
+ * Makes the setup a runner case runs over, from what a setup is made of where
88
+ * it runs.
89
+ *
90
+ * @param environment - The tab's storage, its workers, and the fixtures
91
+ * @returns The setup
92
+ */
93
+ export function runnerSetup(environment) {
94
+ return async (cleanup) => {
95
+ const { storage, openSession } = await environment.openStorage(cleanup);
96
+ await storage.repos.create(REPO);
97
+ await installFixtures(storage, REPO, environment.fixtures);
98
+ const host = testHost();
99
+ cleanup(() => host.close());
100
+ // Pieces are planned at the platform's sizes unless a case sets its own.
101
+ let pieceBytes;
102
+ readTestPieceBytesFrom(() => pieceBytes);
103
+ cleanup(() => {
104
+ pieceBytes = undefined;
105
+ });
106
+ return {
107
+ storage,
108
+ repo: REPO,
109
+ host,
110
+ pool: (options = {}) => {
111
+ const start = environment.units;
112
+ const wrap = options.units;
113
+ const pool = new UnitPool({
114
+ units: wrap === undefined ? start : () => wrap(start),
115
+ width: options.width ?? 4,
116
+ connect: host.connect,
117
+ });
118
+ cleanup(() => pool.close());
119
+ return pool;
120
+ },
121
+ runner: (pool, options = {}) => new WebTaskRunner({ repo: REPO, pool, locks: storage.adapters.locks, ...options }),
122
+ openSession: async () => {
123
+ const session = await openSession();
124
+ cleanup(() => session.close());
125
+ return session;
126
+ },
127
+ pieceBytes: (bytes) => {
128
+ pieceBytes = `${bytes}`;
129
+ },
130
+ };
131
+ };
132
+ }
133
+ // =============================================================================
134
+ // Helpers
135
+ // =============================================================================
136
+ const WordsType = ArrayType(StringType);
137
+ const EventsType = ArrayType(IntegerType);
138
+ const SalesType = DictType(IntegerType, IntegerType);
139
+ const CountsType = DictType(StringType, IntegerType);
140
+ const IntDictType = DictType(IntegerType, IntegerType);
141
+ /** A stock runner with east-node-std, as a task's default is. */
142
+ const STANDARD = variant('east_node', { platforms: ['@elaraai/east-node-std'], decode: variant('lazy', null) });
143
+ /** A stock runner with the specs' own package beside east-node-std's. */
144
+ const WITH_TEST = variant('east_node', { platforms: ['@elaraai/east-node-std', TEST_PLATFORM], decode: variant('lazy', null) });
145
+ /** A stock runner given no platform package. */
146
+ const PLATFORM_FREE = variant('east_node', { platforms: [], decode: variant('lazy', null) });
147
+ /** The limits a call runs under unless a case sets its own. */
148
+ const LIMITS = { timeoutMs: 60_000, maxResultBytes: 1024 * 1024, maxLogBytes: 64 * 1024 };
149
+ const encodeInteger = encodeBeast2For(IntegerType);
150
+ const decodeInteger = decodeBeast2For(IntegerType);
151
+ const encodeString = encodeBeast2For(StringType);
152
+ const decodeString = decodeBeast2For(StringType);
153
+ const utf8 = new TextEncoder();
154
+ /** The path of an input of the fixture package. */
155
+ function inputPath(name) {
156
+ return [variant('field', 'inputs'), variant('field', name)];
157
+ }
158
+ /**
159
+ * Asserts two East values of a type are equal, as East compares them.
160
+ *
161
+ * @throws {AssertionError} When they are not
162
+ */
163
+ function same(type, actual, expected, message) {
164
+ if (!equalFor(type)(actual, expected)) {
165
+ const print = printFor(type);
166
+ throw new AssertionError(`${message}: expected ${print(expected)}, found ${print(actual)}`);
167
+ }
168
+ }
169
+ /** The hash of a fixture task. */
170
+ async function taskHashOf(setup, name) {
171
+ const pkg = await packageRead(setup.storage, setup.repo, FIXTURE_PACKAGE, FIXTURE_VERSION);
172
+ const hash = pkg.tasks.get(name);
173
+ if (hash === undefined)
174
+ throw new Error(`the fixture package has no task '${name}'`);
175
+ return hash;
176
+ }
177
+ /** Writes values as datasets, and answers their hashes. */
178
+ async function datasets(setup, values) {
179
+ const hashes = [];
180
+ for (const [type, value] of values)
181
+ hashes.push(await datasetWrite(setup.storage, setup.repo, value, type));
182
+ return hashes;
183
+ }
184
+ /** One stream of an execution's log, whole. */
185
+ async function logOf(setup, taskHash, inputs, result, stream) {
186
+ return (await setup.storage.logs.read(setup.repo, taskHash, inputsHash([...inputs]), result.executionId, stream, { offset: 0, limit: 1 << 24 })).data;
187
+ }
188
+ /** An execution's record. */
189
+ function recordOf(setup, taskHash, inputs, executionId) {
190
+ return setup.storage.refs.executionGet(setup.repo, taskHash, inputsHash([...inputs]), executionId);
191
+ }
192
+ /** An execution's owner. */
193
+ function ownerOf(setup, taskHash, inputs, executionId) {
194
+ return setup.storage.refs.executionOwnerRead(setup.repo, taskHash, inputsHash([...inputs]), executionId);
195
+ }
196
+ /**
197
+ * Records an attempt of a task over inputs running, owned as given, as a
198
+ * runner records one, and answers its record.
199
+ */
200
+ async function runningAs(setup, taskHash, inputHashes, owner) {
201
+ const ids = { inHash: inputsHash(inputHashes), executionId: uuidv7(), startTime: Date.now() };
202
+ const attempt = new ExecutionAttempt(setup.storage, setup.repo, taskHash, inputHashes, ids, false);
203
+ const startedAt = new Date();
204
+ await attempt.recordOwner(owner, startedAt);
205
+ await attempt.recordRunning(owner ?? { pid: 0n, pidStartTime: 0n, bootId: '' }, startedAt);
206
+ const record = await recordOf(setup, taskHash, inputHashes, ids.executionId);
207
+ if (record?.type !== 'running')
208
+ throw new AssertionError(`the attempt is recorded ${record?.type}, not running`);
209
+ return record.value;
210
+ }
211
+ /** Waits until `holds` does, checking every few milliseconds. */
212
+ async function until(what, holds, ms = 30_000) {
213
+ const deadline = Date.now() + ms;
214
+ while (!(await holds())) {
215
+ if (Date.now() > deadline)
216
+ throw new AssertionError(`waited ${ms / 1000} s for ${what}`);
217
+ await new Promise((resolve) => setTimeout(resolve, 5));
218
+ }
219
+ }
220
+ /** What a promise settles to, or a failure naming what was awaited once it
221
+ * has not settled in time: a run that ignores what should end it fails its
222
+ * case, rather than holding it. */
223
+ async function settled(what, promise, ms = 30_000) {
224
+ let timer;
225
+ const late = new Promise((_resolve, reject) => {
226
+ timer = setTimeout(() => reject(new AssertionError(`waited ${ms / 1000} s for ${what}`)), ms);
227
+ });
228
+ try {
229
+ return await Promise.race([promise, late]);
230
+ }
231
+ finally {
232
+ clearTimeout(timer);
233
+ }
234
+ }
235
+ /** A program's IR bundle, as a call is given it. */
236
+ function ir(fn) {
237
+ return encodeEastIR(fn.toIR());
238
+ }
239
+ /** A detached call of a program over values, on a runner, under limits. */
240
+ function call(fn, args, runner = PLATFORM_FREE, limits = {}) {
241
+ return { bodyIr: ir(fn), args, runner, limits: { ...LIMITS, ...limits } };
242
+ }
243
+ /** Creates the case's workspace and deploys the fixture package to it, its
244
+ * records' indexes built on the runner. */
245
+ async function deploy(setup, runner) {
246
+ await workspaceCreate(setup.storage, setup.repo, WORKSPACE);
247
+ await workspaceDeploy(setup.storage, setup.repo, WORKSPACE, FIXTURE_PACKAGE, FIXTURE_VERSION, { runner });
248
+ }
249
+ /**
250
+ * Wraps the workers a pool starts to count their starts and their
251
+ * terminations, handing everything else through.
252
+ */
253
+ function counting(counts) {
254
+ return (start) => {
255
+ const worker = start();
256
+ counts.started++;
257
+ return {
258
+ postMessage: (message, transfer) => worker.postMessage(message, transfer),
259
+ get onmessage() {
260
+ return worker.onmessage;
261
+ },
262
+ set onmessage(handler) {
263
+ worker.onmessage = handler;
264
+ },
265
+ get onerror() {
266
+ return worker.onerror;
267
+ },
268
+ set onerror(handler) {
269
+ worker.onerror = handler;
270
+ },
271
+ terminate: () => {
272
+ counts.terminated++;
273
+ worker.terminate();
274
+ },
275
+ };
276
+ };
277
+ }
278
+ /**
279
+ * The storage, its object store telling `heard` of each object read whole:
280
+ * what shows a delivery staged by ranges, never whole.
281
+ */
282
+ function readsWhole(storage, heard) {
283
+ const objects = new Proxy(storage.objects, {
284
+ get(target, property) {
285
+ if (property === 'read') {
286
+ return (repo, hash) => {
287
+ heard(hash);
288
+ return target.read(repo, hash);
289
+ };
290
+ }
291
+ const value = Reflect.get(target, property);
292
+ return typeof value === 'function' ? value.bind(target) : value;
293
+ },
294
+ });
295
+ return { ...storage, objects, validateRepository: (repo) => storage.validateRepository(repo), runStates: (repo) => storage.runStates(repo) };
296
+ }
297
+ /** How many of a split task's pieces' rows fall at each key's remainder of
298
+ * 97, as `split_counts` counts them: the rows decoded from each piece. */
299
+ async function countedByRemainder(setup, pieces) {
300
+ const counts = new SortedMap([], compareFor(IntegerType));
301
+ for (const piece of pieces) {
302
+ for (const [key] of decodeBeast2For(SalesType)(await readDatasetWhole(setup.storage, setup.repo, piece))) {
303
+ const remainder = key % 97n;
304
+ counts.set(remainder, (counts.get(remainder) ?? 0n) + 1n);
305
+ }
306
+ }
307
+ return counts;
308
+ }
309
+ /** `n` rows keyed `0 … n-1`, each valued its key. */
310
+ function salesOf(n) {
311
+ return new SortedMap(Array.from({ length: n }, (_, i) => [BigInt(i), BigInt(i)]), compareFor(IntegerType));
312
+ }
313
+ /** How many of `0 … n-1` fall at each remainder of `by`, as a task that
314
+ * counts them by remainder counts them. */
315
+ function remainders(n, by) {
316
+ const counts = new SortedMap([], compareFor(IntegerType));
317
+ for (let i = 0; i < n; i++) {
318
+ const key = BigInt(i % by);
319
+ counts.set(key, (counts.get(key) ?? 0n) + 1n);
320
+ }
321
+ return counts;
322
+ }
323
+ // =============================================================================
324
+ // The programs a call runs
325
+ // =============================================================================
326
+ /** `x × 2`. */
327
+ const double = East.function([IntegerType], IntegerType, ($, x) => x.multiply(2n));
328
+ /** Each element doubled: a collection the call returns. */
329
+ const doubleEach = East.function([EventsType], EventsType, ($, xs) => xs.map(($, x) => x.multiply(2n)));
330
+ /** The numbers `0 … n-1` written one after another: a String that does not
331
+ * compress to nothing. */
332
+ const digits = East.function([IntegerType], StringType, ($, n) => {
333
+ const out = $.let('');
334
+ const i = $.let(0n);
335
+ $.while(East.less(i, n), ($) => {
336
+ $.assign(out, East.str `${out}${i}`);
337
+ $.assign(i, i.add(1n));
338
+ });
339
+ return out;
340
+ });
341
+ /** Writes a line to stdout for each number below `n`, then `done` to stderr. */
342
+ const lines = East.function([IntegerType], IntegerType, ($, n) => {
343
+ const i = $.let(0n);
344
+ $.while(East.less(i, n), ($) => {
345
+ $(Console.log(East.str `line ${i}`));
346
+ $.assign(i, i.add(1n));
347
+ });
348
+ $(Console.error('done'));
349
+ return n;
350
+ });
351
+ /** Refuses whatever it is given. */
352
+ const refusing = East.function([IntegerType], IntegerType, ($, n) => $.error(East.str `refused ${n}`));
353
+ /** Waits for its host to say it may go on: until its time runs out, or its
354
+ * host releases it. */
355
+ const waiting = East.asyncFunction([], NullType, ($) => {
356
+ $(test_wait());
357
+ });
358
+ /** Its text, echoed by its host through the port its worker was handed. */
359
+ const echoing = East.asyncFunction([StringType], StringType, ($, text) => test_host_echo(text));
360
+ /** Closes its own worker, as a worker closes itself, and never returns. */
361
+ const exiting = East.asyncFunction([], NullType, ($) => {
362
+ $(test_exit());
363
+ });
364
+ /** How many words. */
365
+ const countWords = East.function([WordsType], IntegerType, ($, words) => words.size());
366
+ /** Counts for ever, never yielding its thread. */
367
+ const runaway = East.function([], IntegerType, ($) => {
368
+ const i = $.let(0n);
369
+ $.while(true, ($) => {
370
+ $.assign(i, i.add(1n));
371
+ });
372
+ return i;
373
+ });
374
+ // =============================================================================
375
+ // The cases
376
+ // =============================================================================
377
+ /**
378
+ * The runner's cases.
379
+ */
380
+ export const runnerCases = [
381
+ {
382
+ name: 'runs a task of every output kind, owned by the tab\'s session, storing each output as the value path writes it',
383
+ run: async (setup) => {
384
+ const runner = setup.runner(setup.pool());
385
+ const events = Array.from({ length: 2500 }, (_, i) => BigInt(i));
386
+ const cases = [
387
+ {
388
+ task: 'lengths', inputs: [[WordsType, ['pear', 'fig', 'apple']]], type: CountsType,
389
+ value: new SortedMap([['apple', 5n], ['fig', 3n], ['pear', 4n]], compareFor(StringType)),
390
+ },
391
+ { task: 'count', inputs: [[WordsType, ['pear', 'fig', 'apple']]], type: IntegerType, value: 3n },
392
+ { task: 'sums', inputs: [[EventsType, events]], type: EventsType, value: events.map((_, i) => (BigInt(i) * BigInt(i + 1)) / 2n) },
393
+ { task: 'distinct', inputs: [[EventsType, events]], type: SetType(IntegerType), value: new SortedSet([0n, 1n, 2n, 3n, 4n], compareFor(IntegerType)) },
394
+ {
395
+ task: 'doubled', inputs: [[SalesType, salesOf(300)]], type: IntDictType,
396
+ value: new SortedMap([...salesOf(300)].map(([key, amount]) => [key, amount * 2n]), compareFor(IntegerType)),
397
+ },
398
+ { task: 'total', inputs: [[EventsType, events]], type: IntegerType, value: (2499n * 2500n) / 2n },
399
+ { task: 'nothing', inputs: [], type: IntDictType, value: new SortedMap([], compareFor(IntegerType)) },
400
+ ];
401
+ for (const { task, inputs, type, value } of cases) {
402
+ const taskHash = await taskHashOf(setup, task);
403
+ const inputHashes = await datasets(setup, inputs);
404
+ const result = await runner.execute(setup.storage, taskHash, inputHashes);
405
+ equal(result.state, 'success', `${task}: ${result.error ?? ''}`);
406
+ equal(result.outputHash, await datasetWrite(setup.storage, setup.repo, value, type), `${task}'s output is what the value path stores for the same value`);
407
+ equal(result.cached, false, task);
408
+ equal(result.peakBytes, undefined, `${task}: a browser measures no memory`);
409
+ const record = await recordOf(setup, taskHash, inputHashes, result.executionId);
410
+ ok(record?.type === 'success', `${task} is recorded success, not ${record?.type}`);
411
+ equal(record.value.outputHash, result.outputHash);
412
+ equal(record.value.unit, false, `${task} is a task's own execution`);
413
+ equal(record.value.peakBytes.type, 'none', `${task}'s record names no peak`);
414
+ const owner = await ownerOf(setup, taskHash, inputHashes, result.executionId);
415
+ ok(owner !== null && equalFor(ExecutionOwnerType)(owner, { pid: 0n, pidStartTime: 0n, bootId: setup.storage.adapters.locks.session }), `${task}'s owner is the tab's session`);
416
+ }
417
+ // Served from the execution cache when it ran before.
418
+ const taskHash = await taskHashOf(setup, 'count');
419
+ const inputHashes = await datasets(setup, [[WordsType, ['pear', 'fig', 'apple']]]);
420
+ const again = await runner.execute(setup.storage, taskHash, inputHashes);
421
+ equal(again.cached, true, 'a run over inputs it ran before is served from the cache');
422
+ equal(again.outputHash, await datasetWrite(setup.storage, setup.repo, 3n, IntegerType));
423
+ const forced = await runner.execute(setup.storage, taskHash, inputHashes, { force: true });
424
+ equal(forced.cached, false, 'a forced run runs again');
425
+ equal(forced.outputHash, again.outputHash);
426
+ },
427
+ },
428
+ {
429
+ name: 'merges a dict its unit left in several runs into one, folding the keys they share',
430
+ run: async (setup) => {
431
+ const runner = setup.runner(setup.pool());
432
+ const result = await runner.execute(setup.storage, await taskHashOf(setup, 'tallies'), []);
433
+ equal(result.state, 'success', result.error ?? '');
434
+ // 132 072 emissions of i % 1000: past the 131 072 a run holds.
435
+ equal(result.outputHash, await datasetWrite(setup.storage, setup.repo, remainders(131_072 + 1_000, 1000), IntDictType), 'the output is the one run the merge wrote');
436
+ },
437
+ },
438
+ {
439
+ name: 'records a failing program failed, exit code 1, its message and locations ending its stderr',
440
+ run: async (setup) => {
441
+ const runner = setup.runner(setup.pool());
442
+ const taskHash = await taskHashOf(setup, 'fails');
443
+ const inputHashes = await datasets(setup, [[WordsType, ['a', 'b']]]);
444
+ const result = await runner.execute(setup.storage, taskHash, inputHashes);
445
+ equal(result.state, 'failed');
446
+ equal(result.exitCode, 1, 'a failed outcome exits 1, as the runner protocol has it');
447
+ ok(/^Exit code: 1\nstderr:\nError: too many words: 2\n {2}at /.test(result.error ?? ''), `the error names the failure: ${result.error}`);
448
+ const record = await recordOf(setup, taskHash, inputHashes, result.executionId);
449
+ ok(record?.type === 'failed', `recorded ${record?.type}`);
450
+ same(IntegerType, record.value.exitCode, 1n, 'the record\'s exit code');
451
+ equal(record.value.peakBytes.type, 'none');
452
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stdout'), 'checking the words\n', 'what it wrote before it failed is in its log');
453
+ const stderr = await logOf(setup, taskHash, inputHashes, result, 'stderr');
454
+ ok(/^Error: too many words: 2\n( {2}at [^\n]+\n)+$/.test(stderr), `its stderr log is the failure and its locations, as east-node's exec writes them: ${JSON.stringify(stderr)}`);
455
+ },
456
+ },
457
+ {
458
+ name: 'writes what a unit\'s console writes to the execution\'s logs, and to its listeners, as it writes it',
459
+ run: async (setup) => {
460
+ const runner = setup.runner(setup.pool());
461
+ const taskHash = await taskHashOf(setup, 'chatty');
462
+ const inputHashes = await datasets(setup, [[WordsType, ['a', 'b']]]);
463
+ const heard = { stdout: '', stderr: '' };
464
+ const result = await runner.execute(setup.storage, taskHash, inputHashes, {
465
+ onStdout: (text) => {
466
+ heard.stdout += text;
467
+ },
468
+ onStderr: (text) => {
469
+ heard.stderr += text;
470
+ },
471
+ });
472
+ equal(result.state, 'success', result.error ?? '');
473
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stdout'), 'counting 2 words\n');
474
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stderr'), 'a line to stderr\n');
475
+ deepEqual(heard, { stdout: 'counting 2 words\n', stderr: 'a line to stderr\n' });
476
+ },
477
+ },
478
+ {
479
+ name: 'refuses a command — a custom task, or a task on the custom runtime — recording it error: a browser runs no commands',
480
+ run: async (setup) => {
481
+ const runner = setup.runner(setup.pool());
482
+ for (const task of ['command', 'custom_runtime']) {
483
+ const taskHash = await taskHashOf(setup, task);
484
+ const inputHashes = await datasets(setup, [[WordsType, ['a']]]);
485
+ const result = await runner.execute(setup.storage, taskHash, inputHashes);
486
+ equal(result.state, 'error', task);
487
+ equal(result.error, NO_COMMANDS, task);
488
+ equal(result.exitCode, undefined, `${task} ran nothing that exited`);
489
+ const record = await recordOf(setup, taskHash, inputHashes, result.executionId);
490
+ ok(record?.type === 'error' && record.value.message === NO_COMMANDS, `${task} is recorded error, naming why: ${record?.type}`);
491
+ equal(await ownerOf(setup, taskHash, inputHashes, result.executionId), null, `${task} never ran, so no owner is recorded`);
492
+ }
493
+ },
494
+ },
495
+ {
496
+ name: 'fails a unit that lists a platform package its worker does not serve, naming the package',
497
+ run: async (setup) => {
498
+ const runner = setup.runner(setup.pool());
499
+ const result = await runner.execute(setup.storage, await taskHashOf(setup, 'io_task'), await datasets(setup, [[WordsType, ['a']]]));
500
+ equal(result.state, 'failed');
501
+ equal(result.exitCode, 1);
502
+ ok(/the platform package @elaraai\/east-node-io is not served to units in this browser/.test(result.error ?? ''), `the failure names the package: ${result.error}`);
503
+ },
504
+ },
505
+ {
506
+ name: 'fails a unit that calls a platform function its packages do not provide — FileSystem.readFile — naming the function',
507
+ run: async (setup) => {
508
+ const runner = setup.runner(setup.pool());
509
+ const result = await runner.execute(setup.storage, await taskHashOf(setup, 'reads_file'), await datasets(setup, [[WordsType, ['a']]]));
510
+ equal(result.state, 'failed');
511
+ equal(result.exitCode, 1);
512
+ ok(/Platform function 'fs_read_file' not found/.test(result.error ?? ''), `the failure names FileSystem.readFile's platform function: ${result.error}`);
513
+ },
514
+ },
515
+ {
516
+ name: 'runs a task an app\'s own platform package answers, beside east-node-std\'s',
517
+ run: async (setup) => {
518
+ const runner = setup.runner(setup.pool());
519
+ const result = await runner.execute(setup.storage, await taskHashOf(setup, 'greets'), await datasets(setup, [[WordsType, ['world']]]));
520
+ equal(result.state, 'success', result.error ?? '');
521
+ equal(result.outputHash, await datasetWrite(setup.storage, setup.repo, 'hello, world', StringType));
522
+ },
523
+ },
524
+ {
525
+ name: 'splits a task over its input into pieces and two levels of merges, and serves its relaunch from the cache',
526
+ run: async (setup) => {
527
+ setup.pieceBytes(64);
528
+ const runner = setup.runner(setup.pool());
529
+ const taskHash = await taskHashOf(setup, 'split_counts');
530
+ const rows = 40_000;
531
+ const inputHashes = await datasets(setup, [[SalesType, salesOf(rows)]]);
532
+ const expected = await datasetWrite(setup.storage, setup.repo, remainders(rows, 97), IntDictType);
533
+ const progress = [];
534
+ const result = await runner.execute(setup.storage, taskHash, inputHashes, {
535
+ onPartitionProgress: (p) => progress.push(`${p.phase} ${p.state}`),
536
+ });
537
+ equal(result.state, 'success', result.error ?? '');
538
+ equal(result.outputHash, expected, 'the assembled output is what the value path stores');
539
+ const log = (await logOf(setup, taskHash, inputHashes, result, 'stdout')).split('\n');
540
+ const pieces = log.filter((line) => /^piece \d+\/\d+ completed task=/.test(line)).length;
541
+ equal(mergeTreeLevels([pieces]), 2, `the input ran as more pieces than one merge unit takes: ${pieces}`);
542
+ // The pieces' outputs all overlap, so they merge in one group: runs of
543
+ // 32 at the first level, and their outputs at the second.
544
+ const first = mergeTreeGroups(Array.from({ length: pieces }, (_, i) => i)).filter((run) => run.length >= 2).length;
545
+ const merges = log.filter((line) => line.startsWith('merge ')).map((line) => line.split(' task=')[0]).sort();
546
+ deepEqual(merges, [
547
+ ...Array.from({ length: first }, (_, i) => `merge level 1/2 unit ${i + 1}/${first} completed`),
548
+ 'merge level 2/2 unit 1/1 completed',
549
+ ].sort(), 'the pieces merged in two levels');
550
+ ok(progress.includes('partition started') && progress.includes('partition completed') && progress.includes('merge completed'), `each unit's progress is reported: ${[...new Set(progress)].join(', ')}`);
551
+ const own = await recordOf(setup, taskHash, inputHashes, result.executionId);
552
+ ok(own?.type === 'success' && own.value.plan.type === 'some', 'the task\'s own record names its last stage');
553
+ // Its relaunch is served from the cache: the task's own execution, and,
554
+ // with that record gone, every unit it ran.
555
+ const again = await runner.execute(setup.storage, taskHash, inputHashes);
556
+ equal(again.cached, true);
557
+ equal(again.outputHash, expected);
558
+ await setup.storage.refs.executionDelete(setup.repo, taskHash, inputsHash(inputHashes), result.executionId);
559
+ const relaunch = await runner.execute(setup.storage, taskHash, inputHashes);
560
+ equal(relaunch.state, 'success', relaunch.error ?? '');
561
+ equal(relaunch.cached, false, 'the task runs again');
562
+ equal(relaunch.outputHash, expected);
563
+ const relaunched = (await logOf(setup, taskHash, inputHashes, relaunch, 'stdout')).split('\n').filter((line) => /^(piece|merge) /.test(line));
564
+ equal(relaunched.length, pieces + first + 1, 'every unit settles again');
565
+ ok(relaunched.every((line) => / cached task=/.test(line)), `every unit is served from the cache:\n${relaunched.join('\n')}`);
566
+ },
567
+ },
568
+ {
569
+ name: 'runs a split task\'s units as the dataflow runs each — pieces, and a merge of their outputs — recorded as units and served from the cache',
570
+ run: async (setup) => {
571
+ setup.pieceBytes(64);
572
+ const runner = setup.runner(setup.pool());
573
+ const { storage, repo } = setup;
574
+ const taskHash = await taskHashOf(setup, 'split_counts');
575
+ const inputHashes = await datasets(setup, [[SalesType, salesOf(5_000)]]);
576
+ const task = decodeTaskObject(await storage.objects.read(repo, taskHash));
577
+ const plan = await planPieces(storage, repo, task.inputs, inputHashes, pieceSizes());
578
+ ok(plan.pieces.length >= 2, `the input is ${plan.pieces.length} pieces`);
579
+ const pieces = plan.pieces.slice(0, 2);
580
+ const outputs = [];
581
+ for (const inputs of pieces) {
582
+ const result = await runner.executeUnit(storage, taskHash, { inputs, merge: null, own: false });
583
+ equal(result.state, 'success', result.error ?? '');
584
+ equal(result.outputHash, await datasetWrite(storage, repo, await countedByRemainder(setup, inputs), IntDictType), 'a piece counts its own rows');
585
+ const record = await recordOf(setup, taskHash, inputs, result.executionId);
586
+ ok(record?.type === 'success' && record.value.unit, 'its record says it is a unit of a split task');
587
+ outputs.push(result.outputHash);
588
+ }
589
+ const merge = { inputs: ['merge', ...outputs], merge: { parts: outputs, range: null }, own: false };
590
+ const merged = await runner.executeUnit(storage, taskHash, merge);
591
+ equal(merged.state, 'success', merged.error ?? '');
592
+ equal(merged.outputHash, await datasetWrite(storage, repo, await countedByRemainder(setup, pieces.map((inputs) => inputs[0])), IntDictType), 'a merge folds the keys its parts share');
593
+ const record = await recordOf(setup, taskHash, merge.inputs, merged.executionId);
594
+ ok(record?.type === 'success' && record.value.unit, 'its record says it is a unit of a split task');
595
+ const again = await runner.executeUnit(storage, taskHash, merge);
596
+ equal(again.cached, true, 'a unit that ran before is served from the cache');
597
+ equal(again.outputHash, merged.outputHash);
598
+ },
599
+ },
600
+ {
601
+ name: 'cancels a run its signal aborts: the unit\'s worker is terminated and replaced, and the execution recorded cancelled',
602
+ run: async (setup) => {
603
+ const counts = { started: 0, terminated: 0 };
604
+ const runner = setup.runner(setup.pool({ width: 1, units: counting(counts) }));
605
+ const taskHash = await taskHashOf(setup, 'waits');
606
+ const inputHashes = await datasets(setup, [[WordsType, ['a', 'b', 'c']]]);
607
+ const controller = new AbortController();
608
+ const running = runner.execute(setup.storage, taskHash, inputHashes, { signal: controller.signal });
609
+ // The unit waits on its host, mid-program.
610
+ await until('the unit to wait on its host', () => setup.host.asked.includes('wait'));
611
+ const ids = await setup.storage.refs.executionListIds(setup.repo, taskHash, inputsHash(inputHashes));
612
+ equal(ids.length, 1);
613
+ equal((await recordOf(setup, taskHash, inputHashes, ids[0]))?.type, 'running', 'it is recorded running while it runs');
614
+ controller.abort();
615
+ const result = await settled('the run to end once aborted', running);
616
+ equal(result.state, 'error');
617
+ equal(result.cancelled, true);
618
+ equal((await recordOf(setup, taskHash, inputHashes, result.executionId))?.type, 'cancelled');
619
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stdout'), 'waiting for the host\n', 'what it wrote is in its log');
620
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stderr'), 'e3: cancelled: e3 stopped the runner because the run was aborted\n', 'and why it stopped');
621
+ equal(counts.terminated, 1, 'its worker was terminated');
622
+ // The next unit runs on a worker started in its place.
623
+ const next = await runner.execute(setup.storage, await taskHashOf(setup, 'count'), await datasets(setup, [[WordsType, ['x']]]));
624
+ equal(next.state, 'success', next.error ?? '');
625
+ equal(counts.started, 2, 'a worker was started in its place');
626
+ },
627
+ },
628
+ {
629
+ name: 'records a run aborted while its unit waits for a worker cancelled, never started and owned by no one',
630
+ run: async (setup) => {
631
+ const runner = setup.runner(setup.pool({ width: 1 }));
632
+ const busy = runner.execute(setup.storage, await taskHashOf(setup, 'waits'), await datasets(setup, [[WordsType, ['a']]]));
633
+ await until('the first unit to wait on its host', () => setup.host.asked.includes('wait'));
634
+ const controller = new AbortController();
635
+ const taskHash = await taskHashOf(setup, 'count');
636
+ const inputHashes = await datasets(setup, [[WordsType, ['b']]]);
637
+ const waited = [];
638
+ const queued = runner.execute(setup.storage, taskHash, inputHashes, {
639
+ signal: controller.signal,
640
+ onWaiting: (needs) => waited.push(needs),
641
+ });
642
+ await until('the second unit to wait for a worker', () => waited.length > 0);
643
+ controller.abort();
644
+ const result = await settled('the waiting run to end once aborted', queued);
645
+ equal(result.cancelled, true);
646
+ deepEqual(waited, [0, null], 'it waited for a core alone, and stopped waiting');
647
+ equal((await recordOf(setup, taskHash, inputHashes, result.executionId))?.type, 'cancelled');
648
+ equal(await logOf(setup, taskHash, inputHashes, result, 'stderr'), 'e3: cancelled: e3 did not start the runner because the run was aborted\n');
649
+ equal(await ownerOf(setup, taskHash, inputHashes, result.executionId), null, 'it never ran, so no owner is recorded');
650
+ setup.host.release();
651
+ equal((await busy).state, 'success');
652
+ },
653
+ },
654
+ {
655
+ name: 'runs as many units at once as its pool is wide, and the rest in the order they began to wait',
656
+ run: async (setup) => {
657
+ const runner = setup.runner(setup.pool({ width: 2 }));
658
+ const taskHash = await taskHashOf(setup, 'waits');
659
+ const events = [];
660
+ const runs = [1, 2, 3, 4].map(async (n) => {
661
+ const inputHashes = await datasets(setup, [[WordsType, Array.from({ length: n }, (_, i) => `word ${i}`)]]);
662
+ return runner.execute(setup.storage, taskHash, inputHashes, {
663
+ onWaiting: (needs) => events.push(`${n} ${needs === null ? 'placed' : 'waiting'}`),
664
+ });
665
+ });
666
+ await until('two units to wait on their host, and two for a worker', () => setup.host.asked.length === 2 && events.length === 2);
667
+ deepEqual(setup.host.asked, ['wait', 'wait'], 'two units run: as many as the pool is wide');
668
+ setup.host.release();
669
+ for (const result of await Promise.all(runs))
670
+ equal(result.state, 'success', result.error ?? '');
671
+ const began = events.filter((event) => event.endsWith(' waiting')).map((event) => event.split(' ')[0]);
672
+ const placed = events.filter((event) => event.endsWith(' placed')).map((event) => event.split(' ')[0]);
673
+ equal(began.length, 2);
674
+ deepEqual(placed, began, 'the units that waited ran in the order they began to wait');
675
+ },
676
+ },
677
+ {
678
+ name: 'calls a function within its limits: a value, a collection spliced from its segments, and a stored dataset as an argument',
679
+ run: async (setup) => {
680
+ const runner = setup.runner(setup.pool());
681
+ const { storage } = setup;
682
+ // Bytes that are their buffer whole, which a message would move rather
683
+ // than copy.
684
+ const arg = encodeInteger(21n).slice();
685
+ const spec = { ...call(double, [arg]), bodyIr: ir(double).slice() };
686
+ const sizes = [spec.bodyIr.length, arg.length];
687
+ const doubled = await runner.runDetached(spec, { storage });
688
+ ok(doubled.kind === 'success', `a value: ${doubled.kind}`);
689
+ same(IntegerType, decodeInteger(doubled.value), 42n, 'its value');
690
+ deepEqual([doubled.stdout, doubled.stderr, doubled.stdoutTruncated, doubled.stderrTruncated], ['', '', false, false]);
691
+ deepEqual([spec.bodyIr.length, arg.length], sizes, 'the caller keeps its bytes: the worker was given copies');
692
+ const events = Array.from({ length: 3000 }, (_, i) => BigInt(i));
693
+ const expected = events.map((x) => x * 2n);
694
+ const each = await runner.runDetached(call(doubleEach, [encodeBeast2For(EventsType)(events)]), { storage });
695
+ ok(each.kind === 'success', `a collection: ${each.kind}`);
696
+ same(EventsType, decodeBeast2For(EventsType)(each.value), expected, 'its segments spliced into its value');
697
+ const stored = await runner.runDetached(call(doubleEach, [{ dataset: await datasetWrite(storage, setup.repo, events, EventsType) }]), { storage });
698
+ ok(stored.kind === 'success', `a stored dataset: ${stored.kind}`);
699
+ same(EventsType, decodeBeast2For(EventsType)(stored.value), expected, 'a stored dataset is staged as a task\'s input is');
700
+ await rejects(() => runner.runDetached(call(doubleEach, [{ dataset: 'a'.repeat(64) }])), { message: /runDetached needs options\.storage/ }, 'a stored dataset is staged from a repository');
701
+ },
702
+ },
703
+ {
704
+ name: 'calls a function past each limit: its value or its collection too large, and its logs kept to their tails',
705
+ run: async (setup) => {
706
+ const runner = setup.runner(setup.pool());
707
+ const { storage } = setup;
708
+ const text = Array.from({ length: 500 }, (_, i) => `${i}`).join('');
709
+ const whole = await runner.runDetached(call(digits, [encodeInteger(500n)]), { storage });
710
+ ok(whole.kind === 'success', `within its limit: ${whole.kind}`);
711
+ same(StringType, decodeString(whole.value), text, 'its value');
712
+ const value = await runner.runDetached(call(digits, [encodeInteger(500n)], PLATFORM_FREE, { maxResultBytes: 64 }), { storage });
713
+ ok(value.kind === 'too_large' && value.limit === 64 && value.bytes === whole.value.length, `a value over its limit is too large, by its bytes: ${value.kind}`);
714
+ // A collection is weighed by its segments, as the Writer writes them for
715
+ // the same value.
716
+ const events = Array.from({ length: 3000 }, (_, i) => BigInt(i));
717
+ const doubledEvents = await readManifest(storage, setup.repo, await datasetWrite(storage, setup.repo, events.map((x) => x * 2n), EventsType));
718
+ ok(doubledEvents !== null);
719
+ const weight = manifestByteSize(doubledEvents);
720
+ const fits = await runner.runDetached(call(doubleEach, [encodeBeast2For(EventsType)(events)], PLATFORM_FREE, { maxResultBytes: weight }), { storage });
721
+ ok(fits.kind === 'success', `a collection of its limit's weight: ${fits.kind}`);
722
+ const collection = await runner.runDetached(call(doubleEach, [encodeBeast2For(EventsType)(events)], PLATFORM_FREE, { maxResultBytes: weight - 1 }), { storage });
723
+ ok(collection.kind === 'too_large' && collection.limit === weight - 1 && collection.bytes === weight, `a collection over its limit is too large, by its segments' bytes, never spliced: ${collection.kind}`);
724
+ const logged = await runner.runDetached(call(lines, [encodeInteger(100n)], STANDARD, { maxLogBytes: 32 }), { storage });
725
+ ok(logged.kind === 'success', `${logged.kind}`);
726
+ same(IntegerType, decodeInteger(logged.value), 100n, 'its value');
727
+ equal(logged.stdoutTruncated, true, 'its stdout was cut');
728
+ ok(utf8.encode(logged.stdout).length <= 32 && logged.stdout.endsWith('line 98\nline 99\n'), `its stdout is its tail: ${JSON.stringify(logged.stdout)}`);
729
+ deepEqual([logged.stderr, logged.stderrTruncated], ['done\n', false], 'its stderr was not cut');
730
+ },
731
+ },
732
+ {
733
+ name: 'calls a function that fails, one a browser cannot run and one aborted, answering each failed',
734
+ run: async (setup) => {
735
+ const runner = setup.runner(setup.pool());
736
+ const { storage } = setup;
737
+ const failed = await runner.runDetached(call(refusing, [encodeInteger(7n)]), { storage });
738
+ ok(failed.kind === 'failed' && failed.exitCode === 1, `a failure exits 1: ${failed.kind}`);
739
+ // The program is written here, so it carries the locations East finds
740
+ // where the case runs: in a page's bundle, none.
741
+ ok(/^Error: refused 7\n( {2}at [^\n]+\n)*$/.test(failed.stderr), `its stderr is the failure, as east-node's exec writes it: ${JSON.stringify(failed.stderr)}`);
742
+ const custom = await runner.runDetached(call(double, [encodeInteger(1n)], variant('custom', { command: ['east-node', 'run'] })), { storage });
743
+ ok(custom.kind === 'failed' && custom.exitCode === -1, `a command is not run: ${custom.kind}`);
744
+ equal(custom.stderr, NO_COMMANDS);
745
+ const controller = new AbortController();
746
+ const aborting = runner.runDetached(call(waiting, [], WITH_TEST), { storage, signal: controller.signal });
747
+ await until('the call to wait on its host', () => setup.host.asked.includes('wait'));
748
+ controller.abort();
749
+ const aborted = await aborting;
750
+ ok(aborted.kind === 'failed' && aborted.exitCode === -1, `an aborted call failed -1: ${aborted.kind}`);
751
+ },
752
+ },
753
+ {
754
+ name: 'answers a call that runs past its timeout timed out, its worker terminated and replaced',
755
+ run: async (setup) => {
756
+ const counts = { started: 0, terminated: 0 };
757
+ const runner = setup.runner(setup.pool({ width: 1, units: counting(counts) }));
758
+ const { storage } = setup;
759
+ const timedOut = await runner.runDetached(call(waiting, [], WITH_TEST, { timeoutMs: 500 }), { storage });
760
+ ok(timedOut.kind === 'timed_out' && timedOut.ms === 500, `${timedOut.kind}`);
761
+ equal(counts.terminated, 1, 'its worker was terminated');
762
+ const next = await runner.runDetached(call(double, [encodeInteger(4n)]), { storage });
763
+ ok(next.kind === 'success', `the next call runs: ${next.kind}`);
764
+ same(IntegerType, decodeInteger(next.value), 8n, 'its value');
765
+ equal(counts.started, 2, 'on a worker started in its place');
766
+ },
767
+ },
768
+ {
769
+ name: 'hands each worker the port its pool was given, through which an app\'s package reaches the host',
770
+ run: async (setup) => {
771
+ const runner = setup.runner(setup.pool());
772
+ const echoed = await runner.runDetached(call(echoing, [encodeString('ping')], WITH_TEST), { storage: setup.storage });
773
+ ok(echoed.kind === 'success', `${echoed.kind}: ${echoed.stderr}`);
774
+ same(StringType, decodeString(echoed.value), 'ping, from the host', 'the host\'s answer');
775
+ deepEqual(setup.host.asked, ['echo:ping']);
776
+ },
777
+ },
778
+ {
779
+ name: 'runs a one-shot over a workspace\'s dataset, and a split call over its pieces with then',
780
+ run: async (setup) => {
781
+ setup.pieceBytes(64);
782
+ const runner = setup.runner(setup.pool());
783
+ const { storage, repo } = setup;
784
+ await deploy(setup, runner);
785
+ await workspaceSetDataset(storage, repo, WORKSPACE, inputPath('words'), ['a', 'b', 'c'], WordsType);
786
+ const request = { bodyIr: ir(countWords), args: [variant('dataset', inputPath('words'))], runner: PLATFORM_FREE, limits: none };
787
+ const oneShot = await oneShotExecute(storage, runner, repo, WORKSPACE, request, { grant: 'any' });
788
+ ok(oneShot.outcome.type === 'success', `the one-shot: ${oneShot.outcome.type}`);
789
+ same(IntegerType, decodeInteger(oneShot.outcome.value.value), 3n, 'its value');
790
+ deepEqual(oneShot.inputs.map(({ hash }) => hash), [await datasetWrite(storage, repo, ['a', 'b', 'c'], WordsType)], 'it names the dataset it read');
791
+ const rows = 8_000;
792
+ await workspaceSetDataset(storage, repo, WORKSPACE, inputPath('sales'), salesOf(rows), SalesType);
793
+ const progress = [];
794
+ const split = {
795
+ bodyIr: ir(East.function([SalesType, FunctionType([IntegerType, IntegerType], NullType)], NullType, ($, sales, emit) => {
796
+ $.for(sales, ($, _amount, key) => {
797
+ $(emit(key.remainder(7n), 1n));
798
+ });
799
+ })),
800
+ args: [{ arg: variant('dataset', inputPath('sales')), partition: some({ by: [] }) }],
801
+ output: variant('dict', { merge: some(ir(East.function([IntegerType, IntegerType, IntegerType], IntegerType, ($, _key, a, b) => a.add(b)))) }),
802
+ then: some(ir(East.function([IntDictType, SalesType], IntegerType, ($, counts, _sales) => counts.size()))),
803
+ runner: PLATFORM_FREE,
804
+ limits: none,
805
+ };
806
+ const launched = await splitCallPrepare(storage, repo, WORKSPACE, split, { grant: 'any' });
807
+ ok('task' in launched, 'the call launched');
808
+ const outcome = await splitCallRun(storage, runner, repo, launched, { onProgress: (p) => progress.push(p.phase.type) });
809
+ ok(outcome.outcome.type === 'success', `the split call: ${outcome.outcome.type}: ${outcome.stderr}`);
810
+ same(IntegerType, decodeInteger(await readDatasetWhole(storage, repo, outcome.outcome.value.value)), 7n, 'then\'s value');
811
+ ok(outcome.output.type === 'some', 'it names the assembled output');
812
+ same(IntDictType, decodeBeast2For(IntDictType)(await readDatasetWhole(storage, repo, outcome.output.value)), remainders(rows, 7), 'the pieces\' outputs, merged');
813
+ ok(progress.includes('partition') && progress.includes('merge'), `its pieces ran and merged: ${[...new Set(progress)].join(', ')}`);
814
+ },
815
+ },
816
+ {
817
+ name: 'builds a record\'s index at deploy, and runs its mutations, the index maintained by each commit',
818
+ run: async (setup) => {
819
+ const runner = setup.runner(setup.pool());
820
+ const { storage, repo } = setup;
821
+ await deploy(setup, runner);
822
+ const deployed = await storage.datasets.read(repo, WORKSPACE, 'records/counts');
823
+ ok(deployed?.type === 'value', 'the record holds its initial state');
824
+ deepEqual(await recordIndexNames(storage, repo, deployed.value.hash), ['by_count'], 'its index was built at deploy');
825
+ for (const [word, n] of [['apple', 2n], ['pear', 1n], ['apple', 3n]]) {
826
+ const outcome = await recordMutate(storage, runner, repo, WORKSPACE, 'counts', 'add', [encodeString(word), encodeInteger(n)], { actor: 'e3-web' });
827
+ equal(outcome.kind, 'committed', `adding ${n} ${word}: ${JSON.stringify(outcome.kind === 'failed' ? outcome.stderr : outcome.kind)}`);
828
+ }
829
+ const ref = await storage.datasets.read(repo, WORKSPACE, 'records/counts');
830
+ ok(ref?.type === 'value');
831
+ same(CountsType, decodeBeast2For(CountsType)(await readDatasetWhole(storage, repo, ref.value.hash)), new SortedMap([['apple', 5n], ['pear', 1n]], compareFor(StringType)), 'the record holds what its mutations wrote');
832
+ const index = (await readRecordState(storage, repo, ref.value.hash)).indexes.get('by_count');
833
+ ok(index !== undefined, 'the state names its index');
834
+ const manifest = await readManifest(storage, repo, index.manifest);
835
+ ok(manifest !== null);
836
+ equal(manifestElementCount(manifest), 2, 'its index holds an entry for each row');
837
+ },
838
+ },
839
+ {
840
+ name: 'takes a delivery in through intake units: by pieces with an index, whole without, and refused above its whole-intake limit',
841
+ run: async (setup) => {
842
+ setup.pieceBytes(4096);
843
+ const runner = setup.runner(setup.pool());
844
+ const { storage, repo } = setup;
845
+ equal(runner.wholeIntakeLimit, 256 * 1024 * 1024, 'a runner takes in up to 256 MiB whole unless told otherwise');
846
+ equal(DEFAULT_WHOLE_INTAKE_LIMIT, runner.wholeIntakeLimit);
847
+ const type = toEastTypeValue(SalesType);
848
+ // An indexed delivery is taken in a piece of its segments at a time,
849
+ // each staged by ranged reads of its run, never the delivery whole.
850
+ const rows = salesOf(20_000);
851
+ const delivery = encodeBeast2PagedFor(SalesType)(rows);
852
+ const object = await storage.objects.write(repo, delivery);
853
+ const pieces = [];
854
+ const read = [];
855
+ const taken = await intakeDelivery(readsWhole(storage, (hash) => read.push(hash)), repo, runner, { object }, type, object, delivery.length, {
856
+ onProgress: (progress) => pieces.push(progress.pieces.total),
857
+ });
858
+ equal(taken.hash, await datasetWrite(storage, repo, rows, SalesType), 'it is stored as the Writer stores the same rows');
859
+ deepEqual(taken.runners, [WEB_RUNNER]);
860
+ ok(taken.pieces.length > 1 && pieces[0] === taken.pieces.length, `it was taken in as ${taken.pieces.length} pieces`);
861
+ equal(read.filter((hash) => hash === object).length, 0, 'no piece read the delivery whole');
862
+ // One with no index cannot be cut: it is taken in whole, under the limit.
863
+ const plain = encodeBeast2For(SalesType)(salesOf(3_000));
864
+ ok(plain.length > 1024, `the delivery is ${plain.length} bytes`);
865
+ const plainObject = await storage.objects.write(repo, plain);
866
+ const whole = await intakeDelivery(readsWhole(storage, (hash) => read.push(hash)), repo, runner, { object: plainObject }, type, plainObject, plain.length);
867
+ equal(whole.hash, await datasetWrite(storage, repo, salesOf(3_000), SalesType));
868
+ deepEqual(whole.pieces, [], 'taken in whole, by one unit');
869
+ equal(read.filter((hash) => hash === plainObject).length, 1, 'which read it whole');
870
+ const bounded = setup.runner(setup.pool(), { wholeIntakeLimit: 1024 });
871
+ await rejects(() => intakeDelivery(storage, repo, bounded, { object: plainObject }, type, plainObject, plain.length), {
872
+ name: 'DeliveryRefusedError',
873
+ message: /the delivery has no index that reads, so it is taken in whole, by one unit, and at \d+ bytes it is more than the 1024 a unit of this runner takes in whole — write it again with a current Writer, which indexes it/,
874
+ }, 'above its limit, it is refused before any unit runs, naming the fix');
875
+ // A unit refuses a delivery that is not of its declared type.
876
+ await rejects(() => runner.intake(storage, { source: { object }, type: toEastTypeValue(WordsType) }), {
877
+ name: 'DeliveryRefusedError',
878
+ message: /^east-web refused the delivery: /,
879
+ });
880
+ await rejects(() => runner.intake(storage, { source: { file: '/deliveries/sales.beast2' }, type }), {
881
+ message: /a browser's runner cannot read/,
882
+ }, 'a file is no delivery a browser takes in');
883
+ },
884
+ },
885
+ {
886
+ name: 'judges an execution recorded running alive while its owner\'s session lives, and its probe takes one whose session ended for interrupted',
887
+ run: async (setup) => {
888
+ const runner = setup.runner(setup.pool());
889
+ const taskHash = await taskHashOf(setup, 'count');
890
+ const inputs = (word) => datasets(setup, [[WordsType, [word]]]);
891
+ const alive = (inputHashes, running) => runner.executionAlive(setup.storage, taskHash, inputsHash(inputHashes), running);
892
+ const tab = (session) => ({ pid: 0n, pidStartTime: 0n, bootId: session });
893
+ const own = await inputs('own');
894
+ equal(await alive(own, await runningAs(setup, taskHash, own, tab(setup.storage.adapters.locks.session))), true, 'owned by this tab\'s session');
895
+ const other = await setup.openSession();
896
+ const elsewhere = await inputs('elsewhere');
897
+ const elsewhereRunning = await runningAs(setup, taskHash, elsewhere, tab(other.session));
898
+ equal(await alive(elsewhere, elsewhereRunning), true, 'owned by another tab\'s session, which lives');
899
+ const pidOwned = await inputs('pid');
900
+ equal(await alive(pidOwned, await runningAs(setup, taskHash, pidOwned, { pid: 7n, pidStartTime: 1n, bootId: other.session })), false, 'owned by a process, which no tab is');
901
+ const unowned = await inputs('unowned');
902
+ equal(await alive(unowned, await runningAs(setup, taskHash, unowned, null)), false, 'owned by no one');
903
+ // A probe leaves one another tab runs as it is, and runs the task beside it.
904
+ const beside = await runner.execute(setup.storage, taskHash, elsewhere);
905
+ equal(beside.state, 'success', beside.error ?? '');
906
+ equal((await recordOf(setup, taskHash, elsewhere, elsewhereRunning.executionId))?.type, 'running', 'an execution another tab runs is left running');
907
+ // And takes one whose owner's session has ended for interrupted.
908
+ const ended = await inputs('ended');
909
+ const endedRunning = await runningAs(setup, taskHash, ended, tab(other.session));
910
+ await other.close();
911
+ equal(await alive(ended, endedRunning), false, 'its owner\'s session has ended');
912
+ const again = await runner.execute(setup.storage, taskHash, ended);
913
+ equal(again.state, 'success', again.error ?? '');
914
+ equal(again.cached, false);
915
+ equal((await recordOf(setup, taskHash, ended, endedRunning.executionId))?.type, 'interrupted', 'the probe took it for interrupted');
916
+ },
917
+ },
918
+ ];
919
+ /**
920
+ * The cases only workers on threads of their own pass — Web Workers, not the
921
+ * in-process host, whose units share the thread of the test that runs them: a
922
+ * unit that never yields that thread is ended only by terminating it, and only
923
+ * a Web Worker closes itself.
924
+ */
925
+ export const threadCases = [
926
+ {
927
+ name: 'ends a call that never yields its thread at its timeout, terminating its worker, and runs the next on another',
928
+ run: async (setup) => {
929
+ const counts = { started: 0, terminated: 0 };
930
+ const runner = setup.runner(setup.pool({ width: 1, units: counting(counts) }));
931
+ const { storage } = setup;
932
+ const timedOut = await runner.runDetached(call(runaway, [], PLATFORM_FREE, { timeoutMs: 500 }), { storage });
933
+ ok(timedOut.kind === 'timed_out' && timedOut.ms === 500, `${timedOut.kind}`);
934
+ equal(counts.terminated, 1, 'its worker was terminated');
935
+ const next = await runner.runDetached(call(double, [encodeInteger(5n)]), { storage });
936
+ ok(next.kind === 'success', `the next call runs: ${next.kind}`);
937
+ same(IntegerType, decodeInteger(next.value), 10n, 'its value');
938
+ equal(counts.started, 2, 'on a worker started in its place');
939
+ },
940
+ },
941
+ {
942
+ name: 'fails a call whose worker closes itself, which no event says, letting the worker go, and runs the next on another',
943
+ run: async (setup) => {
944
+ const counts = { started: 0, terminated: 0 };
945
+ const runner = setup.runner(setup.pool({ width: 1, units: counting(counts) }));
946
+ const { storage } = setup;
947
+ const exited = await settled('the call whose worker closed itself to end', runner.runDetached(call(exiting, [], WITH_TEST), { storage }));
948
+ ok(exited.kind === 'failed' && exited.exitCode === -1, `the call failed, its worker gone: ${exited.kind}`);
949
+ ok(/the unit worker stopped: it closed itself/.test(exited.stderr), `naming why: ${JSON.stringify(exited.stderr)}`);
950
+ equal(setup.host.closed(), 1, 'the services its worker was handed were ended');
951
+ // Its place is free: the pool is one wide.
952
+ const next = await settled('the next call to run', runner.runDetached(call(double, [encodeInteger(6n)]), { storage }));
953
+ ok(next.kind === 'success', `the next call runs: ${next.kind}`);
954
+ same(IntegerType, decodeInteger(next.value), 12n, 'its value');
955
+ equal(counts.started, 2, 'on a worker started in its place');
956
+ },
957
+ },
958
+ ];
959
+ //# sourceMappingURL=runner-cases.js.map