stopbar 1.1.3 → 1.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.
@@ -0,0 +1,217 @@
1
+ // Built from src/probe/init.ts by scripts/build.ts. Do not edit.
2
+ // stopbar probe init: writes a starter PROBE target, in TypeScript (defineModel from 'stopbar/probe') or in Python
3
+ // (the NDJSON protocol of --cmd, standard library only). Both hold the same model with 2 actions, 1 invariant and
4
+ // 2 mutants, so `--check-mutants` passes on the template as written.
5
+ import {existsSync, mkdirSync, writeFileSync} from 'node:fs'
6
+ import {isAbsolute, join, relative, resolve} from 'node:path'
7
+ import {ProbeError} from './stdio.js'
8
+
9
+
10
+
11
+
12
+ const NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/
13
+
14
+ const ZERO_FP = String.raw`Zero false positives: a failure must always be a real bug.
15
+ 1. gen draws its arguments only from the seeded random numbers and returns plain JSON data:
16
+ the same seed gives the same run on every machine.
17
+ 2. The model is the oracle: compare the system with the model, never with itself.
18
+ 3. No clock, network or shared global state; files only under the scratch directory of the run.
19
+ 4. A mutant is a small, real bug; --check-mutants passes only when the prober catches every one.`
20
+
21
+ const TS = String.raw`// PROBE target __NAME__, written by 'stopbar probe init'. Run it:
22
+ // __RUN__
23
+ // Replace UniqueList with an import of your own code, keep the model (a plain array) and add actions.
24
+ __ZERO_FP__
25
+ import {defineModel} from 'stopbar/probe'
26
+
27
+ type Bug = '' | 'dupes' | 'noRemove'
28
+
29
+ /** The system under test: a list of numbers without duplicates. */
30
+ class UniqueList {
31
+ items: number[] = []
32
+ bug: Bug
33
+ constructor(bug: Bug = '') { this.bug = bug }
34
+ /** Adds x unless it is already there; true if it was added. */
35
+ add(x: number): boolean {
36
+ if (this.bug !== 'dupes' && this.items.includes(x)) return false
37
+ this.items.push(x)
38
+ return true
39
+ }
40
+ /** Removes x; true if it was there. */
41
+ remove(x: number): boolean {
42
+ const i = this.items.indexOf(x)
43
+ if (i < 0) return false
44
+ if (this.bug !== 'noRemove') this.items.splice(i, 1)
45
+ return true
46
+ }
47
+ }
48
+
49
+ type State = {list: UniqueList; model: number[]}
50
+ const fresh = (bug: Bug = ''): State => ({list: new UniqueList(bug), model: []})
51
+
52
+ export default defineModel<State>({
53
+ name: '__NAME__',
54
+ description: 'a list without duplicates vs an array model',
55
+ minSteps: 10,
56
+ maxSteps: 30,
57
+ setup: () => fresh(),
58
+ actions: [
59
+ {
60
+ name: 'add', weight: 2,
61
+ gen: (r) => r.int(0, 9),
62
+ run: (s, x: number, check) => {
63
+ const expected = !s.model.includes(x)
64
+ check.eq('add result', s.list.add(x), expected)
65
+ if (expected) s.model.push(x)
66
+ },
67
+ },
68
+ {
69
+ name: 'remove',
70
+ gen: (r) => r.int(0, 9),
71
+ run: (s, x: number, check) => {
72
+ const i = s.model.indexOf(x)
73
+ check.eq('remove result', s.list.remove(x), i >= 0)
74
+ if (i >= 0) s.model.splice(i, 1)
75
+ },
76
+ },
77
+ ],
78
+ invariants: [{name: 'contents', check: (s, check) => check.eq('contents', s.list.items, s.model)}],
79
+ mutants: {
80
+ M1_allowDuplicates: {description: 'add accepts a value that is already there', setup: () => fresh('dupes')},
81
+ M2_removeKeeps: {description: 'remove reports success but keeps the value', setup: () => fresh('noRemove')},
82
+ },
83
+ })
84
+ `
85
+
86
+ const PY = String.raw`#!/usr/bin/env python3
87
+ # PROBE target __NAME__, written by 'stopbar probe init'. Run it:
88
+ # __RUN__
89
+ # It speaks NDJSON on stdin/stdout, one JSON object per line: info, generate, execute (stdout is for the protocol
90
+ # only; print logs to stderr). Standard library only. Replace UniqueList with an import of your own code, keep the
91
+ # model (a plain list) and add actions.
92
+ __ZERO_FP__
93
+ import json
94
+ import random
95
+ import sys
96
+
97
+ NAME = "__NAME__"
98
+ BUGS = {None: "", "M1_allowDuplicates": "dupes", "M2_removeKeeps": "noRemove"}
99
+
100
+
101
+ class UniqueList:
102
+ """The system under test: a list of numbers without duplicates."""
103
+
104
+ def __init__(self, bug=""):
105
+ self.items, self.bug = [], bug
106
+
107
+ def add(self, x):
108
+ if self.bug != "dupes" and x in self.items:
109
+ return False
110
+ self.items.append(x)
111
+ return True
112
+
113
+ def remove(self, x):
114
+ if x not in self.items:
115
+ return False
116
+ if self.bug != "noRemove":
117
+ self.items.remove(x)
118
+ return True
119
+
120
+
121
+ class Mismatch(Exception):
122
+ def __init__(self, what, expected, actual):
123
+ super().__init__(what)
124
+ self.what, self.expected, self.actual = what, expected, actual
125
+
126
+
127
+ def eq(what, actual, expected):
128
+ if actual != expected:
129
+ raise Mismatch(what, expected, actual)
130
+
131
+
132
+ def generate(seed):
133
+ r = random.Random(seed)
134
+ names = r.choices(["add", "remove"], weights=[2, 1], k=r.randint(10, 30))
135
+ return {"seed": seed, "actions": [{"t": t, "args": r.randint(0, 9)} for t in names]}
136
+
137
+
138
+ def execute(run, mutant=None):
139
+ step, action, cov = -1, None, {}
140
+ try:
141
+ if mutant not in BUGS:
142
+ raise Mismatch("unknown mutant", [m for m in BUGS if m], mutant)
143
+ lst, model = UniqueList(BUGS[mutant]), []
144
+ eq("invariant contents: contents", lst.items, model)
145
+ for step, action in enumerate(run["actions"]):
146
+ t, x = action.get("t"), action.get("args")
147
+ if t == "add":
148
+ expected = x not in model
149
+ eq("add result", lst.add(x), expected)
150
+ if expected:
151
+ model.append(x)
152
+ elif t == "remove":
153
+ there = x in model
154
+ eq("remove result", lst.remove(x), there)
155
+ if there:
156
+ model.remove(x)
157
+ else:
158
+ raise Mismatch("unknown action", ["add", "remove"], action)
159
+ cov[t] = cov.get(t, 0) + 1
160
+ eq("invariant contents: contents", lst.items, model)
161
+ except Mismatch as m:
162
+ return {"ok": False, "mismatch": {"step": step, "action": action, "what": m.what, "expected": m.expected, "actual": m.actual}}
163
+ except Exception as e: # a crash of the code under test is a finding, not a protocol error
164
+ return {"ok": False, "mismatch": {"step": step, "action": action, "what": "exception", "expected": "no error", "actual": "%s: %s" % (type(e).__name__, e)}}
165
+ return {"ok": True, "steps": len(run["actions"]), "cov": cov}
166
+
167
+
168
+ def main():
169
+ for line in iter(sys.stdin.readline, ""):
170
+ if not line.strip():
171
+ continue
172
+ req = json.loads(line)
173
+ op = req.get("op")
174
+ if op == "info":
175
+ res = {"name": NAME, "description": "a list without duplicates vs a list model", "mutants": [m for m in BUGS if m]}
176
+ elif op == "generate":
177
+ res = generate(req["seed"])
178
+ elif op == "execute":
179
+ res = execute(req["run"], req.get("mutant"))
180
+ else:
181
+ res = {"error": "unknown op %r" % op}
182
+ sys.stdout.write(json.dumps(res) + "\n")
183
+ sys.stdout.flush()
184
+
185
+
186
+ if __name__ == "__main__":
187
+ main()
188
+ `
189
+
190
+ /** A path for the printed command: relative to `cwd` when inside it, with forward slashes. */
191
+ function shown(file , cwd ) {
192
+ const r = relative(cwd, file)
193
+ return (r && !r.startsWith('..') && !isAbsolute(r) ? r : file).replace(/\\/g, '/')
194
+ }
195
+
196
+ export function initProbe(o = {}) {
197
+ const lang = o.lang ?? 'ts'
198
+ if (lang !== 'ts' && lang !== 'py') throw new ProbeError(`probe init: --lang must be ts or py, got ${JSON.stringify(lang)}`)
199
+ const name = o.name ?? 'sample'
200
+ if (!NAME.test(name)) throw new ProbeError(`probe init: --name ${JSON.stringify(name)} must start with a letter and hold only letters, digits, - and _ (at most 64), no path`)
201
+ const cwd = o.cwd ?? process.cwd()
202
+ const base = o.repo ? resolve(cwd, o.repo) : cwd
203
+ const dir = resolve(base, o.out ?? 'probes')
204
+ const file = join(dir, lang === 'ts' ? `${name}.probe.ts` : `${name}_probe.py`)
205
+ if (existsSync(file) && !o.force) throw new ProbeError(`probe init: ${file} exists; pass --force to overwrite it`)
206
+ const py = process.platform === 'win32' ? 'python' : 'python3'
207
+ const command = lang === 'ts'
208
+ ? `stopbar probe --target ${shown(file, cwd)} --check-mutants`
209
+ : `stopbar probe --cmd "${py} ${shown(file, cwd)}" --check-mutants`
210
+ const text = (lang === 'ts' ? TS : PY)
211
+ .replace('__ZERO_FP__', ZERO_FP.split('\n').map((l) => (lang === 'ts' ? '// ' : '# ') + l).join('\n'))
212
+ .replaceAll('__NAME__', name).replace('__RUN__', command)
213
+ mkdirSync(dir, {recursive: true})
214
+ writeFileSync(file, text)
215
+ const needs = lang === 'ts' ? `\n (needs stopbar in the project, so that 'stopbar/probe' resolves: npm install --save-dev stopbar)` : ''
216
+ return {file, lang, command, message: `wrote ${file}\nrun it:\n ${command}${needs}`}
217
+ }
@@ -0,0 +1,242 @@
1
+ // Built from src/probe/sdk.ts by scripts/build.ts. Do not edit.
2
+ // stopbar/probe: the SDK for PROBE targets of any TS/JS project. A target describes a model as a list of actions
3
+ // (each with a generator of pure JSON data and a run that drives the real thing and checks it), invariants that hold
4
+ // after every step, and optional mutants (a damaged system under test) that the prober must catch.
5
+ // `stopbar probe --target <file>` loads the file (default export or export `target`) and runs it as any other target.
6
+ // This module has no imports besides node:util, so its source ships as the type declaration of `stopbar/probe`.
7
+ import {isDeepStrictEqual} from 'node:util'
8
+
9
+ // ---------------------------------------------------------------- the target contract (shared with the runner)
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ // ---------------------------------------------------------------- deterministic random numbers
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+ /** xorshift32 on 32-bit integer arithmetic only: the same seed gives the same numbers on every platform. */
37
+ export function createRng(seed ) {
38
+ if (!Number.isFinite(seed)) throw new TypeError(`createRng: seed must be a finite number, got ${seed}`)
39
+ let x = Math.imul(Math.trunc(seed) | 0, 0x9e3779b1) >>> 0 || 7
40
+ const next = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 }
41
+ const int = (min , max ) => {
42
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max < min) throw new RangeError(`rng.int: need integers min <= max, got ${min}, ${max}`)
43
+ return min + Math.floor(next() * (max - min + 1))
44
+ }
45
+ return {
46
+ next, int,
47
+ bool: (p = 0.5) => next() < p,
48
+ pick: (xs ) => {
49
+ if (!xs.length) throw new RangeError('rng.pick: empty list')
50
+ return xs[Math.floor(next() * xs.length)]
51
+ },
52
+ weighted: (xs ) => {
53
+ const w = xs.map((e) => e.weight ?? 1)
54
+ if (w.some((v) => !Number.isFinite(v) || v < 0)) throw new RangeError('rng.weighted: weights must be finite numbers >= 0')
55
+ const total = w.reduce((s, v) => s + v, 0)
56
+ if (!(total > 0)) throw new RangeError('rng.weighted: no value with a weight > 0')
57
+ let r = next() * total
58
+ for (let i = 0; i < xs.length; i++) { if (w[i] > 0 && r < w[i]) return xs[i].value; r -= w[i] }
59
+ for (let i = xs.length - 1; ; i--) if (w[i] > 0) return xs[i].value // rounding at the upper end
60
+ },
61
+ }
62
+ }
63
+
64
+ // ---------------------------------------------------------------- checks
65
+ /** Thrown by a failed check; `execute` turns it into `{ok: false, mismatch}` with the step and the action. */
66
+ export class MismatchError extends Error {
67
+ what
68
+ expected
69
+ actual
70
+ constructor(what , expected , actual ) {
71
+ super(`${what}: expected ${show(expected)}, actual ${show(actual)}`)
72
+ this.name = 'MismatchError'
73
+ this.what = what; this.expected = expected; this.actual = actual
74
+ }
75
+ }
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+ export const check = {
86
+ ok(what, cond, ...rest ) {
87
+ if (!cond) throw new MismatchError(what, rest.length >= 2 ? rest[1] : 'truthy', rest.length >= 1 ? rest[0] : cond)
88
+ },
89
+ eq(what, actual, expected) { if (!isDeepStrictEqual(actual, expected)) throw new MismatchError(what, expected, actual) },
90
+ fail(what, expected, actual) { throw new MismatchError(what, expected, actual) },
91
+ }
92
+
93
+ function show(v ) {
94
+ try { return JSON.stringify(v, jsonSafe) ?? String(v) } catch { return String(v) }
95
+ }
96
+ function jsonSafe(_k , v ) {
97
+ if (typeof v === 'bigint') return `${v}n`
98
+ if (v instanceof Map) return {Map: [...v.entries()]}
99
+ if (v instanceof Set) return {Set: [...v.values()]}
100
+ if (typeof v === 'function' || typeof v === 'symbol') return String(v)
101
+ return v
102
+ }
103
+ /** Values of a mismatch travel as JSON between processes: make them plain data (BigInt, Map, Set, cycles). */
104
+ function plain(v ) {
105
+ if (v === undefined) return undefined
106
+ try { const s = JSON.stringify(v, jsonSafe); return s === undefined ? String(v) : JSON.parse(s) } catch { return String(v) }
107
+ }
108
+ function errorText(e ) {
109
+ if (e instanceof Error) return `${e.name}: ${e.message}`
110
+ return `thrown ${show(e)}`
111
+ }
112
+
113
+ // ---------------------------------------------------------------- defineModel
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+ const NAT = (n ) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
145
+
146
+ export function defineModel (spec ) {
147
+ const bad = (why ) => { throw new TypeError(`defineModel(${JSON.stringify(spec?.name)}): ${why}`) }
148
+ if (!spec || typeof spec !== 'object') bad('spec must be an object')
149
+ if (typeof spec.name !== 'string' || !spec.name) bad('name must be a non-empty string')
150
+ if (typeof spec.description !== 'string') bad('description must be a string')
151
+ if (typeof spec.setup !== 'function') bad('setup must be a function')
152
+ if (spec.teardown !== undefined && typeof spec.teardown !== 'function') bad('teardown must be a function')
153
+ if (!Array.isArray(spec.actions) || !spec.actions.length) bad('actions must be a non-empty array')
154
+ const byName = new Map ()
155
+ for (const a of spec.actions) {
156
+ if (!a || typeof a.name !== 'string' || !a.name || typeof a.gen !== 'function' || typeof a.run !== 'function') bad('every action needs a name, gen(r) and run(state, args, check)')
157
+ if (byName.has(a.name)) bad(`action ${JSON.stringify(a.name)} is defined twice`)
158
+ if (a.weight !== undefined && !(Number.isFinite(a.weight) && a.weight >= 0)) bad(`action ${a.name}: weight must be a number >= 0`)
159
+ byName.set(a.name, a)
160
+ }
161
+ if (!spec.actions.some((a) => (a.weight ?? 1) > 0)) bad('at least one action needs a weight > 0')
162
+ const minSteps = spec.minSteps ?? 15, maxSteps = spec.maxSteps ?? 40
163
+ if (!NAT(minSteps) || !NAT(maxSteps) || minSteps > maxSteps) bad('minSteps and maxSteps must be integers with 0 <= minSteps <= maxSteps')
164
+ const invariants = (spec.invariants ?? []).map((inv, i) => {
165
+ if (typeof inv === 'function') return {name: '', check: inv}
166
+ if (inv && typeof inv.check === 'function' && typeof inv.name === 'string') return inv
167
+ return bad(`invariant ${i} must be a function or {name, check}`)
168
+ })
169
+ const mutants = new Map ()
170
+ for (const [name, m] of Object.entries(spec.mutants ?? {})) {
171
+ if (typeof m === 'function') mutants.set(name, m)
172
+ else if (m && typeof m.setup === 'function') mutants.set(name, (ctx) => m.setup(ctx))
173
+ else bad(`mutant ${name} must be a setup function or {setup}`)
174
+ }
175
+ const weighted = spec.actions.map((a) => ({weight: a.weight ?? 1, value: a}))
176
+
177
+ return {
178
+ name: spec.name,
179
+ description: spec.description,
180
+ mutants: [...mutants.keys()],
181
+ generate(seed ) {
182
+ const r = createRng(seed)
183
+ const n = r.int(minSteps, maxSteps)
184
+ const actions = []
185
+ for (let i = 0; i < n; i++) {
186
+ const a = r.weighted(weighted)
187
+ const args = a.gen(r)
188
+ // the run in memory must equal its JSON copy (a saved reproduction replays exactly what was found)
189
+ actions.push(args === undefined ? {t: a.name} : {t: a.name, args: JSON.parse(JSON.stringify(args))})
190
+ }
191
+ return {seed, actions}
192
+ },
193
+ async execute(run , dir , mutant ) {
194
+ const ctx = mutant === undefined ? {seed: run.seed, dir} : {seed: run.seed, dir, mutant}
195
+ const cov = {}
196
+ let step = -1, action = null, state , ready = false
197
+ const mismatch = (e , prefix = '') => e instanceof MismatchError
198
+ ? {ok: false, mismatch: {step, action, what: prefix + e.what, expected: plain(e.expected), actual: plain(e.actual)}}
199
+ : {ok: false, mismatch: {step, action, what: prefix ? `${prefix}exception` : 'exception', expected: 'no error', actual: errorText(e)}}
200
+ const checkAll = async () => {
201
+ for (const inv of invariants) {
202
+ try { await inv.check(state , check) } catch (e) { throw new Tagged(e, inv.name ? `invariant ${inv.name}: ` : '') }
203
+ }
204
+ }
205
+ let out
206
+ try {
207
+ let setup = spec.setup
208
+ if (mutant !== undefined) {
209
+ const m = mutants.get(mutant)
210
+ if (!m) throw new MismatchError('unknown mutant', [...mutants.keys()], mutant)
211
+ setup = m
212
+ }
213
+ state = await setup(mutant === undefined ? ctx : {seed: run.seed, dir})
214
+ ready = true
215
+ await checkAll()
216
+ for (let i = 0; i < run.actions.length; i++) {
217
+ step = i; action = run.actions[i]
218
+ const a = run.actions[i]
219
+ const def = a && typeof a === 'object' ? byName.get(a.t) : undefined
220
+ if (!def) throw new MismatchError('unknown action', [...byName.keys()], a)
221
+ cov[def.name] = (cov[def.name] ?? 0) + 1
222
+ await def.run(state , a.args, check)
223
+ await checkAll()
224
+ }
225
+ out = {ok: true, steps: run.actions.length, cov}
226
+ } catch (e) {
227
+ out = e instanceof Tagged ? mismatch(e.cause, e.prefix) : mismatch(e)
228
+ }
229
+ if (ready && spec.teardown) {
230
+ try { await spec.teardown(state , ctx) } catch (e) { if (out.ok) out = mismatch(e, 'teardown: ') }
231
+ }
232
+ return out
233
+ },
234
+ }
235
+ }
236
+
237
+ /** An error from an invariant, with the invariant's name for the report. */
238
+ class Tagged {
239
+ cause
240
+ prefix
241
+ constructor(cause , prefix ) { this.cause = cause; this.prefix = prefix }
242
+ }