@threadedstack/wmd-web 0.1.51 → 0.1.53

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.
package/README.md CHANGED
@@ -102,8 +102,8 @@ The interface this host implements is in [docs/host-interface.md](docs/host-inte
102
102
  - **Exit.** `proc_exit` sets the shared exit flag (the first code wins), tells the page,
103
103
  and throws to unwind its own Worker. The page then terminates every Worker. A trap on
104
104
  any thread ends the machine with code 4, as in the runner.
105
- - **Memory.** One `WebAssembly.Memory({initial: 6144, maximum, shared: true})`.
106
- `maximum` is 6144 + RAM pages + 1 GiB of slack (10,240 + 16,384 pages for
105
+ - **Memory.** One `WebAssembly.Memory({initial, maximum, shared: true})`, `initial` the minimum vm.wasm's
106
+ memory import declares (512 pages, 32 MiB, since IOS-2; 6144 before). `maximum` is 6144 (heap room) + RAM pages + 1 GiB of slack (10,240 + 16,384 pages for
107
107
  `--ram 256`). Views over it are rebuilt whenever `memory.buffer` changes after a grow.
108
108
  - **Output.** stdout and stderr go into a ring per fd in a SharedArrayBuffer
109
109
  (`src/host/stdio.js`), 32 MiB each for a boot (`bootWmd({stdioRingBytes})`, a power of
package/RELEASE.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wmd-web",
3
3
  "version": "0.5.1",
4
- "commit": "8f7cfff4adf7a48395a945e15a1041b56c81e789",
4
+ "commit": "1c2eb4f7c274b135d46e3d5a340dfe47a067ac1f",
5
5
  "previous": null,
6
6
  "decisions": [
7
7
  "D-388",
@@ -80,12 +80,12 @@
80
80
  "D-661",
81
81
  "D-666"
82
82
  ],
83
- "vmSources": "3e3c540edec568f5142f2beab29f03613e70f033",
83
+ "vmSources": "2a7e60f9e7f01494c5141ec1ac9e38435b7f6ace",
84
84
  "guest": {
85
85
  "arch": "arm64",
86
86
  "files": {
87
87
  "vm.wasm": {
88
- "sha256": "ec00c59a70add068305168952885ac3c637b0bd274c1c7a7c28aac9e24fcc3de",
88
+ "sha256": "7d16efadd83097e9b9188410187fb929b4ee5afbcb22cd387deebf1206b52376",
89
89
  "bytes": 1575966
90
90
  },
91
91
  "Image": {
@@ -150,13 +150,13 @@
150
150
  "bytes": 87706
151
151
  },
152
152
  "edge-site/wasm/linux.py": {
153
- "sha256": "5f7ec28282f78691a4d84e37aeb8197cc5aa1888ffb2034f73e4e9c80faf9e22",
154
- "bytes": 27198
153
+ "sha256": "54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2",
154
+ "bytes": 27628
155
155
  }
156
156
  }
157
157
  },
158
158
  "files": {
159
- "README.md": "6ac8c77da8d0352ed0c9d7390f9ea648d46f5ab64b03fe26658165e0e3ec5a7b",
159
+ "README.md": "f0f607498adc74465fdf90467313117fc3aad39a803efa4c8704605bb916a297",
160
160
  "edge-site/own/HASHES.txt": "4d83edcb41399bb89eb7b1f89115886d739adac887bdde59a8d33e3a4602683a",
161
161
  "edge-site/own/NOTICES.txt": "8ceca5406ee5833737bd5fa4a41d434bf5e4d26eff6da1e42c693176ee113101",
162
162
  "edge-site/own/acorn/LICENSE": "76a876cf886ff9be2a8b5e2e86514fed06223c8c9f0c1e9ee9606e93841e00b7",
@@ -167,7 +167,7 @@
167
167
  "edge-site/wasm/NOTICES.txt": "7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421",
168
168
  "edge-site/wasm/edgejs.wasm": "7131008ab38d52ff31b0d3059c6e105e8a448775408981956ce7aff792bfd98b",
169
169
  "edge-site/wasm/linux.cjs": "77bb31f2d92a36f8a76bb129187febd253ce79e1c1dc9d4bccc87474075fef3f",
170
- "edge-site/wasm/linux.py": "5f7ec28282f78691a4d84e37aeb8197cc5aa1888ffb2034f73e4e9c80faf9e22",
170
+ "edge-site/wasm/linux.py": "54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2",
171
171
  "export-page/coi-sw.js": "0300e670b413cb2e0aae35843fc583546bbf6687df971ab6df41cfa3b0d494d7",
172
172
  "export-page/index.html": "f5450c89e63601bbbbffef421f03491b231d1f143070012c1c5315d4b0059f43",
173
173
  "export-page/run.css": "b57adf1e76553549c1f89ff157b7973409dedc21889cd3932948cd05b51adc6f",
@@ -176,11 +176,11 @@
176
176
  "guest/arm64/Image-4k": "55ab90773d080416f1539ae2caac0a49bb98e2bb34ce9384849725fb8e601551",
177
177
  "guest/arm64/features": "4dc6f2a114c7c87a67eb9f0fe53c52b6b8128bb30830a6be498432a3701587f4",
178
178
  "guest/arm64/initramfs.cpio.gz": "ac7c0fc194b059579943c3d8ceaa0757c3e3e248231c2ad779260e97d5084cd3",
179
- "guest/arm64/vm.wasm": "ec00c59a70add068305168952885ac3c637b0bd274c1c7a7c28aac9e24fcc3de",
179
+ "guest/arm64/vm.wasm": "7d16efadd83097e9b9188410187fb929b4ee5afbcb22cd387deebf1206b52376",
180
180
  "package.json": "6de9aa9fabdb395651d39997c17e094f01a574f54a36f0af31bd3ffaae53cda1",
181
181
  "src/base.js": "982f8e46dbb727ec542a494ebdb884ccd19a31ff4e091425b2d1fc01b0d4754a",
182
182
  "src/blob.js": "bb2a2f0d87ce236280a7be2f246c926010dfe07f649c27da5e70d8eb5eaf7061",
183
- "src/boot.js": "d983b2eb5a4faadd0893ce24d3ba27bd20e2bd02a577dcb6658aebb8c94ee491",
183
+ "src/boot.js": "7ecdbe8c614436884d18181389af73568baba9e668601568437e8b59266dfaae",
184
184
  "src/build/builder.js": "c7794ec15b183213228776c8f4fb0950dec7e621f948358da7de8f90ef4f70ec",
185
185
  "src/build/context.js": "d38097c61dbdadc4d41290c010425a4422f499aba473fa2b83f2a5c41e543571",
186
186
  "src/build/dockerfile.js": "5957fe3d4ac8ff8b312f980ee04bd1d98ad4373a61f9a33e02f1ff1108b6ea53",
@@ -255,7 +255,7 @@
255
255
  "src/edge/sems.js": "f5bd680e67b7ec3eeb16b2f7ac9207b16491001400b435ff5ee3a34f050d8ceb",
256
256
  "src/edge/service-host.js": "f77664be9e3a0cc1cc9b283c5aeda7d94c7a9d61b8cecda5b90822295d315df6",
257
257
  "src/edge/service-port.js": "6daff74e083d8d6e4d3ce950004bafb8632e78c9fbf626197a2c18453ac96eeb",
258
- "src/edge/setup.js": "a868fb062f7ed18f77a517c1b7c6521231d26c29e8e289f83d38415250cc05cf",
258
+ "src/edge/setup.js": "2ee13fbcb0dfd5978540598fb2e085269bd84021419fa71b0cc0ffb901e4cfec",
259
259
  "src/edge/shim.js": "25efa4dddd3bbdd4a2967d99116e10c011a41aa0a4bdd7ce670fbf6d01735a76",
260
260
  "src/edge/site.js": "ff63be7c751678b773fd03e79e551e6fe6e85caa0444b6413b7bb940b8316979",
261
261
  "src/edge/spawn-guard.js": "666cc6cca0628f3c07093f08da277a1d6291eebb91c19abebf0d422f6197e401",
@@ -290,10 +290,10 @@
290
290
  "src/host/chan-services.js": "e7f52931b6ef76a8b97b793d0a1d86fb35d20dbca3dd333d18cc4ded0806c9f7",
291
291
  "src/host/chan.js": "bb9e76890b0efeee7cfbd8481b9fb4620b3b184459d96d62ff68ddcdc8a46f83",
292
292
  "src/host/ckpt-file.js": "da7938fa640a062e77bdfb59caad5b3b1fcbf6150e3220de3be23f253f4c4497",
293
- "src/host/ckpt-io.js": "3fbe74f0254c597f10d088c85e8ba72725502d86ae4dd8c6d2bf0821a93c873f",
294
- "src/host/ckpt-point.js": "42bc16b3f754de3cd4e39f37a0feca2ffd8b4231cd72ec32bd6e1ea734c3c8c7",
295
- "src/host/ckpt-save.js": "e222571033ae74a4439596c5e90e03b2aa9a5516665dd290f8dd243712294523",
296
- "src/host/ckpt.js": "f079c6a71f769855d8ddc1c521c7408d3e73cd152f99872607e0b6918177173b",
293
+ "src/host/ckpt-io.js": "c176b98bc9fd7669da6336d481425b980af440a7c1f95463f6f1c4808e9590bf",
294
+ "src/host/ckpt-point.js": "e08441b52d65b18c91f7e14b6ab3ad347572a0ac96a6642cf8072b47dde404eb",
295
+ "src/host/ckpt-save.js": "7bb07f536005fb5e7d9db6a09169a5ce1e3865d337ab65ce798a111334c6aa07",
296
+ "src/host/ckpt.js": "5b651f67742d133f246239cdb6a7dcdf688aa62c84e0ef53925077740551412b",
297
297
  "src/host/clock.js": "aba6af3a8b1a985ae340892222e4b482d33afe20f5c8b3a4c7403ce87d1e247c",
298
298
  "src/host/csp-reason.js": "ecec797e31006896176ff4e2972f11e5d5df160fe0cd80071c39d7808ff922fc",
299
299
  "src/host/ctl.js": "86066c8d3be8e6f6b05e831344cd72ebc446ced391fc8290e1c584940b8ab3e0",
@@ -314,7 +314,7 @@
314
314
  "src/host/jit-hub.js": "cf3fc9f9d4e3fb50c41d6de5e2523f380d3c6c1feaf61c15d90cde89aec2f4c3",
315
315
  "src/host/jit-snap.js": "3932f36047c9edeb7f59282d1c37fef19c8f5a9fe4bd0192fb93aa64030fe51d",
316
316
  "src/host/jit.js": "72ef7334506fde2b3724cee93b52a987fbd6d45473b8de93d914db8a80ae9e17",
317
- "src/host/layout.js": "d5bc5aa9292630b204438df5d6278fda6daa2a65acc061e1c57e0272b32fecc8",
317
+ "src/host/layout.js": "c878b8da956da3ebc2391cf802869f12b3d74c131ffbcb9879536617728beeac",
318
318
  "src/host/monitor.js": "ae1741ba35668bcc6192642246494433b175668933921634c699af5a0a69acc0",
319
319
  "src/host/p9mount.js": "cd27abd769b19ed8b26050ddd8b6d61f81faa5a431924217dd0bf2593258d5b9",
320
320
  "src/host/pinned-fetch.js": "873eb804604c150f6c8e488eb6c49fb8dc7a85108e80bf1a831904b9555726eb",
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threadedstack/wmd-web",
3
- "version": "0.1.51",
3
+ "version": "0.1.53",
4
4
  "license": "MIT",
5
5
  "homepage": "https://github.com/threadedstack/wmd-releases",
6
6
  "repository": {
@@ -9,8 +9,8 @@
9
9
  },
10
10
  "description": "Browser host for wmd's guest vm.wasm (Web Workers + shared memory + WASI preview1)",
11
11
  "wmd": {
12
- "tag": "v0.1.51",
13
- "commit": "8f7cfff4adf7a48395a945e15a1041b56c81e789",
12
+ "tag": "v0.1.53",
13
+ "commit": "1c2eb4f7c274b135d46e3d5a340dfe47a067ac1f",
14
14
  "web": "0.5.1"
15
15
  },
16
16
  "type": "module",
package/src/boot.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  CTL_CK_ATTACHES,
25
25
  CTL_CK_GO,
26
26
  CTL_CK_RESTORED,
27
+ CTL_CK_STREAM,
27
28
  CTL_SPAWN_FAIL,
28
29
  POOL_MAX,
29
30
  SLOT_STATE,
@@ -48,7 +49,7 @@ import { ControlClient } from './host/ctl.js'
48
49
  import { chooseTwin, eventsOf, putBackTwin, specKeysDiffering, twinForBoot } from './gowasm/boot-setup.js'
49
50
  import { PAGE as CKPT_PAGE, requestCheckpoint } from './host/ckpt-point.js'
50
51
  import {
51
- CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyForChoice, specChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
52
+ CheckpointError, serviceErrorCode, assembleCheckpoint, memChunksOf, bootKeyForChoice, specChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, checkArgvFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
52
53
  } from './host/ckpt.js'
53
54
  import { captureJit, jitSnapStats, modulesOf, ownersNeedingHub, restoreStore } from './host/jit-snap.js'
54
55
  export { CheckpointError, memoryStore, opfsStore } from './host/ckpt.js'
@@ -100,12 +101,14 @@ export async function edgeSetup(o = {}) {
100
101
 
101
102
  const pythonLooks = new WeakMap() // the look at a service's layers, once per service object (a restore's text choice asks again)
102
103
  /** X25: {path, version, ms} of the image's python found in the 9P service's layers (src/edge/python-look.js), kept per service; never throws (a layer that cannot be read: no python). */
103
- async function pythonLook(A, svc, env, e = {}) {
104
+ async function pythonLook(A, svc, env, e = {}, once = null) {
104
105
  if (!svc.layers || !svc.layers.length) return null
105
106
  let p = pythonLooks.get(svc)
106
107
  if (!p) {
108
+ // IOS-2: the look reads the boot's own download of each layer (layerOnce), so a layer is fetched once and held once
109
+ const fetchFn = e.fetchLayer || (once ? u => once.get(u).then(b => ({ arrayBuffer: async () => b })) : null)
107
110
  p = import('./edge/python-look.js')
108
- .then(m => m.lookForPython(svc.layers, env, { at: svc.at ?? 'rootfs', ...(e.fetchLayer ? { fetchFn: e.fetchLayer } : {}) }))
111
+ .then(m => m.lookForPython(svc.layers, env, { at: svc.at ?? 'rootfs', ...(fetchFn ? { fetchFn } : {}) }))
109
112
  .catch(() => ({ path: '', version: '', ms: 0 }))
110
113
  pythonLooks.set(svc, p)
111
114
  }
@@ -147,7 +150,7 @@ export async function edgeAuto(o, counts = edgePlanCounts) {
147
150
  return off('bundle/config/config.json is not JSON')
148
151
  }
149
152
  // X25: the image's python, found in the service's layers (gone at once with `python: false` and for an image whose layers are not given)
150
- const imagePython = e.python === false ? null : await pythonLook(A, svc, facts.env, e)
153
+ const imagePython = e.python === false ? null : await pythonLook(A, svc, facts.env, e, o._layerOnce)
151
154
  if (imagePython && typeof e.onLog === 'function') try { e.onLog(0, { type: 'python-look', ms: imagePython.ms, path: imagePython.path, version: imagePython.version }) } catch {} // the look's cost, for the page's own log
152
155
  // a container that cannot use node in the frame loads no more of the edge code than the plan (the reason is counted); one that has a python the plan
153
156
  // could take goes on without node (python only, src/edge/setup.js)
@@ -190,7 +193,7 @@ export async function edgeTextOptions(plain) {
190
193
  const facts = A.containerFacts(svc.files, plain.args || [])
191
194
  const pre = A.preplan(facts, { rt: e.rt, win: ABLE_WIN })
192
195
  // python's mounts by the same rule (the switch `python: false` is this boot's choice, not the text's): the checkpoint's key does not depend on it
193
- const look = await pythonLook(A, svc, facts.env, e)
196
+ const look = await pythonLook(A, svc, facts.env, e, plain._layerOnce)
194
197
  const py = look?.path ? A.pythonPlanFor(facts, look, { ...e, python: undefined }, ABLE_WIN) : { use: false }
195
198
  if (!pre.use && !py.use) return null
196
199
  const files = A.addEdgeMounts(svc.files, pre.use ? pre.node : undefined, undefined, py.use ? A.pythonSpecTools(py.python) : [])
@@ -284,7 +287,79 @@ export function isOutOfMemory({ reserve = false, usedUp = false, said = false, m
284
287
  if (!reserve && memoryBytes > memoryMaxBytes - OOM_MARGIN) return 'memory at its maximum'
285
288
  return null
286
289
  }
287
- const VM_MIN_PAGES = 6144 // vm.wasm's memory import minimum (384 MiB)
290
+ const VM_MIN_PAGES = 6144 // vm.wasm's memory import minimum up to IOS-2 (384 MiB): the heap room the memory's maximum keeps above the RAM
291
+
292
+ /**
293
+ * IOS-2: where the LEB128 minimum of the module's `env`.`memory` import starts in `bytes`, and its value: {at, min}, or null (not a module, no such
294
+ * import). Reads only the import section's header and entries.
295
+ */
296
+ function memoryImportOf(bytes) {
297
+ if (!bytes || bytes.length < 8 || bytes[0] !== 0 || bytes[1] !== 0x61 || bytes[2] !== 0x73 || bytes[3] !== 0x6d) return null
298
+ let i = 8
299
+ const u = () => {
300
+ let r = 0
301
+ let sh = 0
302
+ for (;;) {
303
+ if (i >= bytes.length) throw new RangeError('truncated')
304
+ const b = bytes[i++]
305
+ r += (b & 0x7f) * 2 ** sh
306
+ if (!(b & 0x80)) return r
307
+ sh += 7
308
+ }
309
+ }
310
+ const name = () => {
311
+ const n = u()
312
+ const t = new TextDecoder().decode(bytes.subarray(i, i + n))
313
+ i += n
314
+ return t
315
+ }
316
+ try {
317
+ while (i < bytes.length) {
318
+ const id = bytes[i++]
319
+ const size = u()
320
+ const end = i + size
321
+ if (id !== 2) {
322
+ i = end
323
+ continue
324
+ }
325
+ const n = u()
326
+ for (let k = 0; k < n; k++) {
327
+ const mod = name()
328
+ const field = name()
329
+ const kind = bytes[i++]
330
+ if (kind === 0) u() // function: type index
331
+ else if (kind === 1) {
332
+ i++ // table: element type, then limits
333
+ const f = u()
334
+ u()
335
+ if (f & 1) u()
336
+ } else if (kind === 2) {
337
+ const f = u()
338
+ const at = i
339
+ const min = u()
340
+ if (f & 1) u()
341
+ if (mod === 'env' && field === 'memory') return { at, min }
342
+ } else if (kind === 3) i += 2 // global: type, mutability
343
+ else return null
344
+ }
345
+ return null
346
+ }
347
+ } catch {
348
+ return null
349
+ }
350
+ return null
351
+ }
352
+ /** IOS-2: vm.wasm's declared minimum of memory 0, in 64 KiB pages (null when the bytes have no `env`.`memory` import). */
353
+ /**
354
+ * IOS-2: how many pages from 0 a restore reads to find pages the new instance's start wrote that the checkpoint had as zero: those below the
355
+ * memory's size when the instance was made (it could write nothing above), at most the checkpoint's. Each page read is committed by mobile
356
+ * WebKit, so a bound of VM_MIN_PAGES (384 MiB) cost a phone that much for a 32 MiB vm.wasm.
357
+ */
358
+ export const restoreZeroScanPages = (memPages, instancePages) => Math.min(memPages, instancePages)
359
+
360
+ export const vmMemoryMinPages = bytes => memoryImportOf(bytes)?.min ?? null
361
+ /** IOS-2 (tests): the byte offset of that minimum's LEB128 in `bytes`. */
362
+ export const vmMemoryMinAt = bytes => memoryImportOf(bytes)?.at ?? null
288
363
 
289
364
  const haveJspi = () => typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function'
290
365
 
@@ -784,6 +859,33 @@ function packShared(bytes) {
784
859
  return toShared(bytes)
785
860
  }
786
861
 
862
+ /**
863
+ * IOS-2: one download per layer url for a boot. get(url) starts (once) the boot's own kind of download (shared memory, no-store) and gives its
864
+ * promise; take(url) hands that promise over and forgets it, so the map holds no bytes once the boot has the pack.
865
+ */
866
+ export function layerOnce(signal, fetchFn = (url, sig) => fetchShared(url, sig, undefined, true)) {
867
+ const m = new Map()
868
+ return {
869
+ get(url) {
870
+ let p = m.get(url)
871
+ if (!p) {
872
+ p = fetchFn(url, signal)
873
+ p.catch(() => {})
874
+ m.set(url, p)
875
+ }
876
+ return p
877
+ },
878
+ take(url) {
879
+ const p = m.get(url) || null
880
+ m.delete(url)
881
+ return p
882
+ },
883
+ get size() {
884
+ return m.size
885
+ },
886
+ }
887
+ }
888
+
787
889
  function toShared(bytes) {
788
890
  const sab = new SharedArrayBuffer(bytes.byteLength)
789
891
  new Uint8Array(sab).set(bytes)
@@ -906,6 +1008,8 @@ export async function bootWmd(o) {
906
1008
  if (!globalThis.crossOriginIsolated) {
907
1009
  throw new Error('page is not cross-origin isolated (needs COOP same-origin + COEP require-corp)')
908
1010
  }
1011
+ // IOS-2: one download per layer url for this boot, shared by X25's python look and the boot's own packs
1012
+ if (!o._layerOnce) o = { ...o, _layerOnce: layerOnce(o.signal) }
909
1013
  // X5 option A: `edge: { base }` is all a page says; the setup of node in the frame is done here (edgeAuto below)
910
1014
  const plain0 = o // the options as the caller gave them: a restore chooses node in the frame from its checkpoint's choice (chooseEdge)
911
1015
  let auto = null
@@ -1061,13 +1165,15 @@ async function bootMachine(o) {
1061
1165
  o._assets = undefined // the handle keeps no reference of its own to the previous boot's assets
1062
1166
  // W24: one download per file, with its bytes as they come. A file the caller passed as bytes, or one a restore reuses
1063
1167
  // (o.assets), is reported once, done and cached.
1064
- const download = (file, url, shared, extra = {}) => {
1168
+ const download = (file, url, shared, extra = {}, pre = null) => {
1065
1169
  const kind = `download:${file}`
1066
1170
  const base = { t: 'boot', stage: 'download', file, ...extra }
1067
1171
  let finalUrl = url
1068
1172
  const before = timingCount(url)
1069
1173
  const ts = absMs()
1070
- return fetchShared(url, o.signal, (bytes, total) => be.progress(kind, { ...base, state: 'progress', bytes, total, cached: null }), shared, r => (finalUrl = r.url || url)).then(async buf => {
1174
+ const fetchIt = () => fetchShared(url, o.signal, (bytes, total) => be.progress(kind, { ...base, state: 'progress', bytes, total, cached: null }), shared, r => (finalUrl = r.url || url))
1175
+ // IOS-2: a layer the python look already downloaded (layerOnce) is that download; if it failed, the boot fetches it itself as before
1176
+ return (pre ? pre.catch(fetchIt) : fetchIt()).then(async buf => {
1071
1177
  const tookMs = Math.round(absMs() - ts)
1072
1178
  // the browser adds a response's Resource Timing entry a little after its body is read (Chromium: a small file was
1073
1179
  // read before its entry existed): wait for it, at most 200 ms
@@ -1109,7 +1215,7 @@ async function bootMachine(o) {
1109
1215
  ? Promise.resolve(A.chanLayers.map((ls, i) => ls.map((b, j) => given(`pack:${packIds[i][j]}`, b, { port: chanSvcs[i].port }))))
1110
1216
  : Promise.all(
1111
1217
  chanSvcs.map((svc, i) =>
1112
- Promise.all((svc.layers || []).map((l, j) => (typeof l === 'string' ? download(`pack:${packIds[i][j]}`, l, true, { port: svc.port }) : Promise.resolve(given(`pack:${packIds[i][j]}`, packShared(l), { port: svc.port }))))),
1218
+ Promise.all((svc.layers || []).map((l, j) => (typeof l === 'string' ? download(`pack:${packIds[i][j]}`, l, true, { port: svc.port }, o._layerOnce?.take(l)) : Promise.resolve(given(`pack:${packIds[i][j]}`, packShared(l), { port: svc.port }))))),
1113
1219
  ),
1114
1220
  ).then(downloaded)
1115
1221
  layersP.catch(() => {})
@@ -1163,6 +1269,7 @@ async function bootMachine(o) {
1163
1269
  try {
1164
1270
  const h = await raceAbort(lazyIn.header)
1165
1271
  checkVmKeyFits(h, vmKey)
1272
+ checkArgvFits(h, argv) // IOS-2: another command line (a 1024 MiB base under a 256 MiB request) is refused before its body is read
1166
1273
  settleLayout(chooseLayout(o.args, o, h)) // X24 default: the base snapshot's own layout
1167
1274
  // part 4: and its own twin choice. The spec text is first used by the boot key and by the channel service's Worker, both below this point in this same
1168
1275
  // try, so the choice made here is made before either has it; only the layers and ports of the services were used before (their packs download meanwhile)
@@ -1293,7 +1400,10 @@ async function bootMachine(o) {
1293
1400
 
1294
1401
  // 2. Shared memory and control block.
1295
1402
  const tMem = absMs()
1296
- let memory = new WebAssembly.Memory({ initial: VM_MIN_PAGES, maximum, shared: true })
1403
+ // IOS-2: memory 0 starts at vm.wasm's own declared minimum, and its heap grows as it is used. Mobile WebKit counts every byte of the initial
1404
+ // memory at once (D-516); VM_MIN_PAGES stays the heap room of the maximum. A vm.wasm that declares more (or bytes that cannot be read) gets that.
1405
+ const declaredMin = vmMemoryMinPages(new Uint8Array(vmBytes))
1406
+ let memory = new WebAssembly.Memory({ initial: declaredMin ?? VM_MIN_PAGES, maximum, shared: true })
1297
1407
  const memoryInitialBytes = memory.buffer.byteLength
1298
1408
  const ctlSab = createControl()
1299
1409
  const ctl = new Int32Array(ctlSab)
@@ -1325,7 +1435,7 @@ async function bootMachine(o) {
1325
1435
  }
1326
1436
  function restoreMemoryNow() {
1327
1437
  const tm = absMs()
1328
- const have = memory.buffer.byteLength / CKPT_PAGE
1438
+ const have = memory.buffer.byteLength / CKPT_PAGE // the size the instance made: its start function wrote nothing above it
1329
1439
  if (restoreIn.header.memPages > have) memory.grow(restoreIn.header.memPages - have)
1330
1440
  const u8 = new Uint8Array(memory.buffer)
1331
1441
  const kept = new Uint8Array(restoreIn.header.memPages)
@@ -1359,7 +1469,7 @@ async function bootMachine(o) {
1359
1469
  }
1360
1470
  // pages the instance's start function wrote that were zero at the checkpoint (the runner's zero_absent): the static region
1361
1471
  let zeroed = 0
1362
- const w = new Int32Array(memory.buffer, 0, Math.min(restoreIn.header.memPages, VM_MIN_PAGES) * (CKPT_PAGE / 4))
1472
+ const w = new Int32Array(memory.buffer, 0, restoreZeroScanPages(restoreIn.header.memPages, have) * (CKPT_PAGE / 4))
1363
1473
  for (let p = 0; p * (CKPT_PAGE / 4) < w.length; p++) {
1364
1474
  if (kept[p]) continue
1365
1475
  const lo = p * (CKPT_PAGE / 4)
@@ -2293,6 +2403,7 @@ async function bootMachine(o) {
2293
2403
  const c = ck
2294
2404
  if (!c) return
2295
2405
  ck = null
2406
+ Atomics.store(ctl, CTL_CK_STREAM, 0)
2296
2407
  clearTimeout(c.timer)
2297
2408
  clearInterval(c.poll)
2298
2409
  if (c.atPoint && !c.went) {
@@ -2368,6 +2479,15 @@ async function bootMachine(o) {
2368
2479
  function ckptMaybeGo() {
2369
2480
  const c = ck
2370
2481
  if (!c || c.went || !c.mem || !c.svc || !c.jitDone) return
2482
+ if (c.stream && !c.streamDone) {
2483
+ if (c.saving) return
2484
+ if (!c.mem.streamed) return ckptFail(new CheckpointError('memory', 'the guest copied its memory although the checkpoint was to be saved straight to the store'))
2485
+ c.saving = true
2486
+ clearTimeout(c.timer) // the guest is at its point: the save's own time is vCPU 0's to bound (goTimeoutMs)
2487
+ ckptStreamSave(c)
2488
+ return
2489
+ }
2490
+ Atomics.store(ctl, CTL_CK_STREAM, 0)
2371
2491
  c.went = true
2372
2492
  c.goAt = gnow()
2373
2493
  Atomics.store(ctl, CTL_CK_GO, 1)
@@ -2412,7 +2532,25 @@ async function bootMachine(o) {
2412
2532
  }
2413
2533
 
2414
2534
  function ckptAssemble(c, names) {
2535
+ // IOS-2: a checkpoint saved straight to a store was built and written before the guest went on: its answer is ready, with the resume's times
2536
+ if (c.savedResult) {
2537
+ const st = c.savedResult.header.stats
2538
+ if (st) {
2539
+ st.resumeMs = c.resumeAt - c.goAt
2540
+ st.savePauseMs = c.goAt - c.pointAt
2541
+ }
2542
+ return c.resolve(c.savedResult)
2543
+ }
2415
2544
  try {
2545
+ c.resolve(ckptBuild(c, names))
2546
+ } catch (err) {
2547
+ c.reject(err)
2548
+ }
2549
+ }
2550
+
2551
+ /** The checkpoint of a point whose parts are all in (c.mem, c.svc, c.jitSnap, c.ctlBytes): {header, sections}. Throws. */
2552
+ function ckptBuild(c, names) {
2553
+ {
2416
2554
  const t = absMs()
2417
2555
  const stats = {
2418
2556
  stopLatencyMs: c.pointAt - c.t0, // request to the vCPUs stopped and the point entered (includes the guest's world stop, share drain and service stop)
@@ -2455,9 +2593,31 @@ async function bootMachine(o) {
2455
2593
  ckpt.header.stats.assembleMs = absMs() - t
2456
2594
  ckpt.header.svcStats = Object.fromEntries(Object.entries(c.svc).map(([port, d]) => [port, { bytes: d.bytes, fids: d.fids }]))
2457
2595
  if (c.jitSnap) ckpt.header.jitStats = jitSnapStats(c.jitSnap)
2458
- c.resolve(ckpt)
2596
+ return ckpt
2597
+ }
2598
+ }
2599
+
2600
+ /**
2601
+ * IOS-2: vm.checkpoint({save}) once every part is in and the guest is still at its point: the memory sections are lazy chunks over the frozen
2602
+ * memory (vCPU 0 found the non-zero pages and copied none), the store's Worker pulls them one at a time through its one reused buffer, and only
2603
+ * then does the guest go on. The page never holds a copy of the guest's memory.
2604
+ */
2605
+ async function ckptStreamSave(c) {
2606
+ try {
2607
+ const names = await netNameList()
2608
+ if (ck !== c) return
2609
+ c.goAt = c.resumeAt = gnow() // provisional: the header is written before the guest goes on
2610
+ c.mem.chunks = memChunksOf(memory, c.mem.index)
2611
+ if (c.mem.ram) c.mem.ram.chunks = memChunksOf(ramMem, c.mem.ram.index)
2612
+ const ckpt = ckptBuild(c, names)
2613
+ ckpt.header.stats.streamed = true
2614
+ const saved = await c.stream.store.save(c.stream.name, ckpt)
2615
+ if (ck !== c) return
2616
+ c.savedResult = { header: ckpt.header, saved, streamed: true }
2617
+ c.streamDone = true
2618
+ ckptMaybeGo()
2459
2619
  } catch (err) {
2460
- c.reject(err)
2620
+ ckptFail(err instanceof CheckpointError ? err : new CheckpointError('io', `saving the checkpoint failed: ${(err && err.message) || err}`))
2461
2621
  }
2462
2622
  }
2463
2623
 
@@ -2467,14 +2627,21 @@ async function bootMachine(o) {
2467
2627
  * times. It stays usable (restore it again as often as wanted) until the caller drops it; to survive a reload save
2468
2628
  * it with a store (opfsStore().save(name, ckpt)).
2469
2629
  */
2470
- function checkpoint({ label = '', timeoutMs = 60_000 } = {}) {
2630
+ function checkpoint({ label = '', timeoutMs = 60_000, save = null } = {}) {
2631
+ // IOS-2: save {store, name}: the checkpoint goes straight to the store and the answer is {header, saved, streamed}, no sections. With an
2632
+ // OPFS store the page never holds the guest's memory (see ckptStreamSave); with another store it is taken in memory and saved, as before
2633
+ if (save && (!save.store || typeof save.store.save !== 'function' || !save.name)) return Promise.reject(new TypeError('checkpoint({save}): save is {store, name}'))
2634
+ if (save && save.store.kind !== 'opfs') {
2635
+ return checkpoint({ label, timeoutMs }).then(async ckpt => ({ header: ckpt.header, saved: await save.store.save(save.name, ckpt), streamed: false }))
2636
+ }
2471
2637
  if (!ckptOn) return Promise.reject(new Error('this machine was booted without checkpoint support: bootWmd({checkpoint: true})'))
2472
2638
  if (restoring) return Promise.reject(new CheckpointError('busy', 'a restore is running: this machine is about to end, and a checkpoint taken now would be lost'))
2473
2639
  if (done || chanDied) return Promise.reject(new Error('the machine has ended'))
2474
2640
  if (ck) return Promise.reject(new Error('a checkpoint is already being taken'))
2475
2641
  if (o.edge?.busy?.()) return Promise.reject(new CheckpointError('busy', 'node runs outside the guest (page switch edge=1): its files and processes are not in a checkpoint; take it when no such program runs'))
2476
2642
  return new Promise((resolve, reject) => {
2477
- const c = (ck = { label, t0: gnow(), resolve, reject, attachesBefore: Atomics.load(ctl, CTL_CK_ATTACHES), timer: null })
2643
+ const c = (ck = { label, t0: gnow(), resolve, reject, attachesBefore: Atomics.load(ctl, CTL_CK_ATTACHES), timer: null, stream: save })
2644
+ Atomics.store(ctl, CTL_CK_STREAM, save ? 1 : 0)
2478
2645
  c.timer = setTimeout(() => ckptFail(new CheckpointError('timeout', `the guest did not reach its checkpoint point in ${timeoutMs} ms`)), timeoutMs)
2479
2646
  if (!requestCheckpoint(memory, ctl)) ckptFail(new CheckpointError('not-ready', 'the guest has not started its checkpoint thread yet (it does that once the kernel has booted); try again after the control session is up'))
2480
2647
  })
@@ -2,7 +2,7 @@
2
2
  // The files of node in the sandboxed frame: the path under a source (the option edge: { sources } of bootWmd), the role the frame gives the file, its
3
3
  // sha256 and its size. The page accepts a file only when it has exactly this sha256 and size. The notice files travel with the rest.
4
4
  // EDGE_PACKAGE is the package that holds these files, for the {name} {version} {file} of a registry source's url (null: none named).
5
- export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.51' }
5
+ export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.53' }
6
6
  export const EDGE_PINS = [
7
7
  { path: 'wmd_browser_bg.wasm', role: 'wasm', sha256: '1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2', size: 6334959 },
8
8
  { path: 'wmd_browser.js', role: 'glue', sha256: 'b389b072096881ba39b22cd705d3a230af02acc5409c61fb4f997d1081c4df6f', size: 75647 },
@@ -13,5 +13,5 @@ export const EDGE_PINS = [
13
13
  { path: 'edgejs.wasm', role: 'edgejs', sha256: '7131008ab38d52ff31b0d3059c6e105e8a448775408981956ce7aff792bfd98b', size: 59169054 },
14
14
  { path: 'edgejs.NOTICES.txt', role: 'notice', sha256: '7ae1af355689c49eae0a3e1ca3ea85a7d0793100f6bd7f9dabc7916e191e0421', size: 363824 },
15
15
  { path: 'linux.cjs', role: 'linux', sha256: '77bb31f2d92a36f8a76bb129187febd253ce79e1c1dc9d4bccc87474075fef3f', size: 87706 },
16
- { path: 'linux.py', role: 'linuxpy', sha256: '5f7ec28282f78691a4d84e37aeb8197cc5aa1888ffb2034f73e4e9c80faf9e22', size: 27198 },
16
+ { path: 'linux.py', role: 'linuxpy', sha256: '54ee1c3be7af2c1517c1de0ae984b51adbbd77e0a71b277161e78320f50f1be2', size: 27628 },
17
17
  ]
package/src/edge/setup.js CHANGED
@@ -85,12 +85,13 @@ const idleOf = g => (typeof g.requestIdleCallback === 'function' ? f => g.reques
85
85
  * @param {boolean} [o.fscache] false: no start keeps file answers (default on in every browser, src/edge/sbx/cap.js FSCACHE_OFF; a browser that fails the equality proof is off there only)
86
86
  * @param {number} [o.frameCap] the most frames of node this page has alive at once (default by browser, src/edge/sbx/cap.js); a start that needs a new one over it runs in the guest
87
87
  * @param {boolean} [o.prepare] false: no frame is made before the first node command (default true, with keepFrame)
88
+ * @param {boolean} [o.early] false: python's module and the runtime's files are fetched only from prepare() on (default: from the setup on, when python is planned)
88
89
  * @param {function} [o.onLog] (id, record) of each run, and the site's events ({type: 'site', ...})
89
90
  * @param {function} [o.onBridge] (bridge) when a machine's bridge is made
90
91
  * @param {{on: number, off: object}} counts the plan's decisions, counted (src/boot.js edgePlanCounts)
91
92
  */
92
93
  export function edgeSetupIn(o, counts) {
93
- const { origin: siteOrigin, sources, base, pinned = null, fetchFiles: fetchFilesOpt, fetchOpts = {}, filesWaitMs, filesRetryMs, filesProgressMs, frameCap: frameCapOpt, fscache: fscacheOpt, python: pythonAsk, imagePython, pythonMaxMiB, fetchPython: fetchPythonOpt, ramMiB = 0, main = [], memoryMB = 0, swapMB = 0, env = [], user = '', readonlyRoot = false, hasTmpfs = false, p9port = 564, root = 'rootfs', settings = {}, rt = RT_DEFAULT, handIn = null, watch = {}, prepare = true, shareSite = false, edgeWasm = '/wasm/edgejs.wasm', onLog = () => {}, onBridge = () => {}, doc = globalThis.document, win = globalThis } = o
94
+ const { origin: siteOrigin, sources, base, pinned = null, fetchFiles: fetchFilesOpt, fetchOpts = {}, filesWaitMs, filesRetryMs, filesProgressMs, frameCap: frameCapOpt, fscache: fscacheOpt, python: pythonAsk, imagePython, pythonMaxMiB, fetchPython: fetchPythonOpt, ramMiB = 0, main = [], memoryMB = 0, swapMB = 0, env = [], user = '', readonlyRoot = false, hasTmpfs = false, p9port = 564, root = 'rootfs', settings = {}, rt = RT_DEFAULT, handIn = null, watch = {}, prepare = true, early = true, shareSite = false, edgeWasm = '/wasm/edgejs.wasm', onLog = () => {}, onBridge = () => {}, doc = globalThis.document, win = globalThis } = o
94
95
  const sandbox = !siteOrigin
95
96
  const origin = sandbox ? SANDBOX : siteOrigin
96
97
  // X25: python in the frame follows the switch of node (`edge`) and has its own, `python: false`; the page's plan for the image's python is planPython
@@ -179,6 +180,14 @@ export function edgeSetupIn(o, counts) {
179
180
  ...(filesRetryMs !== undefined ? { retryMs: filesRetryMs } : {}),
180
181
  ...(filesProgressMs !== undefined ? { progressMs: filesProgressMs } : {}),
181
182
  })
183
+ // PYFRAME-1: a python start in the frame needs python's module and the runtime's files; the downloads begin now (before the boot, network only: no frame
184
+ // is made and nothing compiled here) instead of when the page is idle after the boot, which a command that comes right after the boot waited for.
185
+ // Only with a frame made ahead (prepare and keepFrame on); `early: false` keeps the old order.
186
+ const earlyPy = !!pyGate && early !== false && prepare && watch.keepFrame !== false
187
+ if (earlyPy) {
188
+ pyGate.begin()
189
+ gate.begin()
190
+ }
182
191
  const site = frameSite({ origin, probe: sandbox ? () => sbx.files().then(r => !r.error) : iframeProbe({ doc, win }), onEvent: e => onLog(0, e) })
183
192
  // what a start waits for: node's files (the gate of item 12); and when the page planned python, python's module too. A start that is python's goes to the guest while
184
193
  // python's module is loading or when its fetch failed; a start of node goes to the guest only while it is loading (a failed fetch leaves python in the guest).
@@ -235,6 +244,8 @@ export function edgeSetupIn(o, counts) {
235
244
  onMessage: (m, machine) => mine.onMessage(m, machine),
236
245
  }
237
246
  }
247
+ let holdSite = null // PYFRAME-1: the setup's own use of the site while its early-prepared frame waits for a machine
248
+ let closed = false
238
249
  const e = {
239
250
  use: true,
240
251
  reason: '',
@@ -260,7 +271,9 @@ export function edgeSetupIn(o, counts) {
260
271
  const go = async () => {
261
272
  if (sandbox) pyGate?.begin() // python's module comes with them
262
273
  if (sandbox) gate.begin() // the files come while the frame is made (a node start finds them in, or waits at most FILES_WAIT_MS)
263
- const { prepareEdge } = await import('./page.js')
274
+ const { prepareEdge, useSite } = await import('./page.js')
275
+ // PYFRAME-1: a frame prepared before the boot is held by the setup until close() (a boot that fails or never comes leaves no frame behind)
276
+ if (earlyPy && !holdSite && !closed) holdSite = useSite(owner, origin)
264
277
  if (sandbox) await sbx.loadCode()
265
278
  const cfg = { rt, ...runtimeConfig(rt, sandbox ? { ...handIn, sbx: true, ...fscHand } : handIn), edgeWasm: prepWasm, ...(sandbox ? { linuxSrc: 'sbx:linux.cjs' } : {}), linux: {}, ...(pyPlan.use && prepWasm !== nodeWasm ? { memoryMaxMiB: capMiB } : {}) }
266
279
  p.started = Math.round(performance.now())
@@ -273,9 +286,15 @@ export function edgeSetupIn(o, counts) {
273
286
  return p
274
287
  },
275
288
  close() {
289
+ closed = true
290
+ holdSite?.()
291
+ holdSite = null
276
292
  pers.forEach(per => per.close())
277
293
  if (!sandbox) releaseSite(doc, origin, owner)
278
294
  },
279
295
  }
296
+ // PYFRAME-1: with python planned the frame is made and python's module compiled while the machine boots (the page's idle time during the boot), not after
297
+ // it: the first python start then finds the module compiled. A boot's own prepare() call takes this one.
298
+ if (earlyPy) e.prepare()
280
299
  return e
281
300
  }
@@ -4,7 +4,7 @@
4
4
  //
5
5
  // in: {id, op:'save', name, header, sections:[{name, lens:[n]}]} -> {ok, bytes, ms, shaMs, version, leftover}
6
6
  // The bytes are pulled, one chunk at a time: when the save is ready for chunk (si, ci) the Worker posts
7
- // {need:true, saveId:id, si, ci}; the page answers {op:'chunk', saveId, si, ci, buf}. At most one chunk (32 MiB)
7
+ // {need:true, saveId:id, si, ci, back?}; the page answers {op:'chunk', saveId, si, ci, buf, len?} (back: the last chunk's buffer, reused, IOS-2). At most one chunk (32 MiB)
8
8
  // waits here, and a chunk is dropped as soon as it is written. One save at a time (a second is refused: busy).
9
9
  // {id, op:'info', name} -> {ok, header} (header only: fast, no digests)
10
10
  // {id, op:'load', name, sections:[names] | null (all), verify} -> {ok, header, sections:{name:[ArrayBuffer]}, ms}
@@ -187,7 +187,7 @@ async function handle(m) {
187
187
  }
188
188
  }
189
189
 
190
- const saver = createSaver(msg => self.postMessage(msg))
190
+ const saver = createSaver((msg, transfer = []) => self.postMessage(msg, transfer))
191
191
 
192
192
  self.onmessage = async e => {
193
193
  const m = e.data
@@ -16,7 +16,7 @@
16
16
  // every checkpoint when the vCPUs run again. The page writes a request kind into the word at
17
17
  // word_addr (guest memory) and notifies it; the ctl thread hands it to vCPU 0.
18
18
 
19
- import { CTL_CK_ATTACHES, CTL_CK_GO, CTL_CK_HOSTREQ, CTL_CK_POINTS } from './layout.js'
19
+ import { CTL_CK_ATTACHES, CTL_CK_GO, CTL_CK_HOSTREQ, CTL_CK_POINTS, CTL_CK_STREAM } from './layout.js'
20
20
 
21
21
  export const PAGE = 65536
22
22
  /** struct vm_snapshot_hdr (guest/vm/include/vm/snapshot.h), 336 bytes: field offsets read here. */
@@ -38,7 +38,7 @@ export const WINDOW_PAGES = 16384
38
38
  * back to back, CHUNK_PAGES each), pages (total), nonzero, scanMs, copyMs}. Reads the memory
39
39
  * without atomics: the machine is frozen.
40
40
  */
41
- export function scanMemory(memory, { now = () => performance.now(), chunkPages = CHUNK_PAGES, limitBytes = Infinity, verifyAbove = false, skip = null } = {}) {
41
+ export function scanMemory(memory, { now = () => performance.now(), chunkPages = CHUNK_PAGES, limitBytes = Infinity, verifyAbove = false, skip = null, copy = true } = {}) {
42
42
  const buf = memory.buffer
43
43
  // limitBytes: pages from here up are taken to be zero and are not read. Reading an untouched page of a shared
44
44
  // memory commits it in WebKit (W34: a full walk of a 3968 MiB memory added about 2.2 GB of footprint), so a caller
@@ -100,7 +100,8 @@ export function scanMemory(memory, { now = () => performance.now(), chunkPages =
100
100
  }
101
101
  const t1 = now()
102
102
  const chunks = []
103
- for (let k = 0; k < n; k += chunkPages) {
103
+ // copy false (IOS-2, a checkpoint saved straight to a store): the index only; the page reads the pages while the machine stays frozen
104
+ for (let k = 0; copy && k < n; k += chunkPages) {
104
105
  const m = Math.min(chunkPages, n - k)
105
106
  const c = new Uint8Array(m * PAGE)
106
107
  for (let j = 0; j < m; j++) c.set(new Uint8Array(buf, idx[k + j] * PAGE, PAGE), j * PAGE)
@@ -167,7 +168,9 @@ export function createCkptImports({ memory, ram = null, touched = () => null, ct
167
168
  const skips = desc ? touchedSkips(memory, desc) : null
168
169
  // RAM in memory 0 starts at a 64 KiB boundary (memory.grow), so a skipped page is all RAM
169
170
  if (skips && (Number(new BigUint64Array(memory.buffer, desc, 6)[2]) % PAGE) !== 0) throw new Error('guest RAM is not page-aligned in memory 0')
170
- cap = scanMemory(memory, { now, limitBytes: limit, verifyAbove: verifyBound, skip: skips ? skips.mem0 : null })
171
+ const copy = Atomics.load(ctl, CTL_CK_STREAM) !== 1
172
+ cap = scanMemory(memory, { now, limitBytes: limit, verifyAbove: verifyBound, skip: skips ? skips.mem0 : null, copy })
173
+ cap.streamed = !copy
171
174
  cap.limitBytes = Number.isFinite(limit) ? limit : null
172
175
  // the live g_rsv {brk, end} of vm.wasm 50c6495e / 3aef93fc (linear address 4251160), next to what vm_heap_top() says
173
176
  try {
@@ -177,14 +180,14 @@ export function createCkptImports({ memory, ram = null, touched = () => null, ct
177
180
  } catch {}
178
181
  cap.heapTopRet = heapTop()
179
182
  // the flat layout: guest RAM is a memory of its own (host/ram-mem.js), every page of it the guest's
180
- if (ram) cap.ram = scanMemory(ram, { now, skip: skips ? skips.ram : null })
183
+ if (ram) cap.ram = scanMemory(ram, { now, skip: skips ? skips.ram : null, copy })
181
184
  } catch (err) {
182
185
  post({ t: 'ckpt-mem-error', message: String(err && err.message ? err.message : err) })
183
186
  Atomics.wait(ctl, CTL_CK_GO, 0, goTimeoutMs)
184
187
  Atomics.store(ctl, CTL_CK_GO, 0)
185
188
  return -12
186
189
  }
187
- post({ t: 'ckpt-mem', index: cap.index, chunks: cap.chunks, pages: cap.pages, scannedPages: cap.scannedPages, skippedPages: cap.skippedPages, ramScannedPages: cap.ram?.scannedPages, ramSkippedPages: cap.ram?.skippedPages, aboveNonzero: cap.aboveNonzero, brkLive: cap.brkLive, endLive: cap.endLive, heapTopRet: cap.heapTopRet, limitBytes: cap.limitBytes, nonzero: cap.nonzero, scanMs: cap.scanMs, copyMs: cap.copyMs, ram: cap.ram ? { index: cap.ram.index, chunks: cap.ram.chunks, pages: cap.ram.pages, nonzero: cap.ram.nonzero, scanMs: cap.ram.scanMs, copyMs: cap.ram.copyMs } : null, doneAt: now() }, [cap.index.buffer, ...cap.chunks, ...(cap.ram ? [cap.ram.index.buffer, ...cap.ram.chunks] : [])])
190
+ post({ t: 'ckpt-mem', streamed: cap.streamed, index: cap.index, chunks: cap.chunks, pages: cap.pages, scannedPages: cap.scannedPages, skippedPages: cap.skippedPages, ramScannedPages: cap.ram?.scannedPages, ramSkippedPages: cap.ram?.skippedPages, aboveNonzero: cap.aboveNonzero, brkLive: cap.brkLive, endLive: cap.endLive, heapTopRet: cap.heapTopRet, limitBytes: cap.limitBytes, nonzero: cap.nonzero, scanMs: cap.scanMs, copyMs: cap.copyMs, ram: cap.ram ? { index: cap.ram.index, chunks: cap.ram.chunks, pages: cap.ram.pages, nonzero: cap.ram.nonzero, scanMs: cap.ram.scanMs, copyMs: cap.ram.copyMs } : null, doneAt: now() }, [cap.index.buffer, ...cap.chunks, ...(cap.ram ? [cap.ram.index.buffer, ...cap.ram.chunks] : [])])
188
191
  const r = Atomics.wait(ctl, CTL_CK_GO, 0, goTimeoutMs)
189
192
  const go = Atomics.load(ctl, CTL_CK_GO)
190
193
  Atomics.store(ctl, CTL_CK_GO, 0)
@@ -5,12 +5,16 @@
5
5
  // chunk(m) delivers the page's answer: bytes, or {error} (the page could not copy the chunk: out of memory).
6
6
  // page side answerNeed(ck, need, send): copies exactly the chunk asked for and sends {op:'chunk', saveId, si, ci, buf},
7
7
  // or {op:'chunk', ..., error} when the copy failed, so the save fails instead of waiting for ever.
8
+ // IOS-2: the buffer of the chunk last written goes back to the page with the next need ({need, ..., back}, transferred), and the page copies
9
+ // the next chunk into it ({buf: back, len}) when it is large enough: a save makes one 32 MiB buffer for a section of equal chunks, instead of a
10
+ // fresh copy per chunk that the Worker drops but frees only at its next GC (on a phone that was about 150 MiB of peak for a 234 MB checkpoint).
8
11
  //
9
12
  // One save at a time: `saving` is what refuses a second ("busy"); done() clears it, so a failed save does not block the next.
10
13
  import { CheckpointError } from './ckpt-file.js'
11
14
 
12
15
  export function createSaver(post) {
13
16
  let saving = null // {id, waits: Map key -> {resolve, reject}}
17
+ let back = null // the buffer of the chunk delivered last: written by the time the next chunk is asked for, so it goes back to the page
14
18
  return {
15
19
  get busy() {
16
20
  return !!saving
@@ -28,7 +32,10 @@ export function createSaver(post) {
28
32
  const f = () =>
29
33
  new Promise((resolve, reject) => {
30
34
  waits.set(`${si}:${ci}`, { resolve, reject })
31
- post({ need: true, saveId: m.id, si, ci })
35
+ const b = back
36
+ back = null
37
+ if (b) post({ need: true, saveId: m.id, si, ci, back: b }, [b])
38
+ else post({ need: true, saveId: m.id, si, ci })
32
39
  })
33
40
  f.size = len
34
41
  Object.defineProperty(f, 'length', { value: len })
@@ -44,19 +51,36 @@ export function createSaver(post) {
44
51
  if (!w) return false
45
52
  saving.waits.delete(`${m.si}:${m.ci}`)
46
53
  if (m.error) w.reject(new CheckpointError('io', `the page could not copy checkpoint chunk ${m.si}:${m.ci} (${m.error})`))
47
- else w.resolve(new Uint8Array(m.buf))
54
+ else {
55
+ back = m.buf
56
+ w.resolve(new Uint8Array(m.buf, 0, m.len ?? m.buf.byteLength))
57
+ }
48
58
  return true
49
59
  },
50
60
  /** The save ended, however it ended. */
51
61
  done() {
52
62
  saving = null
63
+ back = null
53
64
  },
54
65
  }
55
66
  }
56
67
 
57
68
  export function answerNeed(ck, need, send) {
58
69
  try {
59
- const buf = ck.sections[need.si].chunks[need.ci].slice().buffer
70
+ const src = ck.sections[need.si].chunks[need.ci]
71
+ const b = need.back
72
+ // a lazy chunk (IOS-2: pages of a frozen memory) copies itself into the buffer
73
+ const put = u8 => (src.lazy ? src.read(u8) : u8.set(src))
74
+ if (b instanceof ArrayBuffer && b.byteLength >= src.length) {
75
+ put(new Uint8Array(b, 0, src.length))
76
+ send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, buf: b, len: src.length }, [b])
77
+ return
78
+ }
79
+ let buf
80
+ if (src.lazy) {
81
+ buf = new ArrayBuffer(src.length)
82
+ put(new Uint8Array(buf))
83
+ } else buf = src.slice().buffer
60
84
  send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, buf }, [buf])
61
85
  } catch (e) {
62
86
  send({ op: 'chunk', saveId: need.saveId, si: need.si, ci: need.ci, error: String((e && e.message) || e) })
package/src/host/ckpt.js CHANGED
@@ -206,14 +206,40 @@ export function restoreFdTable(ctl, bytes, nfiles = Infinity) {
206
206
  * jit: {snap (jit-snap capture)}|null, svc: {port: {segments}}, ctl (bytes), names?: [[name, ip]] (W59: the network's
207
207
  * placeholder map, an optional section `net-names`; FORMAT_VERSION is unchanged and images without it still load)}
208
208
  */
209
+ /** IOS-2: pages per chunk of a streamed save (8 MiB): the page and the store's Worker hold one such buffer at a time. */
210
+ export const STREAM_CHUNK_PAGES = 128
211
+
212
+ /**
213
+ * IOS-2: the memory section of a checkpoint as lazy chunks over a frozen memory: {lazy: true, length, read(u8)}, CHUNK pages each, in the
214
+ * index's order. read() copies the chunk's pages into u8. Valid only while the machine stays at its checkpoint point (vm.checkpoint({save})).
215
+ */
216
+ export function memChunksOf(memory, index, chunkPages = STREAM_CHUNK_PAGES) {
217
+ const out = []
218
+ for (let k = 0; k < index.length; k += chunkPages) {
219
+ const m = Math.min(chunkPages, index.length - k)
220
+ const at = k
221
+ out.push({
222
+ lazy: true,
223
+ length: m * PAGE,
224
+ read(u8) {
225
+ const buf = memory.buffer
226
+ for (let j = 0; j < m; j++) u8.set(new Uint8Array(buf, index[at + j] * PAGE, PAGE), j * PAGE)
227
+ },
228
+ })
229
+ }
230
+ return out
231
+ }
232
+
233
+ const chunkOf = c => (c && c.lazy ? c : new Uint8Array(c))
234
+
209
235
  export function assembleCheckpoint(p) {
210
236
  const sections = []
211
237
  sections.push({ name: 'mem-index', chunks: [new Uint8Array(p.mem.index.buffer, p.mem.index.byteOffset, p.mem.index.byteLength)] })
212
- sections.push({ name: 'mem', chunks: p.mem.chunks.map(c => new Uint8Array(c)) })
238
+ sections.push({ name: 'mem', chunks: p.mem.chunks.map(chunkOf) })
213
239
  // the flat layout: the guest's RAM is a memory of its own, saved as its non-zero pages the same way
214
240
  if (p.mem.ram) {
215
241
  sections.push({ name: 'ram-index', chunks: [new Uint8Array(p.mem.ram.index.buffer, p.mem.ram.index.byteOffset, p.mem.ram.index.byteLength)] })
216
- sections.push({ name: 'ram', chunks: p.mem.ram.chunks.map(c => new Uint8Array(c)) })
242
+ sections.push({ name: 'ram', chunks: p.mem.ram.chunks.map(chunkOf) })
217
243
  }
218
244
  const header = {
219
245
  ...p.meta,
@@ -399,6 +425,24 @@ export function checkVmKeyFits(h, vmKey) {
399
425
  }
400
426
  }
401
427
 
428
+ /**
429
+ * IOS-2: the command line a checkpoint's boot had (its header's boot description) against this boot's. argv is part of the boot key, so a
430
+ * checkpoint of another command line (another --ram, --cpus, kernel command line) can never be restored here: a base snapshot is refused for it
431
+ * at its header, before its body is downloaded and decoded. A header without a description (older snapshots) is left to the full check.
432
+ */
433
+ export function checkArgvFits(h, argv) {
434
+ const theirs = h && h.bootDesc && Array.isArray(h.bootDesc.argv) ? h.bootDesc.argv : null
435
+ if (!theirs || JSON.stringify(theirs) === JSON.stringify(argv)) return
436
+ const at = name => {
437
+ const i = theirs.indexOf(name)
438
+ const j = argv.indexOf(name)
439
+ return i >= 0 && j >= 0 && theirs[i + 1] !== argv[j + 1] ? `${name} ${String(theirs[i + 1]).slice(0, 40)} -> ${name} ${String(argv[j + 1]).slice(0, 40)}` : null
440
+ }
441
+ const named = ['--ram', '--cpus', '--append', '--arch'].map(at).filter(Boolean)
442
+ const what = named.length ? named.join(', ') : `${theirs.slice(1).join(' ').slice(0, 80)} -> ${argv.slice(1).join(' ').slice(0, 80)}`
443
+ throw new CheckpointError('stale', `this checkpoint was taken by a boot with another command line (${what}): it restores only into the same one; it was refused at its header, before its body was read`)
444
+ }
445
+
402
446
  export function checkCheckpointFits(h, { vmKey, bootKey, bootDesc, maxPages, ramPages = 0, hasJit, fmaFused = true }) {
403
447
  if (h.format !== FORMAT_VERSION) throw new CheckpointError('version', `checkpoint format ${h.format}; this build restores format ${FORMAT_VERSION}`)
404
448
  if (h.vmKey !== vmKey) {
@@ -85,6 +85,9 @@ export const CTL_CK_ATTACHES = CKPT_BASE + 1 // wmd.ctl_attach calls so far (one
85
85
  export const CTL_CK_GO = CKPT_BASE + 2 // page -> vCPU 0 inside wmd.point: 0 wait, 1 return 0 (taken), 2 return -1 (failed)
86
86
  export const CTL_CK_POINTS = CKPT_BASE + 3 // wmd.point calls so far
87
87
  export const CTL_CK_RESTORED = CKPT_BASE + 4 // restore: the page has written the checkpoint's memory; the main thread may call vm_resume (1)
88
+ // IOS-2: page -> vCPU 0 before a checkpoint: 1 the point only finds the non-zero pages (no copy); the page reads them from the frozen memory while a
89
+ // store saves them (vm.checkpoint({save})), and lets vCPU 0 go after the save. 0: the point copies them, as before
90
+ export const CTL_CK_STREAM = CKPT_BASE + 5
88
91
 
89
92
  export const CTL_INTS = CKPT_BASE + 8
90
93
  export const CTL_BYTES = CTL_INTS * 4
package/wmdpack.wasm CHANGED
Binary file