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,241 @@
1
+ // stopbar/probe: the SDK for PROBE targets of any TS/JS project. A target describes a model as a list of actions
2
+ // (each with a generator of pure JSON data and a run that drives the real thing and checks it), invariants that hold
3
+ // after every step, and optional mutants (a damaged system under test) that the prober must catch.
4
+ // `stopbar probe --target <file>` loads the file (default export or export `target`) and runs it as any other target.
5
+ // This module has no imports besides node:util, so its source ships as the type declaration of `stopbar/probe`.
6
+ import {isDeepStrictEqual} from 'node:util'
7
+
8
+ // ---------------------------------------------------------------- the target contract (shared with the runner)
9
+ export type Mismatch = {step: number; action: unknown; what: string; expected: unknown; actual: unknown}
10
+ export type Outcome = {ok: true; steps: number; hooks?: number; cov: Record<string, number>} | {ok: false; mismatch: Mismatch}
11
+ export type ProbeRun = {seed: number; actions: unknown[]}
12
+ export interface ProbeTarget<R extends ProbeRun> {
13
+ name: string
14
+ description: string
15
+ /** Names of the mutants `execute` accepts as its third argument (for `stopbar probe --check-mutants`). */
16
+ mutants?: string[]
17
+ generate(seed: number): R
18
+ /** Runs `run` in the empty scratch directory `dir` (against `mutant` if given); never throws for a mismatch, returns it. */
19
+ execute(run: R, dir: string, mutant?: string): Promise<Outcome>
20
+ }
21
+
22
+ // ---------------------------------------------------------------- deterministic random numbers
23
+ export interface Rng {
24
+ /** A number in [0, 1). */
25
+ next(): number
26
+ /** An integer in [min, max], both included. */
27
+ int(min: number, max: number): number
28
+ /** true with probability p (default 0.5). */
29
+ bool(p?: number): boolean
30
+ pick<T>(xs: readonly T[]): T
31
+ /** A value chosen by weight (default weight 1). */
32
+ weighted<T>(xs: readonly {weight?: number; value: T}[]): T
33
+ }
34
+
35
+ /** xorshift32 on 32-bit integer arithmetic only: the same seed gives the same numbers on every platform. */
36
+ export function createRng(seed: number): Rng {
37
+ if (!Number.isFinite(seed)) throw new TypeError(`createRng: seed must be a finite number, got ${seed}`)
38
+ let x = Math.imul(Math.trunc(seed) | 0, 0x9e3779b1) >>> 0 || 7
39
+ const next = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 2 ** 32 }
40
+ const int = (min: number, max: number) => {
41
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || max < min) throw new RangeError(`rng.int: need integers min <= max, got ${min}, ${max}`)
42
+ return min + Math.floor(next() * (max - min + 1))
43
+ }
44
+ return {
45
+ next, int,
46
+ bool: (p = 0.5) => next() < p,
47
+ pick: <T>(xs: readonly T[]): T => {
48
+ if (!xs.length) throw new RangeError('rng.pick: empty list')
49
+ return xs[Math.floor(next() * xs.length)]
50
+ },
51
+ weighted: <T>(xs: readonly {weight?: number; value: T}[]): T => {
52
+ const w = xs.map((e) => e.weight ?? 1)
53
+ if (w.some((v) => !Number.isFinite(v) || v < 0)) throw new RangeError('rng.weighted: weights must be finite numbers >= 0')
54
+ const total = w.reduce((s, v) => s + v, 0)
55
+ if (!(total > 0)) throw new RangeError('rng.weighted: no value with a weight > 0')
56
+ let r = next() * total
57
+ for (let i = 0; i < xs.length; i++) { if (w[i] > 0 && r < w[i]) return xs[i].value; r -= w[i] }
58
+ for (let i = xs.length - 1; ; i--) if (w[i] > 0) return xs[i].value // rounding at the upper end
59
+ },
60
+ }
61
+ }
62
+
63
+ // ---------------------------------------------------------------- checks
64
+ /** Thrown by a failed check; `execute` turns it into `{ok: false, mismatch}` with the step and the action. */
65
+ export class MismatchError extends Error {
66
+ what: string
67
+ expected: unknown
68
+ actual: unknown
69
+ constructor(what: string, expected: unknown, actual: unknown) {
70
+ super(`${what}: expected ${show(expected)}, actual ${show(actual)}`)
71
+ this.name = 'MismatchError'
72
+ this.what = what; this.expected = expected; this.actual = actual
73
+ }
74
+ }
75
+
76
+ export interface Check {
77
+ /** Fails when `cond` is falsy. `actual` and `expected` (optional) go into the report. */
78
+ ok(what: string, cond: unknown, actual?: unknown, expected?: unknown): void
79
+ /** Fails unless `actual` and `expected` are deeply and strictly equal (node:util isDeepStrictEqual). */
80
+ eq(what: string, actual: unknown, expected: unknown): void
81
+ fail(what: string, expected: unknown, actual: unknown): never
82
+ }
83
+
84
+ export const check: Check = {
85
+ ok(what, cond, ...rest: unknown[]) {
86
+ if (!cond) throw new MismatchError(what, rest.length >= 2 ? rest[1] : 'truthy', rest.length >= 1 ? rest[0] : cond)
87
+ },
88
+ eq(what, actual, expected) { if (!isDeepStrictEqual(actual, expected)) throw new MismatchError(what, expected, actual) },
89
+ fail(what, expected, actual): never { throw new MismatchError(what, expected, actual) },
90
+ }
91
+
92
+ function show(v: unknown): string {
93
+ try { return JSON.stringify(v, jsonSafe) ?? String(v) } catch { return String(v) }
94
+ }
95
+ function jsonSafe(_k: string, v: unknown) {
96
+ if (typeof v === 'bigint') return `${v}n`
97
+ if (v instanceof Map) return {Map: [...v.entries()]}
98
+ if (v instanceof Set) return {Set: [...v.values()]}
99
+ if (typeof v === 'function' || typeof v === 'symbol') return String(v)
100
+ return v
101
+ }
102
+ /** Values of a mismatch travel as JSON between processes: make them plain data (BigInt, Map, Set, cycles). */
103
+ function plain(v: unknown): unknown {
104
+ if (v === undefined) return undefined
105
+ try { const s = JSON.stringify(v, jsonSafe); return s === undefined ? String(v) : JSON.parse(s) } catch { return String(v) }
106
+ }
107
+ function errorText(e: unknown): string {
108
+ if (e instanceof Error) return `${e.name}: ${e.message}`
109
+ return `thrown ${show(e)}`
110
+ }
111
+
112
+ // ---------------------------------------------------------------- defineModel
113
+ type Ctx = {seed: number; dir: string; mutant?: string}
114
+ type Awaitable<T> = T | Promise<T>
115
+ export type ActionSpec<S> = {
116
+ name: string
117
+ /** Relative frequency (default 1). */
118
+ weight?: number
119
+ /** Arguments of one step: pure data that survives JSON (saved in reproductions and regressions). */
120
+ gen(r: Rng): unknown
121
+ run(state: S, args: unknown, check: Check): Awaitable<void>
122
+ }
123
+ export type Invariant<S> = ((state: S, check: Check) => Awaitable<void>) | {name: string; check(state: S, check: Check): Awaitable<void>}
124
+ export type MutantSpec<S> = ((ctx: {seed: number; dir: string}) => Awaitable<S>) | {description?: string; setup(ctx: {seed: number; dir: string}): Awaitable<S>}
125
+ export type ModelSpec<S> = {
126
+ name: string
127
+ description: string
128
+ /** Steps per generated run (defaults 15 and 40). */
129
+ minSteps?: number
130
+ maxSteps?: number
131
+ setup(ctx: Ctx): Awaitable<S>
132
+ /** Called in `finally` after every run whose setup returned, also after a failure. */
133
+ teardown?(state: S, ctx: Ctx): Awaitable<void>
134
+ actions: ActionSpec<S>[]
135
+ /** Checked after setup (step -1) and after every step. */
136
+ invariants?: Invariant<S>[]
137
+ /** Each mutant replaces `setup` with a damaged system under test; the prober must find a mismatch on it. */
138
+ mutants?: Record<string, MutantSpec<S>>
139
+ }
140
+ export type ModelStep = {t: string; args?: unknown}
141
+ export type ModelRun = {seed: number; actions: ModelStep[]}
142
+
143
+ const NAT = (n: unknown) => typeof n === 'number' && Number.isSafeInteger(n) && n >= 0
144
+
145
+ export function defineModel<S>(spec: ModelSpec<S>): ProbeTarget<ModelRun> & {mutants: string[]} {
146
+ const bad = (why: string): never => { throw new TypeError(`defineModel(${JSON.stringify(spec?.name)}): ${why}`) }
147
+ if (!spec || typeof spec !== 'object') bad('spec must be an object')
148
+ if (typeof spec.name !== 'string' || !spec.name) bad('name must be a non-empty string')
149
+ if (typeof spec.description !== 'string') bad('description must be a string')
150
+ if (typeof spec.setup !== 'function') bad('setup must be a function')
151
+ if (spec.teardown !== undefined && typeof spec.teardown !== 'function') bad('teardown must be a function')
152
+ if (!Array.isArray(spec.actions) || !spec.actions.length) bad('actions must be a non-empty array')
153
+ const byName = new Map<string, ActionSpec<S>>()
154
+ for (const a of spec.actions) {
155
+ 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)')
156
+ if (byName.has(a.name)) bad(`action ${JSON.stringify(a.name)} is defined twice`)
157
+ if (a.weight !== undefined && !(Number.isFinite(a.weight) && a.weight >= 0)) bad(`action ${a.name}: weight must be a number >= 0`)
158
+ byName.set(a.name, a)
159
+ }
160
+ if (!spec.actions.some((a) => (a.weight ?? 1) > 0)) bad('at least one action needs a weight > 0')
161
+ const minSteps = spec.minSteps ?? 15, maxSteps = spec.maxSteps ?? 40
162
+ if (!NAT(minSteps) || !NAT(maxSteps) || minSteps > maxSteps) bad('minSteps and maxSteps must be integers with 0 <= minSteps <= maxSteps')
163
+ const invariants = (spec.invariants ?? []).map((inv, i) => {
164
+ if (typeof inv === 'function') return {name: '', check: inv}
165
+ if (inv && typeof inv.check === 'function' && typeof inv.name === 'string') return inv
166
+ return bad(`invariant ${i} must be a function or {name, check}`)
167
+ })
168
+ const mutants = new Map<string, (ctx: {seed: number; dir: string}) => Awaitable<S>>()
169
+ for (const [name, m] of Object.entries(spec.mutants ?? {})) {
170
+ if (typeof m === 'function') mutants.set(name, m)
171
+ else if (m && typeof m.setup === 'function') mutants.set(name, (ctx) => m.setup(ctx))
172
+ else bad(`mutant ${name} must be a setup function or {setup}`)
173
+ }
174
+ const weighted = spec.actions.map((a) => ({weight: a.weight ?? 1, value: a}))
175
+
176
+ return {
177
+ name: spec.name,
178
+ description: spec.description,
179
+ mutants: [...mutants.keys()],
180
+ generate(seed: number): ModelRun {
181
+ const r = createRng(seed)
182
+ const n = r.int(minSteps, maxSteps)
183
+ const actions: ModelStep[] = []
184
+ for (let i = 0; i < n; i++) {
185
+ const a = r.weighted(weighted)
186
+ const args = a.gen(r)
187
+ // the run in memory must equal its JSON copy (a saved reproduction replays exactly what was found)
188
+ actions.push(args === undefined ? {t: a.name} : {t: a.name, args: JSON.parse(JSON.stringify(args))})
189
+ }
190
+ return {seed, actions}
191
+ },
192
+ async execute(run: ModelRun, dir: string, mutant?: string): Promise<Outcome> {
193
+ const ctx: Ctx = mutant === undefined ? {seed: run.seed, dir} : {seed: run.seed, dir, mutant}
194
+ const cov: Record<string, number> = {}
195
+ let step = -1, action: unknown = null, state: S | undefined, ready = false
196
+ const mismatch = (e: unknown, prefix = ''): Outcome => e instanceof MismatchError
197
+ ? {ok: false, mismatch: {step, action, what: prefix + e.what, expected: plain(e.expected), actual: plain(e.actual)}}
198
+ : {ok: false, mismatch: {step, action, what: prefix ? `${prefix}exception` : 'exception', expected: 'no error', actual: errorText(e)}}
199
+ const checkAll = async () => {
200
+ for (const inv of invariants) {
201
+ try { await inv.check(state as S, check) } catch (e) { throw new Tagged(e, inv.name ? `invariant ${inv.name}: ` : '') }
202
+ }
203
+ }
204
+ let out: Outcome
205
+ try {
206
+ let setup: (c: Ctx) => Awaitable<S> = spec.setup
207
+ if (mutant !== undefined) {
208
+ const m = mutants.get(mutant)
209
+ if (!m) throw new MismatchError('unknown mutant', [...mutants.keys()], mutant)
210
+ setup = m
211
+ }
212
+ state = await setup(mutant === undefined ? ctx : {seed: run.seed, dir})
213
+ ready = true
214
+ await checkAll()
215
+ for (let i = 0; i < run.actions.length; i++) {
216
+ step = i; action = run.actions[i]
217
+ const a = run.actions[i] as ModelStep
218
+ const def = a && typeof a === 'object' ? byName.get(a.t) : undefined
219
+ if (!def) throw new MismatchError('unknown action', [...byName.keys()], a)
220
+ cov[def.name] = (cov[def.name] ?? 0) + 1
221
+ await def.run(state as S, a.args, check)
222
+ await checkAll()
223
+ }
224
+ out = {ok: true, steps: run.actions.length, cov}
225
+ } catch (e) {
226
+ out = e instanceof Tagged ? mismatch(e.cause, e.prefix) : mismatch(e)
227
+ }
228
+ if (ready && spec.teardown) {
229
+ try { await spec.teardown(state as S, ctx) } catch (e) { if (out.ok) out = mismatch(e, 'teardown: ') }
230
+ }
231
+ return out
232
+ },
233
+ }
234
+ }
235
+
236
+ /** An error from an invariant, with the invariant's name for the report. */
237
+ class Tagged {
238
+ cause: unknown
239
+ prefix: string
240
+ constructor(cause: unknown, prefix: string) { this.cause = cause; this.prefix = prefix }
241
+ }