@mobcomputing/mob 0.0.0-stage → 0.2.1

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/src/worker.mjs ADDED
@@ -0,0 +1,328 @@
1
+ // Runs one gate job in a child process, inside the OS sandbox (sandbox.mjs)
2
+ // and under Node's permission model: it may read only the files the job names,
3
+ // and may not write, spawn processes or use the network. Candidate code is untrusted and may hang or crash, so the parent
4
+ // enforces a timeout. Usage: node worker.mjs <job.json>; prints one JSON line.
5
+ // record: run every recorded input through a tree and write the outputs
6
+ // check: run every input through a candidate tree and compare with the record
7
+ // bench: paired timing of the candidate tree against the current main tree
8
+ // probe: the self-test's check of one planted bug (see selftest.mjs)
9
+ // Python projects run in runner.py processes, one per version of the code;
10
+ // this worker sends them inputs and compares and times their answers.
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import readline from 'node:readline'
14
+ import { spawn } from 'node:child_process'
15
+ import { performance } from 'node:perf_hooks'
16
+ import { fileURLToPath, pathToFileURL } from 'node:url'
17
+
18
+ process.emitWarning = () => {}
19
+ // If the gate stops (Ctrl-C, a killed hook), stop too instead of running on alone.
20
+ const parent = process.ppid
21
+ setInterval(() => { if (process.ppid !== parent) process.exit(1) }, 500).unref()
22
+ const job = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'))
23
+ const config = (await import(pathToFileURL(job.config).href)).default
24
+ const inputs = JSON.parse(fs.readFileSync(job.inputs, 'utf8'))
25
+ const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] }
26
+ const clip = (s, n = 600) => (s.length > n ? s.slice(0, n) + `… (${s.length} chars)` : s)
27
+
28
+ const PYTHON = config.language === 'python'
29
+ const RUNNER = path.join(path.dirname(fileURLToPath(import.meta.url)), 'runner.py')
30
+ const runners = []
31
+
32
+ // Each version of the code runs from its own folder. Outputs that mention it,
33
+ // such as error messages with file paths, show <tree> instead, so the folder
34
+ // name is never a difference.
35
+ const dirs = new Map()
36
+
37
+ async function load(dir, { coverage } = {}) {
38
+ if (PYTHON) return pythonRunner(dir, coverage)
39
+ const lib = await import(pathToFileURL(path.join(dir, config.entry)).href)
40
+ dirs.set(lib, [dir, pathToFileURL(dir).href])
41
+ return lib
42
+ }
43
+
44
+ const hideTree = (text, lib) => (dirs.get(lib) ?? []).reduce((s, d) => s.replaceAll(d, '<tree>'), text)
45
+
46
+ // A Python process for one tree. Calls go one at a time; if the process dies
47
+ // (a planted bug can kill it), that call's output says so and the next call
48
+ // starts a new one.
49
+ function pythonRunner(dir, coverage) {
50
+ const lib = { python: true, child: null, pending: null, exits: [] }
51
+ const start = () => {
52
+ // Each process writes its own coverage file; the self-test merges them.
53
+ const file = coverage && path.join(coverage, `python-${process.pid}-${lib.exits.length}.json`)
54
+ const args = ['-I', '-B', RUNNER, dir, config.entry, config.function, '--memory-mb', String(job.memoryMb ?? 4096), ...(file ? ['--coverage', file] : [])]
55
+ const child = spawn(process.env.MOB_PYTHON ?? config.python ?? 'python3', args, { stdio: ['pipe', 'pipe', 'ignore'] })
56
+ child.stdin.on('error', () => {})
57
+ lib.exits.push(new Promise((resolve) => child.on('exit', resolve)))
58
+ readline.createInterface({ input: child.stdout }).on('line', (line) => { if (lib.child !== child) return; const p = lib.pending; lib.pending = null; p?.(JSON.parse(line)) })
59
+ child.on('exit', () => { if (lib.child !== child) return; lib.child = null; const p = lib.pending; lib.pending = null; p?.({ out: 'THROWS: the Python process exited', ns: 0 }) })
60
+ lib.child = child
61
+ }
62
+ // With isolate, each input gets a new process, so no state carries over.
63
+ lib.call = (input) => new Promise((resolve) => {
64
+ if (!lib.child) start()
65
+ const child = lib.child
66
+ lib.pending = (answer) => { if (config.isolate) { lib.child = null; child.stdin.end() } resolve(answer) }
67
+ child.stdin.write(JSON.stringify(input) + '\n')
68
+ })
69
+ lib.close = () => { lib.child?.stdin.end(); return Promise.all(lib.exits) }
70
+ runners.push(lib)
71
+ return lib
72
+ }
73
+
74
+ // One output per input. Strings are kept as they are; anything else is stored
75
+ // as JSON. An exception is an output too, so a change cannot turn a throw into
76
+ // a value (or the reverse) without being refused.
77
+ async function outputOf(lib, input) {
78
+ if (lib.python) return (await lib.call(input)).out
79
+ try {
80
+ const value = await config.run(lib, input)
81
+ return hideTree(typeof value === 'string' ? value : JSON.stringify(value) ?? 'undefined', lib)
82
+ } catch (error) {
83
+ return `THROWS: ${hideTree(String(error?.message ?? error), lib).slice(0, 200)}`
84
+ }
85
+ }
86
+
87
+ async function record() {
88
+ const lib = await load(job.lib)
89
+ const out = []
90
+ for (const input of inputs) out.push(await outputOf(lib, input))
91
+ // Python line tracking can change what code does (pdfminer.six gives other
92
+ // text for one PDF with it on), so coverage comes from a second run whose
93
+ // outputs are not kept.
94
+ if (PYTHON && job.coverage) {
95
+ const traced = await load(job.lib, { coverage: job.coverage })
96
+ for (const input of inputs) await outputOf(traced, input)
97
+ }
98
+ fs.writeFileSync(job.out, JSON.stringify(out))
99
+ return { ok: true, inputs: inputs.length, throws: out.filter((s) => s.startsWith('THROWS: ')).length }
100
+ }
101
+
102
+ async function check() {
103
+ let lib
104
+ try { lib = await load(job.lib) } catch (error) { return { ok: false, reason: 'does-not-load', detail: String(error?.message ?? error).slice(0, 300) } }
105
+ const expected = JSON.parse(fs.readFileSync(job.expected, 'utf8'))
106
+ let differing = 0
107
+ let first = null
108
+ // Forward, then backward, so state carried from one input to the next is caught.
109
+ for (const pass of ['forward', 'backward']) {
110
+ const order = inputs.map((_, i) => (pass === 'forward' ? i : inputs.length - 1 - i))
111
+ for (const i of order) {
112
+ const got = await outputOf(lib, inputs[i])
113
+ if (got !== expected[i]) {
114
+ differing += 1
115
+ if (!first) first = { input: i, pass, given: clip(JSON.stringify(inputs[i])), expected: clip(expected[i]), got: clip(got) }
116
+ if (job.stopAtFirst) break
117
+ }
118
+ }
119
+ if (differing) break
120
+ }
121
+ return differing ? { ok: false, reason: 'changed-output', detail: `${differing} recorded output(s) differ`, first } : { ok: true, checked: inputs.length * 2 }
122
+ }
123
+
124
+ // The timing workload: every k-th input, so one pass stays short.
125
+ function workload() {
126
+ const step = Math.max(1, Math.ceil(inputs.length / (config.benchInputs ?? 500)))
127
+ return inputs.filter((_, i) => i % step === 0)
128
+ }
129
+
130
+ // Milliseconds one call takes. A Python runner times the call itself, so the
131
+ // time to send inputs between processes is not counted.
132
+ async function timed(lib, input) {
133
+ if (lib.python) return (await lib.call(input)).ns / 1e6
134
+ const t0 = performance.now()
135
+ await outputOf(lib, input)
136
+ return performance.now() - t0
137
+ }
138
+
139
+ // One paired sample runs both trees on every input of the workload,
140
+ // alternating which goes first, so GC and machine noise land on both sides.
141
+ async function pairedPass(a, b, work) {
142
+ let ta = 0
143
+ let tb = 0
144
+ for (let i = 0; i < work.length; i++) {
145
+ const [first, second] = i % 2 === 0 ? [a, b] : [b, a]
146
+ const x = await timed(first, work[i])
147
+ const y = await timed(second, work[i])
148
+ if (first === a) { ta += x; tb += y } else { tb += x; ta += y }
149
+ }
150
+ return [ta, tb]
151
+ }
152
+
153
+ // Largest 0-based k with P(Binomial(n, 1/2) <= k) <= alpha: the k-th smallest
154
+ // paired ratio is a one-sided (1 - alpha) lower bound on the median ratio.
155
+ function signRank(n, alpha) {
156
+ let k = 0
157
+ let cdf = 0
158
+ let term = 0.5 ** n
159
+ for (let j = 0; j < n; j++) {
160
+ cdf += term
161
+ if (cdf > alpha) break
162
+ k = j
163
+ term = (term * (n - j)) / (j + 1)
164
+ }
165
+ return k
166
+ }
167
+
168
+ async function bench() {
169
+ let candidate
170
+ try { candidate = await load(job.lib) } catch (error) { return { ok: false, reason: 'does-not-load', detail: String(error?.message ?? error).slice(0, 300) } }
171
+ const current = await load(job.current)
172
+ const work = workload()
173
+ for (let w = 0; w < 3; w++) await pairedPass(current, candidate, work)
174
+ const cur = []
175
+ const cand = []
176
+ const n = job.samples
177
+ for (let i = 0; i < n; i++) {
178
+ globalThis.gc?.()
179
+ let ta = 0
180
+ let tb = 0
181
+ while (ta < job.minMs) { const [x, y] = await pairedPass(current, candidate, work); ta += x; tb += y }
182
+ cur.push(ta)
183
+ cand.push(tb)
184
+ }
185
+ const ratios = cur.map((ms, i) => ms / cand[i]).sort((x, y) => x - y)
186
+ return { ok: true, samples: n, currentMs: median(cur), candidateMs: median(cand), speedup: median(ratios), lower: ratios[signRank(n, job.alpha)] }
187
+ }
188
+
189
+ // The self-test's search: the original tree and a tree with one planted bug
190
+ // give the same output on every recorded input. Change recorded inputs a
191
+ // little, again and again, until one makes the two disagree; then make that
192
+ // input as small as it can be while they still disagree.
193
+ const CHARS = ['-', '+', '0', '1', '9', ' ', '\n', '\t', '\\', "'", '"', ':', '#', ',', '.', '_', '/', '<', '>', '&', '*', '[', '{', 'é', '🙂', '\u0000', 'x', 'A']
194
+
195
+ function rng(seed) {
196
+ let s = seed >>> 0 || 1
197
+ return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32)
198
+ }
199
+
200
+ function collectStrings(value, out) {
201
+ if (out.length >= 2000) return out
202
+ if (typeof value === 'string') out.push(value)
203
+ else if (value && typeof value === 'object') for (const v of Object.values(value)) collectStrings(v, out)
204
+ return out
205
+ }
206
+
207
+ function* smaller(v) {
208
+ if (typeof v === 'string') {
209
+ for (let size = v.length >> 1; size >= 1; size >>= 1) for (let i = 0; i + size <= v.length; i += size) yield v.slice(0, i) + v.slice(i + size)
210
+ } else if (Array.isArray(v)) {
211
+ for (let i = 0; i < v.length; i++) yield [...v.slice(0, i), ...v.slice(i + 1)]
212
+ for (let i = 0; i < v.length; i++) for (const x of smaller(v[i])) { const a = [...v]; a[i] = x; yield a }
213
+ } else if (v && typeof v === 'object') {
214
+ for (const k of Object.keys(v)) { const o = { ...v }; delete o[k]; yield o }
215
+ for (const k of Object.keys(v)) for (const x of smaller(v[k])) yield { ...v, [k]: x }
216
+ } else if (typeof v === 'number' && v !== 0 && Number.isFinite(v)) {
217
+ yield 0
218
+ if (Math.trunc(v / 2) !== v) yield Math.trunc(v / 2)
219
+ }
220
+ }
221
+
222
+ // One planted bug, start to finish: the recorded inputs first (forward only,
223
+ // the inputs that caught other bugs first, stopping at the first difference),
224
+ // then inputs found for earlier bugs, then the search.
225
+ async function probe() {
226
+ let bugged
227
+ try { bugged = await load(job.lib) } catch { return { ok: true, caught: true } }
228
+ if (job.check) {
229
+ const expected = JSON.parse(fs.readFileSync(job.expected, 'utf8'))
230
+ const first = new Set(job.order ?? [])
231
+ for (const i of [...first, ...inputs.keys()].filter((i, k) => k < first.size || !first.has(i))) {
232
+ if ((await outputOf(bugged, inputs[i])) !== expected[i]) return { ok: true, caught: true, input: i }
233
+ }
234
+ }
235
+ if (!job.hunt) return { ok: true, caught: false }
236
+ process.stdout.write('{"phase":"hunt"}\n')
237
+ const original = await load(job.current)
238
+ const started = performance.now()
239
+ const differs = async (c) => {
240
+ const a = await outputOf(original, c)
241
+ const b = await outputOf(bugged, c)
242
+ return a === b ? null : [a, b]
243
+ }
244
+ for (const c of job.pool ?? []) {
245
+ const d = await differs(c)
246
+ if (d) return { ok: true, caught: false, found: true, input: c, expected: clip(d[0], 200), got: clip(d[1], 200), tries: 0, ms: 0, pool: true }
247
+ }
248
+ const r = rng(job.seed)
249
+ const pick = (xs) => xs[Math.floor(r() * xs.length)]
250
+ const sized = inputs.map((v) => [JSON.stringify(v).length, v]).sort((a, b) => a[0] - b[0]).map(([, v]) => v)
251
+ const strings = collectStrings(inputs, [])
252
+ const words = [...job.words, ...CHARS]
253
+ const numbers = [0, 1, -1, ...job.words.map(Number).filter(Number.isFinite)]
254
+ const kind = (c) => (/\d/.test(c) ? 0 : /\p{L}/u.test(c) ? 1 : /\s/.test(c) ? 2 : 3)
255
+ const token = () => {
256
+ if (r() < 0.5) return pick(words)
257
+ const o = pick(strings) ?? ''
258
+ const j = Math.floor(r() * o.length)
259
+ return o.slice(j, j + 1 + Math.floor(r() * 8))
260
+ }
261
+ const mutateString = (s) => {
262
+ let i = Math.floor(r() * (s.length + 1))
263
+ // Half the time, a place where letters, digits, spaces or symbols meet.
264
+ if (s.length > 1 && r() < 0.5) for (let t = 0; t < 8; t++) { const j = 1 + Math.floor(r() * (s.length - 1)); if (kind(s[j - 1]) !== kind(s[j])) { i = j; break } }
265
+ const len = 1 + Math.floor(r() * 4)
266
+ switch (Math.floor(r() * 7)) {
267
+ case 0: case 1: return s.slice(0, i) + token() + s.slice(i)
268
+ case 2: return s.slice(0, i) + s.slice(i + len)
269
+ case 3: return s.slice(0, i) + token() + s.slice(i + len)
270
+ case 4: return s.slice(0, i) + s.slice(i, i + len * 4) + s.slice(i)
271
+ case 5: return s.slice(0, i)
272
+ default: {
273
+ const c = s[i]
274
+ if (!c) return s + token()
275
+ return s.slice(0, i) + (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()) + s.slice(i + 1)
276
+ }
277
+ }
278
+ }
279
+ const mutate = (v) => {
280
+ if (typeof v === 'string') return mutateString(v)
281
+ if (typeof v === 'number') return pick([-v, v + 1, v - 1, v * 2, Math.trunc(v / 2), v + 0.5, pick(numbers)])
282
+ if (typeof v === 'boolean') return !v
283
+ if (v === null) return pick([0, '', false, []])
284
+ if (Array.isArray(v)) {
285
+ const a = [...v]
286
+ const i = Math.floor(r() * a.length)
287
+ const op = a.length ? Math.floor(r() * 6) : 5
288
+ if (op <= 1) a[i] = mutate(a[i])
289
+ else if (op === 2) a.splice(i, 1)
290
+ else if (op === 3) a.splice(i, 0, a[i])
291
+ else if (op === 4) a.reverse()
292
+ else a.push(a.length ? pick(a) : 0)
293
+ return a
294
+ }
295
+ const keys = Object.keys(v)
296
+ if (!keys.length) return v
297
+ const o = { ...v }
298
+ const k = pick(keys)
299
+ if (r() < 0.8) o[k] = mutate(o[k]); else delete o[k]
300
+ return o
301
+ }
302
+ const deadline = performance.now() + job.budgetMs
303
+ let tries = 0
304
+ while (performance.now() < deadline) {
305
+ let c = sized[Math.floor(r() ** 2 * sized.length)]
306
+ for (let k = 1 + Math.floor(r() * 3); k > 0; k--) c = mutate(c)
307
+ try { c = JSON.parse(JSON.stringify(c) ?? 'null') } catch { continue }
308
+ tries++
309
+ if (!(await differs(c))) continue
310
+ const stop = performance.now() + job.budgetMs / 2
311
+ for (let improved = true; improved && performance.now() < stop;) {
312
+ improved = false
313
+ for (const x of smaller(c)) {
314
+ if (performance.now() >= stop) break
315
+ if (await differs(x)) { c = x; improved = true; break }
316
+ }
317
+ }
318
+ const [a, b] = await differs(c)
319
+ return { ok: true, caught: false, found: true, input: c, expected: clip(a, 200), got: clip(b, 200), tries, ms: Math.round(performance.now() - started) }
320
+ }
321
+ return { ok: true, caught: false, found: false, tries }
322
+ }
323
+
324
+ const modes = { record, check, bench, probe }
325
+ const result = await modes[job.mode]()
326
+ await Promise.all(runners.map((r) => r.close()))
327
+ process.stdout.write(JSON.stringify(result) + '\n')
328
+ process.exit(0)