dsh-logicprobe 0.3.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/LICENSE +21 -0
- package/README.en-US.md +237 -0
- package/README.md +234 -0
- package/cordis.patch.yml +12 -0
- package/lib/engine.js +1103 -0
- package/lib/index.js +277 -0
- package/lib/tool.js +45 -0
- package/lib/types/engine.d.ts +133 -0
- package/lib/types/index.d.ts +46 -0
- package/lib/types/tool.d.ts +8 -0
- package/package.json +81 -0
- package/skills/logicprobe/SKILL.md +266 -0
- package/skills/logicprobe/references/dsh-model-schema.md +104 -0
- package/skills/logicprobe/references/logic-verification-guide.md +413 -0
- package/skills/logicprobe/references/verification-harness.py +582 -0
- package/src/engine.ts +1164 -0
- package/src/index.ts +301 -0
- package/src/tool.ts +48 -0
package/lib/engine.js
ADDED
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
export const ENGINE_SCHEMA_VERSION = 1;
|
|
3
|
+
const DEFAULT_MAX_STATES = 10_000;
|
|
4
|
+
const DEFAULT_MAX_PERMUTATION_EVENTS = 5;
|
|
5
|
+
function stableStringify(value) {
|
|
6
|
+
if (value === null || typeof value !== 'object')
|
|
7
|
+
return JSON.stringify(value);
|
|
8
|
+
if (Array.isArray(value))
|
|
9
|
+
return '[' + value.map((item) => stableStringify(item)).join(',') + ']';
|
|
10
|
+
const record = value;
|
|
11
|
+
return '{' + Object.keys(record).sort().map((key) => JSON.stringify(key) + ':' + stableStringify(record[key])).join(',') + '}';
|
|
12
|
+
}
|
|
13
|
+
export function modelHash(model) {
|
|
14
|
+
return createHash('sha256').update(stableStringify(model)).digest('hex');
|
|
15
|
+
}
|
|
16
|
+
export function validateModel(input) {
|
|
17
|
+
const errors = [];
|
|
18
|
+
const bad = (path, message) => {
|
|
19
|
+
errors.push(path + ': ' + message);
|
|
20
|
+
};
|
|
21
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input)) {
|
|
22
|
+
return { ok: false, errors: ['model: must be an object'] };
|
|
23
|
+
}
|
|
24
|
+
const root = input;
|
|
25
|
+
if (root.schemaVersion !== 1)
|
|
26
|
+
bad('schemaVersion', 'must be 1');
|
|
27
|
+
if (typeof root.init !== 'string' || root.init.length === 0)
|
|
28
|
+
bad('init', 'must be a non-empty string');
|
|
29
|
+
if (!Array.isArray(root.states) || root.states.length === 0) {
|
|
30
|
+
bad('states', 'must be a non-empty array');
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
const seen = new Set();
|
|
34
|
+
root.states.forEach((entry, index) => {
|
|
35
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
36
|
+
bad('states[' + index + ']', 'must be an object');
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const state = entry;
|
|
40
|
+
if (typeof state.id !== 'string' || state.id.length === 0)
|
|
41
|
+
bad('states[' + index + '].id', 'must be a non-empty string');
|
|
42
|
+
else if (seen.has(state.id))
|
|
43
|
+
bad('states[' + index + '].id', 'duplicate state id ' + state.id);
|
|
44
|
+
else
|
|
45
|
+
seen.add(state.id);
|
|
46
|
+
if (state.terminal !== undefined && typeof state.terminal !== 'boolean')
|
|
47
|
+
bad('states[' + index + '].terminal', 'must be a boolean');
|
|
48
|
+
});
|
|
49
|
+
if (typeof root.init === 'string' && root.init.length > 0 && !seen.has(root.init))
|
|
50
|
+
bad('init', 'must name a declared state');
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(root.transitions)) {
|
|
53
|
+
bad('transitions', 'must be an array');
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
const stateIds = new Set(Array.isArray(root.states) ? root.states.map((state) => state.id) : []);
|
|
57
|
+
root.transitions.forEach((entry, index) => {
|
|
58
|
+
const path = 'transitions[' + index + ']';
|
|
59
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
60
|
+
bad(path, 'must be an object');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const transition = entry;
|
|
64
|
+
if (typeof transition.from !== 'string' || transition.from.length === 0)
|
|
65
|
+
bad(path + '.from', 'must be a non-empty string');
|
|
66
|
+
else if (!stateIds.has(transition.from))
|
|
67
|
+
bad(path + '.from', 'unknown state ' + transition.from);
|
|
68
|
+
if (typeof transition.event !== 'string' || transition.event.length === 0)
|
|
69
|
+
bad(path + '.event', 'must be a non-empty string');
|
|
70
|
+
if (typeof transition.to !== 'string' || transition.to.length === 0)
|
|
71
|
+
bad(path + '.to', 'must be a non-empty string');
|
|
72
|
+
else if (!stateIds.has(transition.to))
|
|
73
|
+
bad(path + '.to', 'unknown state ' + transition.to);
|
|
74
|
+
if (transition.guard !== undefined)
|
|
75
|
+
validateGuard(transition.guard, path + '.guard', errors, bad);
|
|
76
|
+
if (transition.updates !== undefined) {
|
|
77
|
+
if (!Array.isArray(transition.updates))
|
|
78
|
+
bad(path + '.updates', 'must be an array');
|
|
79
|
+
else
|
|
80
|
+
transition.updates.forEach((update, updateIndex) => {
|
|
81
|
+
const updatePath = path + '.updates[' + updateIndex + ']';
|
|
82
|
+
if (typeof update !== 'object' || update === null || Array.isArray(update)) {
|
|
83
|
+
bad(updatePath, 'must be an object');
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const record = update;
|
|
87
|
+
if (typeof record.variable !== 'string' || record.variable.length === 0)
|
|
88
|
+
bad(updatePath + '.variable', 'must be a non-empty string');
|
|
89
|
+
if (record.op !== 'set' && record.op !== 'inc' && record.op !== 'dec')
|
|
90
|
+
bad(updatePath + '.op', "must be 'set', 'inc', or 'dec'");
|
|
91
|
+
if (record.value !== undefined && typeof record.value !== 'number')
|
|
92
|
+
bad(updatePath + '.value', 'must be a number');
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
const variableNames = new Set();
|
|
98
|
+
if (root.variables !== undefined) {
|
|
99
|
+
if (!Array.isArray(root.variables))
|
|
100
|
+
bad('variables', 'must be an array');
|
|
101
|
+
else
|
|
102
|
+
root.variables.forEach((entry, index) => {
|
|
103
|
+
const path = 'variables[' + index + ']';
|
|
104
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
105
|
+
bad(path, 'must be an object');
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const variable = entry;
|
|
109
|
+
if (typeof variable.name !== 'string' || variable.name.length === 0)
|
|
110
|
+
bad(path + '.name', 'must be a non-empty string');
|
|
111
|
+
else if (variableNames.has(variable.name))
|
|
112
|
+
bad(path + '.name', 'duplicate variable ' + variable.name);
|
|
113
|
+
else
|
|
114
|
+
variableNames.add(variable.name);
|
|
115
|
+
if (variable.kind !== 'integer' && variable.kind !== 'boolean')
|
|
116
|
+
bad(path + '.kind', "must be 'integer' or 'boolean'");
|
|
117
|
+
const expected = variable.kind === 'boolean' ? 'boolean' : 'number';
|
|
118
|
+
if (typeof variable.init !== expected)
|
|
119
|
+
bad(path + '.init', 'must be a ' + expected);
|
|
120
|
+
if (variable.min !== undefined && typeof variable.min !== 'number')
|
|
121
|
+
bad(path + '.min', 'must be a number');
|
|
122
|
+
if (variable.max !== undefined && typeof variable.max !== 'number')
|
|
123
|
+
bad(path + '.max', 'must be a number');
|
|
124
|
+
if (typeof variable.min === 'number' && typeof variable.max === 'number' && variable.min > variable.max)
|
|
125
|
+
bad(path + '.max', 'must be >= min');
|
|
126
|
+
if (variable.kind === 'integer' && typeof variable.init === 'number') {
|
|
127
|
+
if (typeof variable.min === 'number' && variable.init < variable.min)
|
|
128
|
+
bad(path + '.init', 'must be >= min');
|
|
129
|
+
if (typeof variable.max === 'number' && variable.init > variable.max)
|
|
130
|
+
bad(path + '.init', 'must be <= max');
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const validateVariableRef = (name, path) => {
|
|
135
|
+
if (typeof name !== 'string' || name.length === 0)
|
|
136
|
+
bad(path, 'must be a non-empty string');
|
|
137
|
+
else if (!variableNames.has(name))
|
|
138
|
+
bad(path, 'references unknown variable ' + name);
|
|
139
|
+
};
|
|
140
|
+
if (root.invariants !== undefined) {
|
|
141
|
+
if (!Array.isArray(root.invariants))
|
|
142
|
+
bad('invariants', 'must be an array');
|
|
143
|
+
else
|
|
144
|
+
root.invariants.forEach((entry, index) => {
|
|
145
|
+
const path = 'invariants[' + index + ']';
|
|
146
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
147
|
+
bad(path, 'must be an object');
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
const invariant = entry;
|
|
151
|
+
if (typeof invariant.id !== 'string' || invariant.id.length === 0)
|
|
152
|
+
bad(path + '.id', 'must be a non-empty string');
|
|
153
|
+
if (typeof invariant.description !== 'string')
|
|
154
|
+
bad(path + '.description', 'must be a string');
|
|
155
|
+
if (invariant.kind === 'never-states') {
|
|
156
|
+
if (!Array.isArray(invariant.states) || invariant.states.length === 0)
|
|
157
|
+
bad(path + '.states', 'must be a non-empty array');
|
|
158
|
+
else
|
|
159
|
+
invariant.states.forEach((state, stateIndex) => {
|
|
160
|
+
if (typeof state !== 'string' || state.length === 0)
|
|
161
|
+
bad(path + '.states[' + stateIndex + ']', 'must be a non-empty string');
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
else if (invariant.kind === 'var-in-range') {
|
|
165
|
+
validateVariableRef(invariant.variable, path + '.variable');
|
|
166
|
+
if (invariant.min !== undefined && typeof invariant.min !== 'number')
|
|
167
|
+
bad(path + '.min', 'must be a number');
|
|
168
|
+
if (invariant.max !== undefined && typeof invariant.max !== 'number')
|
|
169
|
+
bad(path + '.max', 'must be a number');
|
|
170
|
+
}
|
|
171
|
+
else if (invariant.kind === 'event-before-state') {
|
|
172
|
+
if (typeof invariant.event !== 'string' || invariant.event.length === 0)
|
|
173
|
+
bad(path + '.event', 'must be a non-empty string');
|
|
174
|
+
if (typeof invariant.state !== 'string' || invariant.state.length === 0)
|
|
175
|
+
bad(path + '.state', 'must be a non-empty string');
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
bad(path + '.kind', 'unknown invariant kind');
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
if (root.concurrentPairs !== undefined) {
|
|
183
|
+
if (!Array.isArray(root.concurrentPairs))
|
|
184
|
+
bad('concurrentPairs', 'must be an array');
|
|
185
|
+
else
|
|
186
|
+
root.concurrentPairs.forEach((entry, index) => {
|
|
187
|
+
const path = 'concurrentPairs[' + index + ']';
|
|
188
|
+
if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || typeof entry[1] !== 'string') {
|
|
189
|
+
bad(path, 'must be a [event, event] string pair');
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
if (root.boundaryChecks !== undefined) {
|
|
194
|
+
if (!Array.isArray(root.boundaryChecks))
|
|
195
|
+
bad('boundaryChecks', 'must be an array');
|
|
196
|
+
else
|
|
197
|
+
root.boundaryChecks.forEach((entry, index) => {
|
|
198
|
+
const path = 'boundaryChecks[' + index + ']';
|
|
199
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
200
|
+
bad(path, 'must be an object');
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const check = entry;
|
|
204
|
+
validateVariableRef(check.variable, path + '.variable');
|
|
205
|
+
if (!Array.isArray(check.values) || check.values.some((value) => typeof value !== 'number'))
|
|
206
|
+
bad(path + '.values', 'must be an array of numbers');
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (root.resourcePairs !== undefined) {
|
|
210
|
+
if (!Array.isArray(root.resourcePairs))
|
|
211
|
+
bad('resourcePairs', 'must be an array');
|
|
212
|
+
else
|
|
213
|
+
root.resourcePairs.forEach((entry, index) => {
|
|
214
|
+
const path = 'resourcePairs[' + index + ']';
|
|
215
|
+
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
|
216
|
+
bad(path, 'must be an object');
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const pair = entry;
|
|
220
|
+
if (typeof pair.resource !== 'string' || pair.resource.length === 0)
|
|
221
|
+
bad(path + '.resource', 'must be a non-empty string');
|
|
222
|
+
if (typeof pair.acquireEvent !== 'string' || pair.acquireEvent.length === 0)
|
|
223
|
+
bad(path + '.acquireEvent', 'must be a non-empty string');
|
|
224
|
+
if (typeof pair.releaseEvent !== 'string' || pair.releaseEvent.length === 0)
|
|
225
|
+
bad(path + '.releaseEvent', 'must be a non-empty string');
|
|
226
|
+
if (pair.failEvent !== undefined && typeof pair.failEvent !== 'string')
|
|
227
|
+
bad(path + '.failEvent', 'must be a string');
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
// Guard/update variable references were validated structurally; re-walk for references.
|
|
231
|
+
if (Array.isArray(root.transitions)) {
|
|
232
|
+
for (const entry of root.transitions) {
|
|
233
|
+
walkGuardReferences(entry.guard, variableNames, errors, bad);
|
|
234
|
+
for (const update of entry.updates ?? []) {
|
|
235
|
+
if (!variableNames.has(update.variable))
|
|
236
|
+
bad('transitions.updates', 'references unknown variable ' + update.variable);
|
|
237
|
+
if (update.op !== 'set' && update.value !== undefined && update.value === 0) {
|
|
238
|
+
// zero delta is harmless; no finding
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
if (errors.length > 0)
|
|
244
|
+
return { ok: false, errors };
|
|
245
|
+
return { ok: true, model: root };
|
|
246
|
+
}
|
|
247
|
+
function validateGuard(input, path, errors, bad) {
|
|
248
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input)) {
|
|
249
|
+
bad(path, 'must be an object');
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const guard = input;
|
|
253
|
+
if (guard.variable !== undefined) {
|
|
254
|
+
if (typeof guard.variable !== 'string' || guard.variable.length === 0)
|
|
255
|
+
bad(path + '.variable', 'must be a non-empty string');
|
|
256
|
+
if (guard.op !== '==' && guard.op !== '!=' && guard.op !== '<' && guard.op !== '<=' && guard.op !== '>' && guard.op !== '>=')
|
|
257
|
+
bad(path + '.op', 'must be a comparison operator');
|
|
258
|
+
if (typeof guard.value !== 'number' && typeof guard.value !== 'boolean')
|
|
259
|
+
bad(path + '.value', 'must be a number or boolean');
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (guard.all !== undefined) {
|
|
263
|
+
if (!Array.isArray(guard.all))
|
|
264
|
+
bad(path + '.all', 'must be an array');
|
|
265
|
+
else
|
|
266
|
+
guard.all.forEach((child, index) => validateGuard(child, path + '.all[' + index + ']', errors, bad));
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (guard.any !== undefined) {
|
|
270
|
+
if (!Array.isArray(guard.any))
|
|
271
|
+
bad(path + '.any', 'must be an array');
|
|
272
|
+
else
|
|
273
|
+
guard.any.forEach((child, index) => validateGuard(child, path + '.any[' + index + ']', errors, bad));
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (guard.not !== undefined) {
|
|
277
|
+
validateGuard(guard.not, path + '.not', errors, bad);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
bad(path, 'must be a leaf ({ variable, op, value }), { all }, { any }, or { not }');
|
|
281
|
+
}
|
|
282
|
+
function walkGuardReferences(guard, variableNames, errors, bad) {
|
|
283
|
+
if (guard === undefined)
|
|
284
|
+
return;
|
|
285
|
+
if ('variable' in guard) {
|
|
286
|
+
if (!variableNames.has(guard.variable))
|
|
287
|
+
bad('guard', 'references unknown variable ' + guard.variable);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
if ('all' in guard) {
|
|
291
|
+
for (const child of guard.all)
|
|
292
|
+
walkGuardReferences(child, variableNames, errors, bad);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
if ('any' in guard) {
|
|
296
|
+
for (const child of guard.any)
|
|
297
|
+
walkGuardReferences(child, variableNames, errors, bad);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if ('not' in guard)
|
|
301
|
+
walkGuardReferences(guard.not, variableNames, errors, bad);
|
|
302
|
+
}
|
|
303
|
+
// ---------------------------------------------------------------------------
|
|
304
|
+
// execution
|
|
305
|
+
// ---------------------------------------------------------------------------
|
|
306
|
+
function isLeafGuard(guard) {
|
|
307
|
+
return 'variable' in guard;
|
|
308
|
+
}
|
|
309
|
+
export function guardVariables(guard) {
|
|
310
|
+
if (guard === undefined)
|
|
311
|
+
return [];
|
|
312
|
+
if (isLeafGuard(guard))
|
|
313
|
+
return [guard.variable];
|
|
314
|
+
if ('all' in guard)
|
|
315
|
+
return guard.all.flatMap((child) => guardVariables(child));
|
|
316
|
+
if ('any' in guard)
|
|
317
|
+
return guard.any.flatMap((child) => guardVariables(child));
|
|
318
|
+
if ('not' in guard)
|
|
319
|
+
return guardVariables(guard.not);
|
|
320
|
+
return [];
|
|
321
|
+
}
|
|
322
|
+
function evalGuard(guard, vars) {
|
|
323
|
+
if (isLeafGuard(guard)) {
|
|
324
|
+
const actual = vars[guard.variable];
|
|
325
|
+
switch (guard.op) {
|
|
326
|
+
case '==': return actual === guard.value;
|
|
327
|
+
case '!=': return actual !== guard.value;
|
|
328
|
+
case '<': return actual < guard.value;
|
|
329
|
+
case '<=': return actual <= guard.value;
|
|
330
|
+
case '>': return actual > guard.value;
|
|
331
|
+
case '>=': return actual >= guard.value;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if ('all' in guard)
|
|
335
|
+
return guard.all.every((child) => evalGuard(child, vars));
|
|
336
|
+
if ('any' in guard)
|
|
337
|
+
return guard.any.some((child) => evalGuard(child, vars));
|
|
338
|
+
if ('not' in guard)
|
|
339
|
+
return !evalGuard(guard.not, vars);
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
function initialState(model) {
|
|
343
|
+
const vars = {};
|
|
344
|
+
for (const variable of model.variables ?? [])
|
|
345
|
+
vars[variable.name] = variable.init;
|
|
346
|
+
return { state: model.init, vars };
|
|
347
|
+
}
|
|
348
|
+
function runtimeKey(runtime) {
|
|
349
|
+
return runtime.state + '|' + stableStringify(runtime.vars);
|
|
350
|
+
}
|
|
351
|
+
function applyUpdates(model, transition, runtime) {
|
|
352
|
+
const vars = { ...runtime.vars };
|
|
353
|
+
for (const update of transition.updates ?? []) {
|
|
354
|
+
const current = vars[update.variable];
|
|
355
|
+
if (update.op === 'set')
|
|
356
|
+
vars[update.variable] = update.value ?? 0;
|
|
357
|
+
else if (update.op === 'inc')
|
|
358
|
+
vars[update.variable] = ((typeof current === 'number' ? current : 0) + (update.value ?? 1));
|
|
359
|
+
else
|
|
360
|
+
vars[update.variable] = ((typeof current === 'number' ? current : 0) - (update.value ?? 1));
|
|
361
|
+
}
|
|
362
|
+
return { state: transition.to, vars };
|
|
363
|
+
}
|
|
364
|
+
function groupTransitions(model) {
|
|
365
|
+
const groups = new Map();
|
|
366
|
+
for (const transition of model.transitions) {
|
|
367
|
+
const key = transition.from + '|' + transition.event;
|
|
368
|
+
const list = groups.get(key) ?? [];
|
|
369
|
+
list.push(transition);
|
|
370
|
+
groups.set(key, list);
|
|
371
|
+
}
|
|
372
|
+
return groups;
|
|
373
|
+
}
|
|
374
|
+
function applicableTransitions(group, runtime) {
|
|
375
|
+
const guarded = [];
|
|
376
|
+
const unguarded = [];
|
|
377
|
+
for (const transition of group) {
|
|
378
|
+
if (transition.guard === undefined)
|
|
379
|
+
unguarded.push(transition);
|
|
380
|
+
else
|
|
381
|
+
guarded.push(transition);
|
|
382
|
+
}
|
|
383
|
+
const matched = guarded.filter((transition) => evalGuard(transition.guard, runtime.vars));
|
|
384
|
+
if (matched.length > 0)
|
|
385
|
+
return matched;
|
|
386
|
+
return unguarded;
|
|
387
|
+
}
|
|
388
|
+
function stepRuntime(model, runtime, event) {
|
|
389
|
+
const group = groupTransitions(model).get(runtime.state + '|' + event);
|
|
390
|
+
if (group === undefined || group.length === 0)
|
|
391
|
+
return [];
|
|
392
|
+
const seen = new Set();
|
|
393
|
+
const outcomes = [];
|
|
394
|
+
for (const transition of applicableTransitions(group, runtime)) {
|
|
395
|
+
const next = applyUpdates(model, transition, runtime);
|
|
396
|
+
const key = runtimeKey(next);
|
|
397
|
+
if (!seen.has(key)) {
|
|
398
|
+
seen.add(key);
|
|
399
|
+
outcomes.push(next);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return outcomes;
|
|
403
|
+
}
|
|
404
|
+
function explore(model, options) {
|
|
405
|
+
const init = initialState(model);
|
|
406
|
+
const reachable = [];
|
|
407
|
+
const reachableKeys = new Set();
|
|
408
|
+
const queue = [init];
|
|
409
|
+
let truncated = false;
|
|
410
|
+
while (queue.length > 0) {
|
|
411
|
+
const runtime = queue.shift();
|
|
412
|
+
const key = runtimeKey(runtime);
|
|
413
|
+
if (reachableKeys.has(key))
|
|
414
|
+
continue;
|
|
415
|
+
reachableKeys.add(key);
|
|
416
|
+
reachable.push(runtime);
|
|
417
|
+
if (reachable.length > options.maxStates) {
|
|
418
|
+
truncated = true;
|
|
419
|
+
break;
|
|
420
|
+
}
|
|
421
|
+
for (const event of allEvents(model)) {
|
|
422
|
+
for (const next of stepRuntime(model, runtime, event)) {
|
|
423
|
+
if (!reachableKeys.has(runtimeKey(next)))
|
|
424
|
+
queue.push(next);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return { reachable, reachableKeys, truncated, initialState: init };
|
|
429
|
+
}
|
|
430
|
+
function allEvents(model) {
|
|
431
|
+
return [...new Set(model.transitions.map((transition) => transition.event))].sort();
|
|
432
|
+
}
|
|
433
|
+
function stateById(model, id) {
|
|
434
|
+
return model.states.find((state) => state.id === id);
|
|
435
|
+
}
|
|
436
|
+
function isTerminal(model, state) {
|
|
437
|
+
return stateById(model, state)?.terminal === true;
|
|
438
|
+
}
|
|
439
|
+
function uniqueTargets(transitions) {
|
|
440
|
+
return [...new Set(transitions.map((transition) => transition.to))];
|
|
441
|
+
}
|
|
442
|
+
function checkResult(id, name, findings, detail) {
|
|
443
|
+
const errors = findings.filter((finding) => finding.severity === 'error').length;
|
|
444
|
+
const warnings = findings.filter((finding) => finding.severity === 'warning').length;
|
|
445
|
+
return {
|
|
446
|
+
id,
|
|
447
|
+
name,
|
|
448
|
+
status: findings.length === 0 ? 'pass' : 'fail',
|
|
449
|
+
detail: detail + (errors > 0 ? ' (' + errors + ' errors' + (warnings > 0 ? ', ' + warnings + ' warnings' : '') + ')' : warnings > 0 ? ' (' + warnings + ' warnings)' : ''),
|
|
450
|
+
findings,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
// ---------------------------------------------------------------------------
|
|
454
|
+
// S1-S7
|
|
455
|
+
// ---------------------------------------------------------------------------
|
|
456
|
+
function S1_reachability(model, exploration) {
|
|
457
|
+
const reached = new Set(exploration.reachable.map((runtime) => runtime.state));
|
|
458
|
+
const unreachable = model.states.filter((state) => !reached.has(state.id)).map((state) => state.id);
|
|
459
|
+
const findings = unreachable.map((state) => ({
|
|
460
|
+
code: 'S1_UNREACHABLE_STATE',
|
|
461
|
+
severity: 'warning',
|
|
462
|
+
message: 'State ' + state + ' is not reachable from init.',
|
|
463
|
+
}));
|
|
464
|
+
return checkResult('S1', 'Reachability', findings, unreachable.length === 0 ? 'All states reachable' : 'Unreachable states: ' + unreachable.join(', '));
|
|
465
|
+
}
|
|
466
|
+
function S2_deadlock(model) {
|
|
467
|
+
const outgoing = new Set(model.transitions.map((transition) => transition.from));
|
|
468
|
+
const findings = [];
|
|
469
|
+
for (const state of model.states) {
|
|
470
|
+
if (state.terminal === true)
|
|
471
|
+
continue;
|
|
472
|
+
if (!outgoing.has(state.id)) {
|
|
473
|
+
findings.push({
|
|
474
|
+
code: 'S2_NO_TRANSITIONS',
|
|
475
|
+
severity: 'error',
|
|
476
|
+
message: 'Non-terminal state ' + state.id + ' has no outgoing transitions.',
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
return checkResult('S2', 'Deadlock', findings, findings.length === 0 ? 'No deadlocks' : 'Deadlocks: ' + findings.map((finding) => finding.message).join('; '));
|
|
481
|
+
}
|
|
482
|
+
function sccs(model) {
|
|
483
|
+
const states = model.states.map((state) => state.id);
|
|
484
|
+
const edges = new Map();
|
|
485
|
+
for (const state of states)
|
|
486
|
+
edges.set(state, []);
|
|
487
|
+
for (const transition of model.transitions) {
|
|
488
|
+
const list = edges.get(transition.from);
|
|
489
|
+
if (list !== undefined)
|
|
490
|
+
list.push(transition.to);
|
|
491
|
+
}
|
|
492
|
+
let index = 0;
|
|
493
|
+
const indices = new Map();
|
|
494
|
+
const low = new Map();
|
|
495
|
+
const onStack = new Set();
|
|
496
|
+
const stack = [];
|
|
497
|
+
const components = [];
|
|
498
|
+
const visit = (node) => {
|
|
499
|
+
indices.set(node, index);
|
|
500
|
+
low.set(node, index);
|
|
501
|
+
index += 1;
|
|
502
|
+
stack.push(node);
|
|
503
|
+
onStack.add(node);
|
|
504
|
+
for (const next of edges.get(node) ?? []) {
|
|
505
|
+
if (!indices.has(next)) {
|
|
506
|
+
visit(next);
|
|
507
|
+
low.set(node, Math.min(low.get(node), low.get(next)));
|
|
508
|
+
}
|
|
509
|
+
else if (onStack.has(next)) {
|
|
510
|
+
low.set(node, Math.min(low.get(node), indices.get(next)));
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (low.get(node) === indices.get(node)) {
|
|
514
|
+
const component = [];
|
|
515
|
+
while (stack.length > 0) {
|
|
516
|
+
const member = stack.pop();
|
|
517
|
+
onStack.delete(member);
|
|
518
|
+
component.push(member);
|
|
519
|
+
if (member === node)
|
|
520
|
+
break;
|
|
521
|
+
}
|
|
522
|
+
components.push(component);
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
for (const state of states) {
|
|
526
|
+
if (!indices.has(state))
|
|
527
|
+
visit(state);
|
|
528
|
+
}
|
|
529
|
+
return components;
|
|
530
|
+
}
|
|
531
|
+
function S3_liveness(model) {
|
|
532
|
+
const components = sccs(model);
|
|
533
|
+
const findings = [];
|
|
534
|
+
for (const component of components) {
|
|
535
|
+
const componentSet = new Set(component);
|
|
536
|
+
const internalEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && componentSet.has(transition.to));
|
|
537
|
+
const escapingEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && !componentSet.has(transition.to));
|
|
538
|
+
if (internalEdges.length === 0 || escapingEdges.length > 0)
|
|
539
|
+
continue;
|
|
540
|
+
if (component.some((state) => isTerminal(model, state)))
|
|
541
|
+
continue;
|
|
542
|
+
findings.push({
|
|
543
|
+
code: 'S3_CLOSED_SCC',
|
|
544
|
+
severity: 'error',
|
|
545
|
+
message: 'Closed SCC has no exit and contains no terminal state: ' + component.sort().join(', '),
|
|
546
|
+
evidence: { states: component.sort(), transitions: internalEdges.length },
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
return checkResult('S3', 'Liveness', findings, findings.length === 0 ? 'No harmful closed SCCs' : 'Closed SCCs: ' + findings.length);
|
|
550
|
+
}
|
|
551
|
+
function assignmentsFor(model, variables) {
|
|
552
|
+
const specs = (model.variables ?? []).filter((variable) => variables.includes(variable.name));
|
|
553
|
+
let combinations = [{}];
|
|
554
|
+
for (const spec of specs) {
|
|
555
|
+
let values;
|
|
556
|
+
if (spec.kind === 'boolean')
|
|
557
|
+
values = [false, true];
|
|
558
|
+
else {
|
|
559
|
+
const constants = collectGuardConstants(model).filter((value) => guardLeaves(model).some((leaf) => leaf.variable === spec.name && typeof leaf.value === 'number' && leaf.value === value));
|
|
560
|
+
if (spec.min !== undefined && spec.max !== undefined) {
|
|
561
|
+
values = [];
|
|
562
|
+
for (let value = spec.min; value <= spec.max && value <= spec.min + 200; value++)
|
|
563
|
+
values.push(value);
|
|
564
|
+
}
|
|
565
|
+
else {
|
|
566
|
+
const set = new Set([-1, 0, 1, ...constants]);
|
|
567
|
+
values = [...set].sort((a, b) => a - b);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const next = [];
|
|
571
|
+
for (const assignment of combinations) {
|
|
572
|
+
for (const value of values) {
|
|
573
|
+
next.push({ ...assignment, [spec.name]: value });
|
|
574
|
+
if (next.length > 10_000)
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
combinations = next;
|
|
579
|
+
}
|
|
580
|
+
return combinations;
|
|
581
|
+
}
|
|
582
|
+
function guardLeaves(model) {
|
|
583
|
+
const leaves = [];
|
|
584
|
+
const visit = (guard) => {
|
|
585
|
+
if ('variable' in guard)
|
|
586
|
+
leaves.push(guard);
|
|
587
|
+
else if ('all' in guard)
|
|
588
|
+
guard.all.forEach(visit);
|
|
589
|
+
else if ('any' in guard)
|
|
590
|
+
guard.any.forEach(visit);
|
|
591
|
+
else if ('not' in guard)
|
|
592
|
+
visit(guard.not);
|
|
593
|
+
};
|
|
594
|
+
for (const transition of model.transitions)
|
|
595
|
+
if (transition.guard !== undefined)
|
|
596
|
+
visit(transition.guard);
|
|
597
|
+
return leaves;
|
|
598
|
+
}
|
|
599
|
+
function collectGuardConstants(model) {
|
|
600
|
+
return guardLeaves(model).filter((leaf) => typeof leaf.value === 'number').map((leaf) => leaf.value);
|
|
601
|
+
}
|
|
602
|
+
function analyzeGuards(model) {
|
|
603
|
+
const determinism = [];
|
|
604
|
+
const completeness = [];
|
|
605
|
+
let truncated = false;
|
|
606
|
+
const groups = groupTransitions(model);
|
|
607
|
+
for (const [key, group] of groups) {
|
|
608
|
+
const [from, event] = key.split('|');
|
|
609
|
+
const unguarded = group.filter((transition) => transition.guard === undefined);
|
|
610
|
+
const guarded = group.filter((transition) => transition.guard !== undefined);
|
|
611
|
+
if (unguarded.length > 1) {
|
|
612
|
+
determinism.push({
|
|
613
|
+
code: 'S4_AMBIGUOUS_DEFAULT',
|
|
614
|
+
severity: 'error',
|
|
615
|
+
message: from + ' + ' + event + ' has multiple unconditional transitions: ' + uniqueTargets(unguarded).join(', '),
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
if (guarded.length === 0)
|
|
619
|
+
continue;
|
|
620
|
+
const variables = [...new Set(group.flatMap((transition) => guardVariables(transition.guard)))];
|
|
621
|
+
const assignments = assignmentsFor(model, variables);
|
|
622
|
+
if (assignments === null) {
|
|
623
|
+
completeness.push({ code: 'S6_UNBOUNDED_DOMAIN', severity: 'warning', message: from + ' + ' + event + ': guard domain too large to enumerate; exhaustive check skipped.' });
|
|
624
|
+
truncated = true;
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
const targets = uniqueTargets(group);
|
|
628
|
+
for (const assignment of assignments) {
|
|
629
|
+
const trueBranches = guarded.filter((transition) => evalGuard(transition.guard, assignment));
|
|
630
|
+
if (trueBranches.length > 1) {
|
|
631
|
+
determinism.push({
|
|
632
|
+
code: 'S4_NONDETERMINISTIC_GUARDS',
|
|
633
|
+
severity: 'error',
|
|
634
|
+
message: from + ' + ' + event + ' has ' + trueBranches.length + ' simultaneously true guards for assignment ' + stableStringify(assignment) + ': ' + uniqueTargets(trueBranches).join(', '),
|
|
635
|
+
evidence: { assignment },
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
if (trueBranches.length === 0 && unguarded.length === 0) {
|
|
639
|
+
completeness.push({
|
|
640
|
+
code: 'S6_INCOMPLETE_GUARD',
|
|
641
|
+
severity: 'error',
|
|
642
|
+
message: from + ' + ' + event + ' has no true guard and no default branch for assignment ' + stableStringify(assignment),
|
|
643
|
+
evidence: { assignment, branches: targets },
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
if (determinism.length + completeness.length > 200) {
|
|
647
|
+
truncated = true;
|
|
648
|
+
break;
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (truncated)
|
|
652
|
+
break;
|
|
653
|
+
}
|
|
654
|
+
return { determinism, completeness, truncated };
|
|
655
|
+
}
|
|
656
|
+
function S4_determinism(model) {
|
|
657
|
+
const analysis = analyzeGuards(model);
|
|
658
|
+
return checkResult('S4', 'Determinism', analysis.determinism, analysis.determinism.length === 0 ? 'Deterministic' : 'Nondeterminism findings: ' + analysis.determinism.length);
|
|
659
|
+
}
|
|
660
|
+
function S6_guardCompleteness(model) {
|
|
661
|
+
const analysis = analyzeGuards(model);
|
|
662
|
+
return checkResult('S6', 'Guard Completeness', analysis.completeness, analysis.completeness.length === 0 ? 'All guard branches defined' : 'Guard findings: ' + analysis.completeness.length);
|
|
663
|
+
}
|
|
664
|
+
function S5_eventCompleteness(model) {
|
|
665
|
+
const events = allEvents(model);
|
|
666
|
+
const findings = [];
|
|
667
|
+
for (const state of model.states) {
|
|
668
|
+
if (state.terminal === true)
|
|
669
|
+
continue;
|
|
670
|
+
const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
|
|
671
|
+
for (const event of events) {
|
|
672
|
+
if (!handled.has(event)) {
|
|
673
|
+
findings.push({
|
|
674
|
+
code: 'S5_UNHANDLED_EVENT',
|
|
675
|
+
severity: 'warning',
|
|
676
|
+
message: state.id + ' silently ignores event ' + event,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
return checkResult('S5', 'Event Completeness', findings, findings.length === 0 ? 'All states handle all relevant events' : findings.length + ' unhandled (state, event) pairs');
|
|
682
|
+
}
|
|
683
|
+
function invariantHolds(invariant, runtime) {
|
|
684
|
+
if (invariant.kind === 'never-states')
|
|
685
|
+
return !invariant.states.includes(runtime.state);
|
|
686
|
+
if (invariant.kind === 'var-in-range') {
|
|
687
|
+
const value = runtime.vars[invariant.variable];
|
|
688
|
+
if (typeof value !== 'number')
|
|
689
|
+
return false;
|
|
690
|
+
if (invariant.min !== undefined && value < invariant.min)
|
|
691
|
+
return false;
|
|
692
|
+
if (invariant.max !== undefined && value > invariant.max)
|
|
693
|
+
return false;
|
|
694
|
+
return true;
|
|
695
|
+
}
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
function shortestViolationForInvariant(model, options, invariant) {
|
|
699
|
+
if (invariant.kind === 'event-before-state') {
|
|
700
|
+
return shortestEventBeforeStateViolation(model, options, invariant);
|
|
701
|
+
}
|
|
702
|
+
const init = initialState(model);
|
|
703
|
+
if (!invariantHolds(invariant, init)) {
|
|
704
|
+
return { invariant, path: [], reason: 'Initial state violates the invariant.' };
|
|
705
|
+
}
|
|
706
|
+
const visited = new Set([runtimeKey(init)]);
|
|
707
|
+
const queue = [{ runtime: init, path: [] }];
|
|
708
|
+
let steps = 0;
|
|
709
|
+
while (queue.length > 0) {
|
|
710
|
+
const entry = queue.shift();
|
|
711
|
+
if (++steps > options.maxStates)
|
|
712
|
+
break;
|
|
713
|
+
for (const event of allEvents(model)) {
|
|
714
|
+
for (const next of stepRuntime(model, entry.runtime, event)) {
|
|
715
|
+
const key = runtimeKey(next);
|
|
716
|
+
if (visited.has(key))
|
|
717
|
+
continue;
|
|
718
|
+
const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
|
|
719
|
+
if (!invariantHolds(invariant, next)) {
|
|
720
|
+
return { invariant, path, reason: 'Invariant violated after ' + path.length + ' events.' };
|
|
721
|
+
}
|
|
722
|
+
visited.add(key);
|
|
723
|
+
queue.push({ runtime: next, path });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return undefined;
|
|
728
|
+
}
|
|
729
|
+
function shortestEventBeforeStateViolation(model, options, invariant) {
|
|
730
|
+
const init = initialState(model);
|
|
731
|
+
const seenInitially = false;
|
|
732
|
+
if (init.state === invariant.state && !seenInitially) {
|
|
733
|
+
return { invariant, path: [], reason: 'Target state ' + invariant.state + ' is initial and the required event ' + invariant.event + ' has not occurred.' };
|
|
734
|
+
}
|
|
735
|
+
const key = (runtime, seen) => runtimeKey(runtime) + '|' + (seen ? '1' : '0');
|
|
736
|
+
const visited = new Set([key(init, false)]);
|
|
737
|
+
const queue = [{ runtime: init, seen: false, path: [] }];
|
|
738
|
+
let steps = 0;
|
|
739
|
+
while (queue.length > 0) {
|
|
740
|
+
const entry = queue.shift();
|
|
741
|
+
if (++steps > options.maxStates)
|
|
742
|
+
break;
|
|
743
|
+
for (const event of allEvents(model)) {
|
|
744
|
+
for (const next of stepRuntime(model, entry.runtime, event)) {
|
|
745
|
+
const seen = entry.seen || event === invariant.event;
|
|
746
|
+
const nextKey = key(next, seen);
|
|
747
|
+
if (visited.has(nextKey))
|
|
748
|
+
continue;
|
|
749
|
+
const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
|
|
750
|
+
if (next.state === invariant.state && !seen) {
|
|
751
|
+
return { invariant, path, reason: 'Target state ' + invariant.state + ' is reachable without event ' + invariant.event + ' in ' + path.length + ' steps.' };
|
|
752
|
+
}
|
|
753
|
+
visited.add(nextKey);
|
|
754
|
+
queue.push({ runtime: next, seen, path });
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return undefined;
|
|
759
|
+
}
|
|
760
|
+
function runInvariants(model, options) {
|
|
761
|
+
const violations = [];
|
|
762
|
+
for (const invariant of model.invariants ?? []) {
|
|
763
|
+
const violation = shortestViolationForInvariant(model, options, invariant);
|
|
764
|
+
if (violation !== undefined)
|
|
765
|
+
violations.push(violation);
|
|
766
|
+
}
|
|
767
|
+
return violations;
|
|
768
|
+
}
|
|
769
|
+
function S7_invariants(model, options) {
|
|
770
|
+
const violations = runInvariants(model, options);
|
|
771
|
+
const findings = violations.map((violation) => ({
|
|
772
|
+
code: 'S7_INVARIANT_VIOLATION',
|
|
773
|
+
severity: 'error',
|
|
774
|
+
message: 'Invariant "' + violation.invariant.id + '" (' + violation.invariant.description + ') violated: ' + violation.reason,
|
|
775
|
+
path: violation.path,
|
|
776
|
+
evidence: { invariant: violation.invariant },
|
|
777
|
+
}));
|
|
778
|
+
return checkResult('S7', 'Invariant Validity', findings, violations.length === 0 ? 'All invariants hold' : 'Invariant violations: ' + violations.length);
|
|
779
|
+
}
|
|
780
|
+
// ---------------------------------------------------------------------------
|
|
781
|
+
// A1-A7
|
|
782
|
+
// ---------------------------------------------------------------------------
|
|
783
|
+
function A1_unexpectedEvents(model) {
|
|
784
|
+
const events = allEvents(model);
|
|
785
|
+
const findings = [];
|
|
786
|
+
for (const state of model.states) {
|
|
787
|
+
if (state.terminal === true)
|
|
788
|
+
continue;
|
|
789
|
+
const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
|
|
790
|
+
for (const event of events) {
|
|
791
|
+
if (!handled.has(event)) {
|
|
792
|
+
findings.push({
|
|
793
|
+
code: 'A1_UNHANDLED_EVENT',
|
|
794
|
+
severity: 'warning',
|
|
795
|
+
message: 'Event ' + event + ' in state ' + state.id + ' has no defined transition (silent ignore).',
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return checkResult('A1', 'Unexpected Event Injection', findings, findings.length === 0 ? 'All event/state combinations defined' : findings.length + ' unhandled combinations');
|
|
801
|
+
}
|
|
802
|
+
function firstOutcome(runtime, outcomes) {
|
|
803
|
+
return outcomes[0];
|
|
804
|
+
}
|
|
805
|
+
function A2_raceInterleaving(model, exploration) {
|
|
806
|
+
const findings = [];
|
|
807
|
+
for (const [e1, e2] of model.concurrentPairs ?? []) {
|
|
808
|
+
for (const runtime of exploration.reachable) {
|
|
809
|
+
const first = firstOutcome(runtime, stepRuntime(model, runtime, e1));
|
|
810
|
+
const second = firstOutcome(runtime, stepRuntime(model, runtime, e2));
|
|
811
|
+
if (first === undefined && second === undefined)
|
|
812
|
+
continue;
|
|
813
|
+
const final12 = first === undefined ? runtime : firstOutcome(first, stepRuntime(model, first, e2)) ?? first;
|
|
814
|
+
const final21 = second === undefined ? runtime : firstOutcome(second, stepRuntime(model, second, e1)) ?? second;
|
|
815
|
+
if (runtimeKey(final12) !== runtimeKey(final21)) {
|
|
816
|
+
findings.push({
|
|
817
|
+
code: 'A2_ORDER_DEPENDENT',
|
|
818
|
+
severity: 'warning',
|
|
819
|
+
message: 'Events ' + e1 + ' and ' + e2 + ' produce order-dependent outcomes from state ' + runtime.state,
|
|
820
|
+
evidence: { e1ThenE2: final12, e2ThenE1: final21 },
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
return checkResult('A2', 'Race Interleaving', findings, findings.length === 0 ? 'No race conditions detected' : 'Order-dependent outcomes: ' + findings.length);
|
|
826
|
+
}
|
|
827
|
+
function stepSequence(model, init, events) {
|
|
828
|
+
let runtime = init;
|
|
829
|
+
for (const event of events) {
|
|
830
|
+
const next = firstOutcome(runtime, stepRuntime(model, runtime, event));
|
|
831
|
+
if (next === undefined)
|
|
832
|
+
continue;
|
|
833
|
+
runtime = next;
|
|
834
|
+
}
|
|
835
|
+
return runtime;
|
|
836
|
+
}
|
|
837
|
+
function permutations(items) {
|
|
838
|
+
if (items.length === 0)
|
|
839
|
+
return [[]];
|
|
840
|
+
const result = [];
|
|
841
|
+
for (let index = 0; index < items.length; index++) {
|
|
842
|
+
const rest = items.slice(0, index).concat(items.slice(index + 1));
|
|
843
|
+
for (const suffix of permutations(rest))
|
|
844
|
+
result.push([items[index], ...suffix]);
|
|
845
|
+
}
|
|
846
|
+
return result;
|
|
847
|
+
}
|
|
848
|
+
function A3_orderPermutation(model, options) {
|
|
849
|
+
const events = allEvents(model).slice(0, options.maxPermutationEvents);
|
|
850
|
+
if (events.length < 2)
|
|
851
|
+
return checkResult('A3', 'Order Permutation', [], 'Fewer than 2 events — skipped');
|
|
852
|
+
const init = initialState(model);
|
|
853
|
+
const outcomes = new Map();
|
|
854
|
+
for (const permutation of permutations(events)) {
|
|
855
|
+
const final = stepSequence(model, init, permutation);
|
|
856
|
+
const key = runtimeKey(final);
|
|
857
|
+
const list = outcomes.get(key) ?? [];
|
|
858
|
+
if (list.length < 3)
|
|
859
|
+
list.push(permutation.join(','));
|
|
860
|
+
outcomes.set(key, list);
|
|
861
|
+
}
|
|
862
|
+
if (outcomes.size > 1) {
|
|
863
|
+
const examples = [...outcomes.entries()].map(([key, sequences]) => ({ final: key.split('|')[0], example: sequences[0] }));
|
|
864
|
+
return checkResult('A3', 'Order Permutation', [{
|
|
865
|
+
code: 'A3_ORDER_DEPENDENT',
|
|
866
|
+
severity: 'warning',
|
|
867
|
+
message: 'Same event set produces ' + outcomes.size + ' different outcomes depending on order.',
|
|
868
|
+
evidence: { examples },
|
|
869
|
+
}], 'Order-dependent outcomes: ' + outcomes.size);
|
|
870
|
+
}
|
|
871
|
+
return checkResult('A3', 'Order Permutation', [], 'Order-independent (sampled first ' + events.length + ' events)');
|
|
872
|
+
}
|
|
873
|
+
function A4_pairSymmetry(model) {
|
|
874
|
+
const findings = [];
|
|
875
|
+
const transitionEvents = new Set(model.transitions.map((transition) => transition.event));
|
|
876
|
+
for (const pair of model.resourcePairs ?? []) {
|
|
877
|
+
const acquireTransitions = model.transitions.filter((transition) => transition.event === pair.acquireEvent);
|
|
878
|
+
const releaseExists = transitionEvents.has(pair.releaseEvent);
|
|
879
|
+
if (acquireTransitions.length === 0 && !releaseExists)
|
|
880
|
+
continue;
|
|
881
|
+
if (acquireTransitions.length > 0 && !releaseExists) {
|
|
882
|
+
findings.push({
|
|
883
|
+
code: 'A4_NO_RELEASE_EVENT',
|
|
884
|
+
severity: 'error',
|
|
885
|
+
message: 'Resource "' + pair.resource + '": acquire event ' + pair.acquireEvent + ' exists but release event ' + pair.releaseEvent + ' is never defined.',
|
|
886
|
+
});
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
for (const acquire of acquireTransitions) {
|
|
890
|
+
// Is any release event reachable in the state graph from the acquired state?
|
|
891
|
+
const reachable = stateGraphReachable(model, acquire.to);
|
|
892
|
+
const releaseReachable = [...reachable].some((state) => model.transitions.some((transition) => transition.from === state && transition.event === pair.releaseEvent));
|
|
893
|
+
if (!releaseReachable) {
|
|
894
|
+
findings.push({
|
|
895
|
+
code: 'A4_NO_RELEASE_REACHABLE',
|
|
896
|
+
severity: 'error',
|
|
897
|
+
message: 'Resource "' + pair.resource + '": after ' + pair.acquireEvent + ' into ' + acquire.to + ', no ' + pair.releaseEvent + ' transition is reachable.',
|
|
898
|
+
evidence: { acquireTransition: acquire },
|
|
899
|
+
});
|
|
900
|
+
continue;
|
|
901
|
+
}
|
|
902
|
+
// Path-sensitive probe: track the held flag along state-graph paths.
|
|
903
|
+
const edges = stateGraphEdges(model);
|
|
904
|
+
const visited = new Set();
|
|
905
|
+
const queue = [{ state: acquire.to, held: true, path: [] }];
|
|
906
|
+
let steps = 0;
|
|
907
|
+
while (queue.length > 0) {
|
|
908
|
+
const entry = queue.shift();
|
|
909
|
+
if (++steps > 1000)
|
|
910
|
+
break;
|
|
911
|
+
const key = entry.state + '|' + (entry.held ? '1' : '0');
|
|
912
|
+
if (visited.has(key))
|
|
913
|
+
continue;
|
|
914
|
+
visited.add(key);
|
|
915
|
+
if (entry.held && isTerminal(model, entry.state)) {
|
|
916
|
+
findings.push({
|
|
917
|
+
code: 'A4_TERMINAL_WITH_RESOURCE',
|
|
918
|
+
severity: 'error',
|
|
919
|
+
message: 'Resource "' + pair.resource + '" is still held when entering terminal state ' + entry.state + '.',
|
|
920
|
+
path: entry.path,
|
|
921
|
+
});
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
for (const transition of edges.get(entry.state) ?? []) {
|
|
925
|
+
let held = entry.held;
|
|
926
|
+
if (transition.event === pair.releaseEvent)
|
|
927
|
+
held = false;
|
|
928
|
+
else if (transition.event === pair.acquireEvent) {
|
|
929
|
+
if (held) {
|
|
930
|
+
findings.push({
|
|
931
|
+
code: 'A4_REACQUIRE_WITHOUT_RELEASE',
|
|
932
|
+
severity: 'warning',
|
|
933
|
+
message: 'Resource "' + pair.resource + '" is acquired again in state ' + entry.state + ' before ' + pair.releaseEvent + '.',
|
|
934
|
+
path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }],
|
|
935
|
+
});
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
held = true;
|
|
939
|
+
}
|
|
940
|
+
queue.push({ state: transition.to, held, path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }] });
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return checkResult('A4', 'Pair Symmetry', findings, findings.length === 0 ? 'All pairs balanced' : 'Asymmetric pairs: ' + findings.length);
|
|
946
|
+
}
|
|
947
|
+
function stateGraphEdges(model) {
|
|
948
|
+
const edges = new Map();
|
|
949
|
+
for (const state of model.states)
|
|
950
|
+
edges.set(state.id, []);
|
|
951
|
+
for (const transition of model.transitions)
|
|
952
|
+
edges.get(transition.from)?.push(transition);
|
|
953
|
+
return edges;
|
|
954
|
+
}
|
|
955
|
+
function stateGraphReachable(model, start) {
|
|
956
|
+
const edges = new Map();
|
|
957
|
+
for (const state of model.states)
|
|
958
|
+
edges.set(state.id, []);
|
|
959
|
+
for (const transition of model.transitions)
|
|
960
|
+
edges.get(transition.from)?.push(transition.to);
|
|
961
|
+
const visited = new Set();
|
|
962
|
+
const queue = [start];
|
|
963
|
+
while (queue.length > 0) {
|
|
964
|
+
const current = queue.shift();
|
|
965
|
+
if (visited.has(current))
|
|
966
|
+
continue;
|
|
967
|
+
visited.add(current);
|
|
968
|
+
for (const next of edges.get(current) ?? [])
|
|
969
|
+
queue.push(next);
|
|
970
|
+
}
|
|
971
|
+
return visited;
|
|
972
|
+
}
|
|
973
|
+
function A5_boundaryBlast(model) {
|
|
974
|
+
const findings = [];
|
|
975
|
+
for (const check of model.boundaryChecks ?? []) {
|
|
976
|
+
const variable = (model.variables ?? []).find((entry) => entry.name === check.variable);
|
|
977
|
+
if (variable === undefined)
|
|
978
|
+
continue;
|
|
979
|
+
for (const value of check.values) {
|
|
980
|
+
if (variable.min !== undefined && value < variable.min) {
|
|
981
|
+
findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is below min ' + variable.min });
|
|
982
|
+
}
|
|
983
|
+
if (variable.max !== undefined && value > variable.max) {
|
|
984
|
+
findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is above max ' + variable.max });
|
|
985
|
+
}
|
|
986
|
+
const assignment = { ...(model.variables ?? []).reduce((result, entry) => { result[entry.name] = entry.init; return result; }, {}), [check.variable]: value };
|
|
987
|
+
for (const [key, group] of groupTransitions(model)) {
|
|
988
|
+
const [from, event] = key.split('|');
|
|
989
|
+
if (!group.some((transition) => guardVariables(transition.guard).includes(check.variable)))
|
|
990
|
+
continue;
|
|
991
|
+
const guarded = group.filter((transition) => transition.guard !== undefined);
|
|
992
|
+
const unguarded = group.filter((transition) => transition.guard === undefined);
|
|
993
|
+
const matched = guarded.filter((transition) => evalGuard(transition.guard, assignment));
|
|
994
|
+
if (matched.length === 0 && unguarded.length === 0) {
|
|
995
|
+
findings.push({
|
|
996
|
+
code: 'A5_GUARD_HOLE',
|
|
997
|
+
severity: 'warning',
|
|
998
|
+
message: from + ' + ' + event + ' has no branch for ' + check.variable + '=' + value,
|
|
999
|
+
evidence: { assignment },
|
|
1000
|
+
});
|
|
1001
|
+
}
|
|
1002
|
+
if (matched.length > 1) {
|
|
1003
|
+
findings.push({
|
|
1004
|
+
code: 'A5_GUARD_OVERLAP',
|
|
1005
|
+
severity: 'warning',
|
|
1006
|
+
message: from + ' + ' + event + ' has ' + matched.length + ' true branches for ' + check.variable + '=' + value,
|
|
1007
|
+
evidence: { assignment },
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return checkResult('A5', 'Boundary Blast', findings, findings.length === 0 ? 'Boundary checks passed' : 'Boundary findings: ' + findings.length);
|
|
1014
|
+
}
|
|
1015
|
+
function A6_resourceInjection(model) {
|
|
1016
|
+
const findings = [];
|
|
1017
|
+
for (const pair of model.resourcePairs ?? []) {
|
|
1018
|
+
if (pair.failEvent === undefined)
|
|
1019
|
+
continue;
|
|
1020
|
+
const acquireStates = new Set(model.transitions.filter((transition) => transition.event === pair.acquireEvent).map((transition) => transition.from));
|
|
1021
|
+
for (const state of acquireStates) {
|
|
1022
|
+
const handled = model.transitions.some((transition) => transition.from === state && transition.event === pair.failEvent);
|
|
1023
|
+
if (!handled) {
|
|
1024
|
+
findings.push({
|
|
1025
|
+
code: 'A6_NO_FAILURE_HANDLER',
|
|
1026
|
+
severity: 'warning',
|
|
1027
|
+
message: 'State ' + state + ' can ' + pair.acquireEvent + ' for "' + pair.resource + '" but has no ' + pair.failEvent + ' transition.',
|
|
1028
|
+
});
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return checkResult('A6', 'Resource Injection', findings, findings.length === 0 ? 'No resource vulnerabilities detected' : 'Resource failure paths missing: ' + findings.length);
|
|
1033
|
+
}
|
|
1034
|
+
function A7_shortestViolations(model, options) {
|
|
1035
|
+
const violations = runInvariants(model, options);
|
|
1036
|
+
const findings = violations.map((violation) => ({
|
|
1037
|
+
code: 'A7_SHORTEST_COUNTEREXAMPLE',
|
|
1038
|
+
severity: 'warning',
|
|
1039
|
+
message: 'Invariant "' + violation.invariant.id + '" shortest violating path length: ' + violation.path.length + (violation.path.length === 0 ? ' (initial state)' : ''),
|
|
1040
|
+
path: violation.path,
|
|
1041
|
+
evidence: { invariant: violation.invariant.id },
|
|
1042
|
+
}));
|
|
1043
|
+
return checkResult('A7', 'Minimal Counter-Example', findings, violations.length === 0 ? 'All invariants hold for all reachable paths' : 'Violated invariants: ' + findings.length);
|
|
1044
|
+
}
|
|
1045
|
+
// ---------------------------------------------------------------------------
|
|
1046
|
+
// main entry
|
|
1047
|
+
// ---------------------------------------------------------------------------
|
|
1048
|
+
export function runVerification(input, options = {}) {
|
|
1049
|
+
const normalized = {
|
|
1050
|
+
maxStates: options.maxStates ?? DEFAULT_MAX_STATES,
|
|
1051
|
+
maxPermutationEvents: options.maxPermutationEvents ?? DEFAULT_MAX_PERMUTATION_EVENTS,
|
|
1052
|
+
};
|
|
1053
|
+
const validation = validateModel(input);
|
|
1054
|
+
if (!validation.ok) {
|
|
1055
|
+
return {
|
|
1056
|
+
ok: false,
|
|
1057
|
+
schemaVersion: 1,
|
|
1058
|
+
modelHash: '',
|
|
1059
|
+
summary: { states: 0, transitions: 0, errors: validation.errors.length, warnings: 0, checksRun: 0 },
|
|
1060
|
+
checks: [{
|
|
1061
|
+
id: 'MODEL',
|
|
1062
|
+
name: 'Model Validation',
|
|
1063
|
+
status: 'fail',
|
|
1064
|
+
detail: 'Model schema validation failed: ' + validation.errors.length + ' errors',
|
|
1065
|
+
findings: validation.errors.map((message) => ({ code: 'MODEL_INVALID', severity: 'error', message })),
|
|
1066
|
+
}],
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
const model = validation.model;
|
|
1070
|
+
const exploration = explore(model, normalized);
|
|
1071
|
+
const checks = [
|
|
1072
|
+
S1_reachability(model, exploration),
|
|
1073
|
+
S2_deadlock(model),
|
|
1074
|
+
S3_liveness(model),
|
|
1075
|
+
S4_determinism(model),
|
|
1076
|
+
S5_eventCompleteness(model),
|
|
1077
|
+
S6_guardCompleteness(model),
|
|
1078
|
+
S7_invariants(model, normalized),
|
|
1079
|
+
A1_unexpectedEvents(model),
|
|
1080
|
+
A2_raceInterleaving(model, exploration),
|
|
1081
|
+
A3_orderPermutation(model, normalized),
|
|
1082
|
+
A4_pairSymmetry(model),
|
|
1083
|
+
A5_boundaryBlast(model),
|
|
1084
|
+
A6_resourceInjection(model),
|
|
1085
|
+
A7_shortestViolations(model, normalized),
|
|
1086
|
+
];
|
|
1087
|
+
const errors = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'error').length, 0);
|
|
1088
|
+
const warnings = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'warning').length, 0);
|
|
1089
|
+
return {
|
|
1090
|
+
ok: true,
|
|
1091
|
+
schemaVersion: 1,
|
|
1092
|
+
modelHash: modelHash(model),
|
|
1093
|
+
summary: {
|
|
1094
|
+
states: model.states.length,
|
|
1095
|
+
transitions: model.transitions.length,
|
|
1096
|
+
errors,
|
|
1097
|
+
warnings,
|
|
1098
|
+
checksRun: checks.length,
|
|
1099
|
+
truncated: exploration.truncated,
|
|
1100
|
+
},
|
|
1101
|
+
checks,
|
|
1102
|
+
};
|
|
1103
|
+
}
|