tla-ts 0.0.1 → 0.0.3-dev.19c763f

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.
Files changed (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1086 -244
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +547 -255
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +710 -0
  36. package/src/liveness.ts +37 -599
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +223 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +276 -53
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +43 -37
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +411 -0
  72. package/src/tlc-summary.ts +109 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1245 -176
package/src/check.ts CHANGED
@@ -1,41 +1,98 @@
1
- import type { Assumption, Expression, SourceLocation } from "./ast";
2
- import { parseConfig, type ModelConfig } from "./config";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
9
+ import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { TlaConfigError, TlaEvaluationError, TlaUnsupportedError } from "./errors";
6
12
  import {
13
+ getErrorExitCode,
14
+ TlaConfigError,
15
+ TlaEvaluationError,
16
+ TlaModuleError,
17
+ UNEXPECTED_EXCEPTION,
18
+ } from "./errors";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
20
+ import {
21
+ describeRange,
7
22
  evaluate,
8
23
  expectBoolean,
24
+ formatRange,
9
25
  getDefinition,
26
+ isConstantLevel,
27
+ isImpure,
10
28
  type Context,
11
29
  type Environment,
12
30
  type Scope,
13
31
  } from "./evaluate";
14
32
  import {
15
- ACTION_LEVEL,
16
33
  createLivenessChecker,
17
- expandTemporal,
18
- getLevel,
19
- TEMPORAL_LEVEL,
20
- toUnscopedExpression,
34
+ type Lasso,
35
+ type LivenessChecker,
21
36
  type LiveSuccessor,
22
- type ScopedExpression,
23
- type TemporalProperty,
24
- } from "./liveness";
25
- import { parseModule } from "./parser";
26
- import { getInitialStates, getSuccessors } from "./successors";
37
+ } from "./live-check";
38
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
39
+ import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
40
+ import { prettyPrint } from "./pretty-print";
41
+ import {
42
+ forEachInitialState,
43
+ forEachSuccessor,
44
+ getInitialStates,
45
+ getSuccessors,
46
+ type Successor,
47
+ } from "./successors";
48
+ import {
49
+ getActionLabel,
50
+ getActionSignature,
51
+ getNextActions,
52
+ getSpecificationValue,
53
+ type SpecAction,
54
+ } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
27
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
+ import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
28
64
  import { createCanonicalizer } from "./canonical";
29
65
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
30
- import { combineHash, formatValue, getValueHash, isSameValue, type Value } from "./values";
66
+ import { createCounterExample } from "./tlc-ext";
67
+ import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
+ import {
69
+ combineHash,
70
+ formatState,
71
+ formatValue,
72
+ getValueHash,
73
+ isFunctionValue,
74
+ isSameValue,
75
+ isUpdatedElementOf,
76
+ setStringOrder,
77
+ toFiniteFunction,
78
+ type Value,
79
+ } from "./values";
31
80
 
32
81
  export interface CheckOptions {
33
82
  source: string;
34
83
  config: string | ModelConfig;
35
84
  loadModule?: (name: string) => string | undefined;
85
+ loadClass?: (name: string) => Uint8Array | undefined;
36
86
  onPrint?: (text: string) => void;
87
+ onPause?: () => void;
37
88
  readFile?: (path: string) => string | undefined;
38
89
  writeFile?: (path: string, content: string) => void;
90
+ seed?: bigint;
91
+ workers?: number;
92
+ // TLC's -lncheck: "final" checks liveness only on the complete state graph.
93
+ livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
39
96
  }
40
97
 
41
98
  export type CheckStatus =
@@ -45,52 +102,91 @@ export type CheckStatus =
45
102
  | "property-violation"
46
103
  | "liveness-violation"
47
104
  | "postcondition-violation"
48
- | "deadlock";
105
+ | "deadlock"
106
+ | "error";
49
107
 
50
108
  export interface TraceStep {
51
109
  action: string | undefined;
110
+ // TLC's name, parameters and location for the action that took this step.
111
+ label: string | undefined;
52
112
  state: Record<string, Value>;
53
113
  }
54
114
 
55
115
  export interface Violation {
56
116
  name: string;
117
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
118
+ properties?: string[];
57
119
  trace: TraceStep[];
58
120
  loopStart: number | undefined;
121
+ loopLabel?: string;
59
122
  message?: string;
123
+ counts?: string;
124
+ unwitnessed?: Postcondition;
125
+ }
126
+
127
+ interface Postcondition {
128
+ name: string;
129
+ message: string;
130
+ counts?: string;
131
+ }
132
+
133
+ // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
134
+ export interface EvaluationFailure {
135
+ message: string;
136
+ trace: TraceStep[];
137
+ initialState: Record<string, Value> | undefined;
138
+ exitCode: number;
60
139
  }
61
140
 
62
141
  export interface CheckResult {
63
142
  status: CheckStatus;
64
143
  violation: Violation | undefined;
144
+ failure: EvaluationFailure | undefined;
65
145
  generatedStates: number;
66
146
  distinctStates: number;
147
+ queuedStates: number;
67
148
  depth: number;
149
+ // How many states that TLC counts as expanded found each number of new states, when TLC prints
150
+ // the outdegree of the state graph.
151
+ outDegrees: number[] | undefined;
152
+ // The smallest distance between the fingerprints of two distinct states, when TLC estimates a
153
+ // collision from the actual fingerprints.
154
+ fingerprintDistance: bigint | undefined;
68
155
  }
69
156
 
70
- export interface NamedExpression {
157
+ interface NamedExpression {
71
158
  name: string;
72
159
  expression: Expression;
73
160
  scope: Scope | undefined;
74
161
  }
75
162
 
76
- export interface StateCheck extends NamedExpression {
163
+ interface StateCheck extends NamedExpression {
77
164
  variables: number[] | undefined;
165
+ membership: Membership | undefined;
78
166
  }
79
167
 
80
- export interface ActionProperty {
168
+ // A conjunct `x \in S` whose S reads no variables.
169
+ interface Membership {
170
+ variable: number;
171
+ set: Expression;
172
+ }
173
+
174
+ interface ActionProperty {
81
175
  name: string;
176
+ box: Expression;
82
177
  action: Expression;
83
178
  subscript: Expression;
84
179
  scope: Scope | undefined;
85
180
  }
86
181
 
87
- export interface Specification {
88
- init: Expression;
89
- next: Expression;
182
+ interface Specification {
183
+ init: Expression | undefined;
184
+ next: Expression | undefined;
185
+ scope: Scope | undefined;
90
186
  temporals: ScopedExpression[];
91
187
  }
92
188
 
93
- export interface Properties {
189
+ interface Properties {
94
190
  initialPredicates: NamedExpression[];
95
191
  invariants: NamedExpression[];
96
192
  actionProperties: ActionProperty[];
@@ -99,18 +195,106 @@ export interface Properties {
99
195
 
100
196
  const START: SourceLocation = { line: 0, column: 0 };
101
197
 
198
+ const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
199
+ const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
200
+
102
201
  const createIdentifier = (name: string): Expression => ({
103
202
  kind: "Identifier",
104
203
  name,
105
204
  location: START,
106
205
  });
107
206
 
108
- const getDefinitionBody = (name: string, environment: Environment) => {
207
+ // TLC leaves the kind out when it rejects arguments to the specification or a property.
208
+ const UNNAMED_ARGUMENT_KINDS = new Set(["name", "property"]);
209
+
210
+ // TLC checks liveness on the graph so far 3 seconds into the search and then every minute, once
211
+ // the graph has grown by a tenth and liveness checking has taken at most a fifth of the time.
212
+ const PERIODIC_START = 3000;
213
+ const PROGRESS_INTERVAL = 60_000;
214
+ const LIVENESS_GROWTH = 0.1;
215
+ const LIVENESS_RATIO = 0.2;
216
+
217
+ const getConfigOperator = (kind: string, name: string, environment: Environment) => {
109
218
  const definition = getDefinition(name, environment);
110
- if (definition?.kind !== "Operator" || definition.params.length > 0) {
111
- throw new TlaConfigError(`${name} is not defined as an operator without arguments`);
219
+ if (!definition) {
220
+ throw new TlaConfigError(
221
+ `The ${kind} ${name} specified in the configuration file\nis not defined in the specification.`,
222
+ );
223
+ }
224
+ if (definition.kind === "Operator" && definition.params.length > 0) {
225
+ throw new TlaConfigError(
226
+ UNNAMED_ARGUMENT_KINDS.has(kind)
227
+ ? `TLC requires ${name} not to take any argument.`
228
+ : `TLC requires ${kind} not to take any argument, but one was given: ${name}`,
229
+ );
230
+ }
231
+ return definition;
232
+ };
233
+
234
+ const getConfigDefinition = (kind: string, name: string, environment: Environment) => {
235
+ const definition = getConfigOperator(kind, name, environment);
236
+ if (isConstantLevel(definition, environment)) {
237
+ throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
112
238
  }
113
- return definition.body;
239
+ return definition;
240
+ };
241
+
242
+ // TLC evaluates every constant definition before it reads the configuration. It keeps a literal
243
+ // number or string, and a definition that fails to evaluate, as an operator.
244
+ const getConstantValue = (name: string, definition: Definition, environment: Environment) => {
245
+ if (!isConstantLevel(definition, environment)) return undefined;
246
+ if (definition.body.kind === "Number" || definition.body.kind === "String") return undefined;
247
+ try {
248
+ return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
+ } catch (error) {
250
+ if (error instanceof TlaEvaluationError) return undefined;
251
+ throw error;
252
+ }
253
+ };
254
+
255
+ const getConfigPredicate = (kind: string, name: string, environment: Environment) => {
256
+ const definition = getConfigOperator(kind, name, environment);
257
+ const value = getConstantValue(name, definition, environment);
258
+ if (value !== undefined && value !== true) {
259
+ throw new TlaConfigError(`The ${kind} of ${name} is equal to ${formatValue(value)}`);
260
+ }
261
+ return value === undefined ? definition : undefined;
262
+ };
263
+
264
+ const getInvariants = (names: string[], environment: Environment) => {
265
+ const analyzer = createLevelAnalyzer({
266
+ constants: new Set(environment.constants.keys()),
267
+ variables: new Set(environment.variables),
268
+ getDefinition: (name) => getDefinition(name, environment),
269
+ });
270
+ return names.flatMap((name) => {
271
+ const definition = getConfigPredicate("invariant", name, environment);
272
+ if (!definition) return [];
273
+ const levels = analyzer.analyzeDefinition(definition, new Map());
274
+ if (levels.level >= ACTION_LEVEL) {
275
+ const note =
276
+ levels.params.size === 0
277
+ ? ""
278
+ : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
279
+ throw new TlaConfigError(
280
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
281
+ );
282
+ }
283
+ return [{ name, expression: createIdentifier(name), scope: undefined }];
284
+ });
285
+ };
286
+
287
+ const toAliasRecord = (value: Value, fieldOrder: string[]) => {
288
+ if (!isFunctionValue(value)) return undefined;
289
+ const record = toFiniteFunction(value);
290
+ if (!record.domain.every((key) => typeof key === "string")) return undefined;
291
+ const entries = record.domain.map((key, index): [string, Value] => [
292
+ String(key),
293
+ record.range[index],
294
+ ]);
295
+ return Object.fromEntries(
296
+ entries.sort((left, right) => fieldOrder.indexOf(left[0]) - fieldOrder.indexOf(right[0])),
297
+ );
114
298
  };
115
299
 
116
300
  const getConjuncts = (expression: Expression, environment: Environment): Expression[] => {
@@ -125,39 +309,66 @@ const getConjuncts = (expression: Expression, environment: Environment): Express
125
309
  return [expression];
126
310
  };
127
311
 
128
- export const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
312
+ const isConstantTrue = (item: ScopedExpression, environment: Environment, usage: string) => {
313
+ const conjunct = item.expression;
314
+ if (conjunct.kind !== "Identifier" || getLevel(conjunct, item.scope, environment) > 0) {
315
+ return false;
316
+ }
317
+ const value = evaluate(conjunct, getContext(environment, undefined, undefined, item.scope));
318
+ if (value === false) {
319
+ throw new TlaConfigError(`The spec is trivially false because ${conjunct.name} is false.`);
320
+ }
321
+ if (value !== true) {
322
+ throw new TlaConfigError(
323
+ `The operator ${conjunct.name}, which equals ${formatValue(value)},\ncannot be used as a ${usage}`,
324
+ );
325
+ }
326
+ return true;
327
+ };
328
+
329
+ const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
129
330
  if (config.specification === undefined) {
130
- if (config.init === undefined)
131
- throw new TlaConfigError(
132
- "The configuration file did not specify the initial state predicate",
133
- );
134
- if (config.next === undefined)
135
- throw new TlaConfigError("The configuration does not specify NEXT");
136
- getDefinitionBody(config.init, environment);
137
- getDefinitionBody(config.next, environment);
331
+ const getOperator = (name: string | undefined, description: string) => {
332
+ if (name === undefined) return undefined;
333
+ const body = getConfigOperator(description, name, environment).body;
334
+ const identifier = createIdentifier(name);
335
+ // TLC evaluates a literal body later and reports that it is not a boolean.
336
+ const isLiteral = body.kind === "Number" || body.kind === "String";
337
+ if (!isLiteral && getLevel(identifier, undefined, environment) === 0) {
338
+ throw new TlaConfigError(`The ${description} ${name} cannot be a constant.`);
339
+ }
340
+ return identifier;
341
+ };
138
342
  return {
139
- init: createIdentifier(config.init),
140
- next: createIdentifier(config.next),
343
+ init: getOperator(config.init, "initial predicate"),
344
+ next: getOperator(config.next, "next state action"),
345
+ scope: undefined,
141
346
  temporals: [],
142
347
  };
143
348
  }
144
- const initConjuncts: Expression[] = [];
145
- const nextActions: Expression[] = [];
349
+ const initConjuncts: ScopedExpression[] = [];
350
+ const nextActions: ScopedExpression[] = [];
146
351
  const temporals: ScopedExpression[] = [];
147
- const body = getDefinitionBody(config.specification, environment);
148
- const getUnscoped = (expression: Expression, scope: Scope | undefined) => {
149
- const unscoped = toUnscopedExpression(expression, scope);
150
- if (!unscoped) {
151
- throw new TlaUnsupportedError(
152
- `The specification ${config.specification} has an initial predicate or next-state relation inside a quantified formula`,
352
+ const definition = getConfigOperator("name", config.specification, environment);
353
+ const value = getConstantValue(config.specification, definition, environment);
354
+ if (value !== undefined) {
355
+ throw new TlaConfigError(
356
+ `The value of ${config.specification} is equal to ${formatValue(value)}`,
357
+ );
358
+ }
359
+ expandTemporal(definition.body, undefined, environment, false).forEach((item) => {
360
+ const conjunct = item.expression;
361
+ if (isConstantTrue(item, environment, "spec")) return;
362
+ if (conjunct.kind === "UnboundedQuantifier" && conjunct.isTemporal) {
363
+ throw setExitCode(
364
+ new TlaConfigError(
365
+ "TLC does not support temporal existential, nor universal, quantification over state variables.",
366
+ ),
367
+ EXIT_STATUS.error,
153
368
  );
154
369
  }
155
- return unscoped;
156
- };
157
- expandTemporal(body, undefined, environment).forEach((item) => {
158
- const conjunct = item.expression;
159
370
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
160
- nextActions.push(getUnscoped(conjunct.expression.action, item.scope));
371
+ nextActions.push({ expression: conjunct.expression.action, scope: item.scope });
161
372
  return;
162
373
  }
163
374
  if (
@@ -178,21 +389,54 @@ export const getSpecification = (config: ModelConfig, environment: Environment):
178
389
  `TLC cannot handle the action-level conjunct of the specification ${config.specification}`,
179
390
  );
180
391
  }
181
- initConjuncts.push(getUnscoped(conjunct, item.scope));
392
+ initConjuncts.push(item);
182
393
  });
183
- if (nextActions.length !== 1) {
394
+ if (nextActions.length > 1) {
184
395
  throw new TlaConfigError(
185
- `The specification ${config.specification} must contain exactly one [][Next]_vars`,
396
+ `The specification ${config.specification} must contain at most one [][Next]_vars`,
186
397
  );
187
398
  }
399
+ const items = [...initConjuncts, ...nextActions];
400
+ const getName = (index: number) => `$specification${index}`;
401
+ const scope = items.reduce<Scope | undefined>(
402
+ (parent, item, index) =>
403
+ item.scope === undefined
404
+ ? parent
405
+ : {
406
+ name: getName(index),
407
+ binding: {
408
+ kind: "Thunk",
409
+ expression: item.expression,
410
+ scope: item.scope,
411
+ state: undefined,
412
+ next: undefined,
413
+ cache: undefined,
414
+ },
415
+ parent,
416
+ },
417
+ undefined,
418
+ );
419
+ const getReference = (item: ScopedExpression, index: number): Expression =>
420
+ item.scope === undefined
421
+ ? item.expression
422
+ : {
423
+ kind: "Identifier",
424
+ name: getName(index),
425
+ location: item.expression.location,
426
+ resolution: { kind: "Local" },
427
+ };
188
428
  return {
189
- init: { kind: "And", operands: initConjuncts, location: START },
190
- next: nextActions[0],
429
+ init:
430
+ initConjuncts.length === 0
431
+ ? undefined
432
+ : { kind: "And", operands: initConjuncts.map(getReference), location: START },
433
+ next: nextActions.length === 0 ? undefined : getReference(nextActions[0], initConjuncts.length),
434
+ scope,
191
435
  temporals,
192
436
  };
193
437
  };
194
438
 
195
- export const getProperties = (config: ModelConfig, environment: Environment): Properties => {
439
+ const getProperties = (config: ModelConfig, environment: Environment): Properties => {
196
440
  const properties: Properties = {
197
441
  initialPredicates: [],
198
442
  invariants: [],
@@ -200,12 +444,15 @@ export const getProperties = (config: ModelConfig, environment: Environment): Pr
200
444
  liveness: [],
201
445
  };
202
446
  config.properties.forEach((name) => {
203
- const body = getDefinitionBody(name, environment);
204
- expandTemporal(body, undefined, environment).forEach((item) => {
447
+ const definition = getConfigPredicate("property", name, environment);
448
+ if (!definition) return;
449
+ expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
205
450
  const conjunct = item.expression;
451
+ if (isConstantTrue(item, environment, "property")) return;
206
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
207
453
  properties.actionProperties.push({
208
454
  name,
455
+ box: conjunct.expression,
209
456
  action: conjunct.expression.action,
210
457
  subscript: conjunct.expression.subscript,
211
458
  scope: item.scope,
@@ -233,27 +480,66 @@ export const getProperties = (config: ModelConfig, environment: Environment): Pr
233
480
  return properties;
234
481
  };
235
482
 
236
- export const getNamedExpressions = (names: string[], environment: Environment): NamedExpression[] =>
237
- names.map((name) => {
238
- getDefinitionBody(name, environment);
239
- return { name, expression: createIdentifier(name), scope: undefined };
483
+ const getNamedExpressions = (
484
+ kind: string,
485
+ names: string[],
486
+ environment: Environment,
487
+ ): NamedExpression[] =>
488
+ names.flatMap((name) =>
489
+ getConfigPredicate(kind, name, environment)
490
+ ? [{ name, expression: createIdentifier(name), scope: undefined }]
491
+ : [],
492
+ );
493
+
494
+ const getBodyRange = (name: string, environment: Environment) => {
495
+ const definition = getDefinition(name, environment);
496
+ return definition?.kind === "Operator" ? definition.bodyRange : undefined;
497
+ };
498
+
499
+ const getPossiblePredicates = (names: string[], environment: Environment) =>
500
+ names.map((name, index) => {
501
+ if (names.indexOf(name) !== index) {
502
+ throw new TlaConfigError(`_POSSIBLE lists ${name} more than once`);
503
+ }
504
+ getConfigDefinition("possible", name, environment);
505
+ const expression = createIdentifier(name);
506
+ if (getLevel(expression, undefined, environment) === TEMPORAL_LEVEL) {
507
+ throw new TlaConfigError(
508
+ `The possible of ${name} is equal to a temporal formula; only state- and action-level predicates are supported`,
509
+ );
510
+ }
511
+ return { name, expression, scope: undefined };
240
512
  });
241
513
 
242
- export const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
514
+ const getMembership = (
515
+ expression: Expression,
516
+ variables: number[] | undefined,
517
+ environment: Environment,
518
+ ): Membership | undefined => {
519
+ if (expression.kind !== "Apply" || expression.operator !== "\\in" || variables?.length !== 1)
520
+ return undefined;
521
+ const element = expression.args[0];
522
+ if (element.kind !== "Identifier" || isLocallyResolved(element)) return undefined;
523
+ return environment.variableIndex.get(element.name) === variables[0]
524
+ ? { variable: variables[0], set: expression.args[1] }
525
+ : undefined;
526
+ };
527
+
528
+ const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
243
529
  named.flatMap((item) =>
244
- getConjuncts(item.expression, environment).map((expression) => ({
245
- name: item.name,
246
- expression,
247
- scope: item.scope,
248
- variables: getReadVariables(expression, environment),
249
- })),
530
+ getConjuncts(item.expression, environment).map((expression) => {
531
+ const variables = getReadVariables(expression, environment);
532
+ return {
533
+ name: item.name,
534
+ expression,
535
+ scope: item.scope,
536
+ variables,
537
+ membership: getMembership(expression, variables, environment),
538
+ };
539
+ }),
250
540
  );
251
541
 
252
- export const isUnchangedFor = (
253
- stateCheck: StateCheck,
254
- state: Value[],
255
- parent: Value[] | undefined,
256
- ) => {
542
+ const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
257
543
  const variables = stateCheck.variables;
258
544
  if (!parent || !variables) return false;
259
545
  for (let index = 0; index < variables.length; index++) {
@@ -262,10 +548,40 @@ export const isUnchangedFor = (
262
548
  return true;
263
549
  };
264
550
 
265
- export interface Search {
551
+ const WIDE_CHARACTER = /[\u0100-\uffff]/;
552
+
553
+ const DESERIALIZERS = new Set(["JsonDeserialize", "ndJsonDeserialize"]);
554
+
555
+ const isWideConfigValue = (value: ConfigValue): boolean =>
556
+ value.kind === "String"
557
+ ? WIDE_CHARACTER.test(value.value)
558
+ : value.kind === "Set" && value.elements.some(isWideConfigValue);
559
+
560
+ const isWideExpression = (expression: Expression): boolean =>
561
+ (expression.kind === "String" && WIDE_CHARACTER.test(expression.value)) ||
562
+ (expression.kind === "Apply" && DESERIALIZERS.has(expression.operator)) ||
563
+ getChildren(expression).some(isWideExpression);
564
+
565
+ // TLC fingerprints a string by the low byte of each character, so it merges states whose
566
+ // strings differ only above U+00FF. Strings reach a state from literals, the config, or files.
567
+ const hasWideString = (config: ModelConfig, environment: Environment) =>
568
+ config.constants.some(
569
+ (constant) =>
570
+ isWideConfigValue(constant.value) || (constant.args ?? []).some(isWideConfigValue),
571
+ ) ||
572
+ [...environment.definitions.values()].some(
573
+ (definition) =>
574
+ isWideExpression(definition.body) ||
575
+ (definition.kind === "Function" &&
576
+ definition.bounds.some((bound) => isWideExpression(bound.set))),
577
+ );
578
+
579
+ interface Search {
266
580
  properties: Properties;
267
581
  spec: Specification;
268
582
  getFingerprintState: (state: Value[]) => Value[];
583
+ getStoredFingerprints: (states: Value[][], fingerprintStates: Value[][]) => BigInt64Array;
584
+ getTlcOrder: () => number[];
269
585
  isSymmetric: boolean;
270
586
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
271
587
  satisfiesConstraints: (state: Value[], parent?: Value[]) => boolean;
@@ -274,9 +590,8 @@ export interface Search {
274
590
  satisfiesActionConstraints: (state: Value[], next: Value[]) => boolean;
275
591
  trackStatePossible: (state: Value[]) => void;
276
592
  trackActionPossible: (state: Value[], next: Value[]) => void;
277
- findPostconditionViolation: (
278
- print: (text: string) => void,
279
- ) => Omit<Violation, "loopStart"> | undefined;
593
+ findUnwitnessedPossible: () => Postcondition | undefined;
594
+ findPostconditionViolation: () => Postcondition | undefined;
280
595
  }
281
596
 
282
597
  const getContext = (
@@ -284,11 +599,39 @@ const getContext = (
284
599
  state: Value[] | undefined,
285
600
  next: Value[] | undefined,
286
601
  scope?: Scope,
287
- ): Context => ({ environment, scope, state, next });
602
+ ) => ({ environment, scope, state, next });
288
603
 
289
604
  const holds = (expression: Expression, context: Context, description: string) =>
290
605
  expectBoolean(evaluate(expression, context), description);
291
606
 
607
+ // TLC names a check that is not a boolean by the location of the predicate it evaluates.
608
+ const holdsLikeTlc = (
609
+ expression: Expression,
610
+ context: Context,
611
+ getMessage = getExpectedBoolean,
612
+ ) => {
613
+ const value = evaluate(expression, context);
614
+ if (typeof value !== "boolean") {
615
+ throw new TlaEvaluationError(getMessage(expression, context.environment));
616
+ }
617
+ return value;
618
+ };
619
+
620
+ // SANY prints a number by its digits and any other expression by its location.
621
+ const getExpectedBoolean = (expression: Expression, environment: Environment) => {
622
+ const definition =
623
+ expression.kind === "Identifier" ? getDefinition(expression.name, environment) : undefined;
624
+ const body = definition?.kind === "Operator" ? definition.body : expression;
625
+ const range = definition?.kind === "Operator" ? definition.bodyRange : undefined;
626
+ const location =
627
+ body.kind === "Number"
628
+ ? (body.text ?? String(body.value))
629
+ : range
630
+ ? formatRange(range)
631
+ : describeRange(body);
632
+ return `TLC expected a boolean value, but did not find one. ${location}`;
633
+ };
634
+
292
635
  const ignorePossible = () => {};
293
636
 
294
637
  const trackPossible = (items: NamedExpression[], runtime: CheckerRuntime, context: Context) =>
@@ -320,36 +663,56 @@ export const findAssumptionViolation = (
320
663
  for (const assumption of assumptions.filter((candidate) => !candidate.isAxiom)) {
321
664
  const failure = getConstantFailure(assumption.expression, environment, "an assumption");
322
665
  if (failure) {
323
- const name =
324
- assumption.name ?? `line ${assumption.location.line}, column ${assumption.location.column}`;
325
- return { name, trace: [], message: failure.message };
666
+ return { name: describeRange(assumption.expression), trace: [], message: failure.message };
326
667
  }
327
668
  }
328
669
  return undefined;
329
670
  };
330
671
 
331
- export const createSearch = (config: ModelConfig, environment: Environment): Search | undefined => {
672
+ export const createSearch = (
673
+ config: ModelConfig,
674
+ environment: Environment,
675
+ getVariableOrder: () => string[],
676
+ ): Search | undefined => {
677
+ const configInvariants = getInvariants(config.invariants, environment);
678
+ const spec = getSpecification(config, environment);
332
679
  const properties = getProperties(config, environment);
333
- const invariants = getStateChecks(
334
- [...getNamedExpressions(config.invariants, environment), ...properties.invariants],
680
+ const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
681
+ const isCheckingBehaviors =
682
+ invariants.length > 0 ||
683
+ properties.actionProperties.length > 0 ||
684
+ properties.liveness.length > 0;
685
+ if (
686
+ spec.init === undefined &&
687
+ (isCheckingBehaviors ||
688
+ properties.initialPredicates.length > 0 ||
689
+ environment.variables.length > 0)
690
+ ) {
691
+ throw new TlaConfigError("The configuration file did not specify the initial state predicate.");
692
+ }
693
+ if (spec.next === undefined && isCheckingBehaviors) {
694
+ throw new TlaConfigError("The configuration file did not specify the next state predicate.");
695
+ }
696
+ const constraints = getStateChecks(
697
+ getNamedExpressions("constraint", config.constraints, environment),
335
698
  environment,
336
699
  );
337
- const isConstantModel =
338
- config.specification === undefined &&
339
- config.init === undefined &&
340
- environment.variables.length === 0;
341
- if (isConstantModel) return undefined;
342
- const spec = getSpecification(config, environment);
700
+ const actionConstraints = getNamedExpressions(
701
+ "action constraint",
702
+ config.actionConstraints,
703
+ environment,
704
+ );
705
+ if (config.rlReward !== undefined) getConfigOperator("rlreward", config.rlReward, environment);
706
+ if (config.periodic !== undefined) getConfigOperator("periodic", config.periodic, environment);
707
+ const possible = getPossiblePredicates(config.possible, environment);
343
708
  if (environment.variables.length === 0) return undefined;
344
709
  const symmetryGroup =
345
710
  config.symmetry === undefined ? [] : getSymmetryGroup(config.symmetry, environment);
711
+ if (config.view !== undefined) getConfigOperator("view function", config.view, environment);
346
712
  const view =
347
- config.view === undefined ? undefined : getNamedExpressions([config.view], environment)[0];
348
- const constraints = getStateChecks(
349
- getNamedExpressions(config.constraints, environment),
350
- environment,
351
- );
352
- const actionConstraints = getNamedExpressions(config.actionConstraints, environment);
713
+ config.view === undefined
714
+ ? undefined
715
+ : { name: config.view, expression: createIdentifier(config.view), scope: undefined };
353
716
  const actionProperties = properties.actionProperties.map((property) => {
354
717
  const unchanged: Expression = {
355
718
  kind: "Unchanged",
@@ -358,72 +721,138 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
358
721
  };
359
722
  return { ...property, unchanged };
360
723
  });
361
- const possible = getNamedExpressions(config.possible, environment);
362
724
  const isActionPossible = (item: NamedExpression) =>
363
725
  getLevel(item.expression, undefined, environment) >= ACTION_LEVEL;
364
726
  const statePossible = possible.filter((item) => !isActionPossible(item));
365
727
  const actionPossible = possible.filter(isActionPossible);
366
728
  const runtime = environment.runtime;
729
+ const tlcOrder = { indices: undefined as number[] | undefined };
730
+ const getTlcOrder = () => {
731
+ if (tlcOrder.indices) return tlcOrder.indices;
732
+ const variableOrder = getVariableOrder();
733
+ const getTlcPosition = (index: number) => {
734
+ const position = variableOrder.indexOf(environment.variables[index]);
735
+ return position === -1 ? environment.variables.length : position;
736
+ };
737
+ tlcOrder.indices = environment.variables
738
+ .map((_, index) => index)
739
+ .sort((left, right) => getTlcPosition(left) - getTlcPosition(right));
740
+ return tlcOrder.indices;
741
+ };
742
+ // A representative in TLC's variable order is the one whose fingerprint TLC reports.
743
+ const order = symmetryGroup.length > 0 ? getTlcOrder() : undefined;
744
+ const getViewValue = (expression: Expression, state: Value[]) =>
745
+ evaluate(expression, getContext(environment, state, undefined));
746
+ const getTlcStateFingerprint = (state: Value[]) => {
747
+ const indices = getTlcOrder();
748
+ const representative =
749
+ symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, indices);
750
+ return getTlcFingerprint(
751
+ view === undefined
752
+ ? indices.map((index) => representative[index])
753
+ : [getViewValue(view.expression, representative)],
754
+ );
755
+ };
756
+ const isFingerprintedLikeTlc = hasWideString(config, environment);
757
+ runtime.getFingerprint = getTlcStateFingerprint;
758
+ const findUnwitnessedPossible = () => {
759
+ const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
760
+ if (!unwitnessed) return undefined;
761
+ const range = getBodyRange(unwitnessed.name, environment);
762
+ const location = range ? ` at ${formatRange(range)}` : "";
763
+ return {
764
+ name: unwitnessed.name,
765
+ message: `The _POSSIBLE predicate ${unwitnessed.name}${location} was never witnessed.\nOthers may be unwitnessed too; only witnessed predicates appear with a\nnon-zero count in the record printed above.\nSee https://explain.tlapl.us/possible-conditions for additional details.`,
766
+ counts: prettyPrint(formatValue(getPossibleCounts(runtime), true)),
767
+ };
768
+ };
367
769
  return {
368
770
  properties,
369
771
  spec,
370
772
  isSymmetric: symmetryGroup.length > 0,
773
+ getTlcOrder,
774
+ getStoredFingerprints: (states, fingerprintStates) => {
775
+ if (view !== undefined || isFingerprintedLikeTlc) {
776
+ return BigInt64Array.from(states, getTlcStateFingerprint);
777
+ }
778
+ const indices = getTlcOrder();
779
+ const getFingerprint = createTlcFingerprinter();
780
+ return BigInt64Array.from(fingerprintStates, (state) =>
781
+ getFingerprint(indices.map((index) => state[index])),
782
+ );
783
+ },
371
784
  getFingerprintState: (state) => {
785
+ if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
372
786
  const representative =
373
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup);
374
- return view === undefined
375
- ? representative
376
- : [evaluate(view.expression, getContext(environment, representative, undefined))];
787
+ symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, order);
788
+ return view === undefined ? representative : [getViewValue(view.expression, representative)];
377
789
  },
378
790
  findViolatedInvariant: (state, parent) =>
379
- invariants.find(
380
- (invariant) =>
381
- !isUnchangedFor(invariant, state, parent) &&
382
- !holds(
383
- invariant.expression,
384
- getContext(environment, state, undefined, invariant.scope),
385
- `invariant ${invariant.name}`,
386
- ),
387
- ),
791
+ invariants.find((invariant) => {
792
+ if (isUnchangedFor(invariant, state, parent)) return false;
793
+ try {
794
+ const context = getContext(environment, state, undefined, invariant.scope);
795
+ const membership = invariant.membership;
796
+ // The parent satisfies every invariant, so only the entries the step changed can fail.
797
+ return parent && membership
798
+ ? !isUpdatedElementOf(
799
+ state[membership.variable],
800
+ parent[membership.variable],
801
+ evaluate(membership.set, context),
802
+ )
803
+ : !holdsLikeTlc(invariant.expression, context);
804
+ } catch (error) {
805
+ // TLC reports a failure only on a state after the initial states as an invariant failure.
806
+ if (!parent) throw error;
807
+ throw withHeadline(
808
+ setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
809
+ `Evaluating invariant ${invariant.name} failed.`,
810
+ );
811
+ }
812
+ }),
388
813
  satisfiesConstraints: (state, parent) =>
389
814
  constraints.every(
390
815
  (constraint) =>
391
816
  isUnchangedFor(constraint, state, parent) ||
392
- holds(
393
- constraint.expression,
394
- getContext(environment, state, undefined),
395
- `constraint ${constraint.name}`,
396
- ),
817
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
397
818
  ),
398
819
  findFailedInitialPredicate: (state) =>
399
820
  properties.initialPredicates.find(
400
821
  (predicate) =>
401
- !holds(
822
+ !holdsLikeTlc(
402
823
  predicate.expression,
403
824
  getContext(environment, state, undefined, predicate.scope),
404
- `property ${predicate.name}`,
405
825
  ),
406
826
  ),
407
827
  findViolatedActionProperty: (state, next) =>
408
- actionProperties.find(
409
- (property) =>
410
- !holds(
411
- property.action,
412
- getContext(environment, state, next, property.scope),
413
- `property ${property.name}`,
414
- ) &&
415
- !holds(
416
- property.unchanged,
417
- getContext(environment, state, next, property.scope),
418
- "a subscript",
419
- ),
420
- ),
828
+ actionProperties.find((property) => {
829
+ try {
830
+ return (
831
+ !holdsLikeTlc(
832
+ property.action,
833
+ getContext(environment, state, next, property.scope),
834
+ () =>
835
+ `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
836
+ ) &&
837
+ !holds(
838
+ property.unchanged,
839
+ getContext(environment, state, next, property.scope),
840
+ "a subscript",
841
+ )
842
+ );
843
+ } catch (error) {
844
+ throw withHeadline(
845
+ withNextStateExitCode(error),
846
+ `Evaluating action property ${property.name} failed.`,
847
+ );
848
+ }
849
+ }),
421
850
  satisfiesActionConstraints: (state, next) =>
422
851
  actionConstraints.every((constraint) =>
423
- holds(
852
+ holdsLikeTlc(
424
853
  constraint.expression,
425
854
  getContext(environment, state, next),
426
- `action constraint ${constraint.name}`,
855
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
427
856
  ),
428
857
  ),
429
858
  trackStatePossible:
@@ -436,20 +865,14 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
436
865
  ? ignorePossible
437
866
  : (state, next) =>
438
867
  trackPossible(actionPossible, runtime, getContext(environment, state, next)),
439
- findPostconditionViolation: (print) => {
440
- const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
441
- if (unwitnessed) {
442
- print(formatValue(getPossibleCounts(runtime), true));
443
- return {
444
- name: unwitnessed.name,
445
- trace: [],
446
- message: `The _POSSIBLE predicate ${unwitnessed.name} was never witnessed.`,
447
- };
448
- }
868
+ findUnwitnessedPossible,
869
+ findPostconditionViolation: () => {
870
+ const unwitnessed = findUnwitnessedPossible();
871
+ if (unwitnessed) return unwitnessed;
449
872
  for (const name of config.postconditions) {
450
873
  const failure = getConstantFailure(createIdentifier(name), environment, "a postcondition");
451
874
  if (failure) {
452
- return { name, trace: [], message: failure.message ?? `Postcondition ${name} is false.` };
875
+ return { name, message: failure.message ?? `Postcondition ${name} is false.` };
453
876
  }
454
877
  }
455
878
  return undefined;
@@ -457,37 +880,154 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
457
880
  };
458
881
  };
459
882
 
460
- export const check = (options: CheckOptions): CheckResult => {
883
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
884
+ // computation of next states. In every other phase, the phase decides the code.
885
+ const withNextStateExitCode = (error: unknown) =>
886
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
887
+
888
+ const withHeadline = (error: unknown, headline: string) =>
889
+ error instanceof TlaEvaluationError
890
+ ? setExitCode(
891
+ new TlaEvaluationError(`${headline}\n${error.message}`, error),
892
+ getErrorExitCode(error),
893
+ )
894
+ : error;
895
+
896
+ // TLC finishes the -dump file whether or not the search finds a violation.
897
+ export const checkSequentially = (options: CheckOptions): CheckResult => {
898
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
899
+ const result = searchStates(options, stateWriter);
900
+ stateWriter?.close();
901
+ return result;
902
+ };
903
+
904
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
461
905
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
462
- const print = options.onPrint ?? console.log;
463
- const specification = createEnvironment(parseModule(options.source), config, {
906
+ const onPrint = options.onPrint ?? console.log;
907
+ // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
908
+ // before the trace would misplace them, so rebuilding a trace prints nothing.
909
+ const output = { isMuted: false };
910
+ const print = (text: string) => {
911
+ if (!output.isMuted) onPrint(text);
912
+ };
913
+ const withoutOutput = <Result>(rebuild: () => Result) => {
914
+ output.isMuted = true;
915
+ const result = rebuild();
916
+ output.isMuted = false;
917
+ return result;
918
+ };
919
+ setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
920
+ const specification = createEnvironment(config, {
921
+ source: options.source,
464
922
  loadModule: options.loadModule,
923
+ loadClass: options.loadClass,
465
924
  print,
466
925
  files: { readFile: options.readFile, writeFile: options.writeFile },
926
+ seed: options.seed,
467
927
  });
468
928
  const environment = specification.environment;
469
929
  const runtime = environment.runtime;
930
+ runtime.pause = options.onPause ?? (() => {});
931
+ runtime.getSpecification = () =>
932
+ getSpecificationValue(
933
+ config,
934
+ environment,
935
+ specification.variableLocations,
936
+ specification.instanceActions,
937
+ );
470
938
  const statistics = { depth: 0 };
471
939
  const createResult = (
472
940
  status: CheckStatus,
473
941
  violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
942
+ failure?: EvaluationFailure,
474
943
  ): CheckResult => ({
475
944
  status,
476
945
  violation: violation && { ...violation, loopStart: violation.loopStart },
946
+ failure,
477
947
  generatedStates: runtime.generatedStates,
478
948
  distinctStates: runtime.distinctStates,
479
- depth: statistics.depth,
949
+ queuedStates: runtime.queueSize,
950
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
951
+ outDegrees: undefined,
952
+ fingerprintDistance: undefined,
953
+ });
954
+ const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
955
+ const expansion = { newStates: 0 };
956
+ const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
957
+ // TLC counts the state it was expanding when an evaluation failed.
958
+ const getPartialOutDegrees = () =>
959
+ outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
960
+ const createSuccess = (): CheckResult => ({
961
+ ...createResult("success"),
962
+ outDegrees: [...outDegrees],
963
+ fingerprintDistance: getFingerprintDistance(
964
+ runtime.distinctStates,
965
+ runtime.generatedStates,
966
+ () =>
967
+ search
968
+ ? search.getStoredFingerprints(states, fingerprintStates)
969
+ : BigInt64Array.from(states, runtime.getFingerprint),
970
+ ),
480
971
  });
481
972
 
973
+ const search = createSearch(config, environment, () =>
974
+ getTlcVariableOrder(options.source, options.loadModule),
975
+ );
482
976
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
483
977
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
484
-
485
- const search = createSearch(config, environment);
486
- if (!search) return createResult("success");
487
- const properties = search.properties;
978
+ if (!search) return createSuccess();
979
+ const hasPostconditions = config.postconditions.length > 0 || config.possible.length > 0;
980
+ const reportViolation = (
981
+ status: CheckStatus,
982
+ violation: Omit<Violation, "loopStart"> & { loopStart?: number },
983
+ getLoopAction?: () => string | undefined,
984
+ ) => {
985
+ if (hasPostconditions) {
986
+ const start = violation.loopStart;
987
+ runtime.counterExample = createCounterExample(
988
+ violation.trace,
989
+ start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
990
+ );
991
+ }
992
+ const unwitnessed = search.findUnwitnessedPossible();
993
+ if (!unwitnessed) search.findPostconditionViolation();
994
+ return createResult(status, unwitnessed ? { ...violation, unwitnessed } : violation);
995
+ };
488
996
  const spec = search.spec;
489
997
  const getFingerprintState = search.getFingerprintState;
490
- const liveness = createLivenessChecker(properties.liveness, spec.temporals, environment);
998
+ const nextActions = { value: undefined as SpecAction[] | undefined };
999
+ const isReducing = config.view !== undefined || config.symmetry !== undefined;
1000
+ const tlcFingerprints: number[] = [];
1001
+ const liveness = withLivenessExitCode(() =>
1002
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1003
+ getFingerprint: (index) =>
1004
+ (tlcFingerprints[index] ??= Number(
1005
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1006
+ )),
1007
+ getSuccessors: (state) => {
1008
+ const successors: LiveSuccessor[] = [];
1009
+ if (spec.next === undefined) return successors;
1010
+ forEachSuccessor(
1011
+ spec.next,
1012
+ state,
1013
+ environment,
1014
+ (successor) => {
1015
+ canonicalizeState(successor.state);
1016
+ const isInModel =
1017
+ search.satisfiesConstraints(successor.state, state) &&
1018
+ search.satisfiesActionConstraints(state, successor.state);
1019
+ if (!isInModel) return false;
1020
+ const fingerprintState = getFingerprintState(successor.state);
1021
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1022
+ successors.push({ index, state: successor.state });
1023
+ return false;
1024
+ },
1025
+ spec.scope,
1026
+ );
1027
+ return successors;
1028
+ },
1029
+ }),
1030
+ );
491
1031
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
492
1032
 
493
1033
  const states: Value[][] = [];
@@ -498,30 +1038,151 @@ export const check = (options: CheckOptions): CheckResult => {
498
1038
  const buckets = new Map<number, number | number[]>();
499
1039
  const canonicalizeState = createCanonicalizer();
500
1040
 
501
- const toRecord = (state: Value[]) =>
502
- Object.fromEntries(environment.variables.map((name, index) => [name, state[index]]));
503
- const getTrace = (
504
- index: number,
505
- last?: { state: Value[]; action: string | undefined },
506
- ): TraceStep[] => {
507
- const steps: TraceStep[] = last ? [{ action: last.action, state: toRecord(last.state) }] : [];
508
- for (let current = index; current !== -1; current = parents[current]) {
509
- steps.push({ action: actions[current], state: toRecord(states[current]) });
1041
+ const toRecord = (state: Value[]): Record<string, Value> =>
1042
+ Object.fromEntries(
1043
+ search.getTlcOrder().map((index) => [environment.variables[index], state[index]]),
1044
+ );
1045
+ const getAliasState = (
1046
+ alias: string,
1047
+ steps: Successor[],
1048
+ position: number,
1049
+ loopStart: number | undefined,
1050
+ ) => {
1051
+ // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1052
+ runtime.getLevel = () => position + 1;
1053
+ runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1054
+ return evaluateAlias(
1055
+ alias,
1056
+ steps[position].state,
1057
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1058
+ );
1059
+ };
1060
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1061
+ try {
1062
+ const body = getConfigDefinition("alias", alias, environment).body;
1063
+ const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
1064
+ const fieldOrder = body.kind === "Record" ? body.fields.map((field) => field.name) : [];
1065
+ return toAliasRecord(value, fieldOrder) ?? toRecord(state);
1066
+ } catch (error) {
1067
+ if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1068
+ return { ...toRecord(state), _ALIASEvalError: error.message };
510
1069
  }
511
- return steps.reverse();
512
- };
513
- const getPathTrace = (path: number[]) =>
514
- path.map((stateIndex, position): TraceStep => {
515
- if (position === 0) return { action: undefined, state: toRecord(states[stateIndex]) };
516
- const previous = path[position - 1];
517
- const action =
518
- previous === stateIndex
519
- ? "Stuttering"
520
- : getSuccessors(spec.next, states[previous], environment).find((successor) =>
521
- isSameState(successor.state, states[stateIndex]),
522
- )?.action;
523
- return { action, state: toRecord(states[stateIndex]) };
1070
+ };
1071
+ // TLC labels a step with the first action that takes it, evaluated as when the search expanded
1072
+ // the previous state.
1073
+ const getLabel = (index: number, previous: Value[], state: Value[]) => {
1074
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1075
+ const expanding = { ...current };
1076
+ Object.assign(current, { index, isExpanding: true, candidate: undefined });
1077
+ const fingerprintState = getFingerprintState(state);
1078
+ const action = nextActions.value.find((item) =>
1079
+ getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
1080
+ isSameState(getFingerprintState(successor.state), fingerprintState),
1081
+ ),
1082
+ );
1083
+ Object.assign(current, expanding);
1084
+ return action && getActionLabel(action);
1085
+ };
1086
+ const toTrace = (steps: Successor[], path: number[], loopStart?: number): TraceStep[] => {
1087
+ const alias = config.alias;
1088
+ const labels = withoutOutput(() => {
1089
+ // TLC rebuilds a trace from the initial predicate, which can reset what TLCSet stored.
1090
+ if (steps.length > 1 && isImpure(environment)) getSpecInitialStates();
1091
+ // TLC finds the action that takes each step before it evaluates the alias.
1092
+ return steps.map((step, position) =>
1093
+ position === 0 || step.action === "Stuttering"
1094
+ ? undefined
1095
+ : getLabel(path[position - 1], steps[position - 1].state, step.state),
1096
+ );
524
1097
  });
1098
+ return steps.map((step, position) => ({
1099
+ action: step.action,
1100
+ label: labels[position],
1101
+ state:
1102
+ alias === undefined
1103
+ ? toRecord(step.state)
1104
+ : getAliasState(alias, steps, position, loopStart),
1105
+ }));
1106
+ };
1107
+ const getSpecInitialStates = () =>
1108
+ spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1109
+ const getTraceSuccessors = (state: Value[]) =>
1110
+ spec.next === undefined ? [] : getSuccessors(spec.next, state, environment, spec.scope);
1111
+ const hasFingerprint = (state: Value[], index: number) =>
1112
+ isSameState(getFingerprintState(state), fingerprintStates[index]);
1113
+ const findSuccessorWithFingerprint = (state: Value[], index: number) =>
1114
+ getTraceSuccessors(state).find((successor) => hasFingerprint(successor.state, index));
1115
+ const getPathStates = (path: number[], nextFailure: string) => {
1116
+ const initial =
1117
+ isReducing || isImpure(environment)
1118
+ ? getSpecInitialStates().find((state) => hasFingerprint(state, path[0]))
1119
+ : states[path[0]];
1120
+ if (!initial) throw new TlaEvaluationError(INITIAL_RECOVERY_FAILURE);
1121
+ const steps: Successor[] = [{ state: initial, action: undefined }];
1122
+ for (let position = 1; position < path.length; position++) {
1123
+ const previous = steps[position - 1].state;
1124
+ if (path[position - 1] === path[position]) {
1125
+ steps.push({ state: previous, action: "Stuttering" });
1126
+ continue;
1127
+ }
1128
+ const successor = findSuccessorWithFingerprint(previous, path[position]);
1129
+ if (!successor) throw new TlaEvaluationError(nextFailure);
1130
+ steps.push(successor);
1131
+ }
1132
+ return steps;
1133
+ };
1134
+ const getTrace = (index: number, last?: Successor) => {
1135
+ const path: number[] = [];
1136
+ for (let position = index; position !== -1; position = parents[position]) {
1137
+ path.unshift(position);
1138
+ }
1139
+ const steps =
1140
+ isReducing && path.length > 1
1141
+ ? getPathStates(path, INITIAL_RECOVERY_FAILURE)
1142
+ : path.map((position) => ({ state: states[position], action: actions[position] }));
1143
+ if (!last) return toTrace(steps, path);
1144
+ const action = isReducing
1145
+ ? getTraceSuccessors(states[index]).find((successor) =>
1146
+ isSameState(successor.state, last.state),
1147
+ )?.action
1148
+ : last.action;
1149
+ return toTrace([...steps, { state: last.state, action }], path);
1150
+ };
1151
+ // TLC prints an initial state on its own without evaluating the alias.
1152
+ const getStateTrace = (index: number) =>
1153
+ parents[index] === -1
1154
+ ? [{ action: undefined, label: undefined, state: toRecord(states[index]) }]
1155
+ : getTrace(index);
1156
+ // TLC names the initial state it was checking unless a standard module's Java code failed.
1157
+ const toFailure = (
1158
+ error: unknown,
1159
+ trace: TraceStep[],
1160
+ initialState?: Value[],
1161
+ failureOutDegrees?: number[],
1162
+ ) => {
1163
+ if (!(error instanceof TlaEvaluationError)) throw error;
1164
+ return {
1165
+ ...createResult("error", undefined, {
1166
+ message: error.message,
1167
+ trace,
1168
+ initialState:
1169
+ initialState && !(error instanceof TlaModuleError) ? toRecord(initialState) : undefined,
1170
+ exitCode: getErrorExitCode(error),
1171
+ }),
1172
+ outDegrees: failureOutDegrees,
1173
+ };
1174
+ };
1175
+ const getPathSteps = (path: number[], loopStart?: number) => {
1176
+ const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1177
+ const last = steps[steps.length - 1].state;
1178
+ const isClosed =
1179
+ !isReducing ||
1180
+ loopStart === undefined ||
1181
+ loopStart === path.length - 1 ||
1182
+ findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1183
+ if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1184
+ return steps;
1185
+ };
525
1186
  const getStateHash = (state: Value[]) => {
526
1187
  let hash = 0x811c9dc5;
527
1188
  for (let index = 0; index < state.length; index++)
@@ -572,21 +1233,44 @@ export const check = (options: CheckOptions): CheckResult => {
572
1233
  isExpanding: false,
573
1234
  candidate: undefined as Value[] | undefined,
574
1235
  candidateLevel: 0,
1236
+ livenessSource: -1,
575
1237
  };
576
1238
  const getPath = (index: number): Value[][] =>
577
1239
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
1240
+ runtime.isSeen = (state) => {
1241
+ const fingerprintState = getFingerprintState(state);
1242
+ return findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1;
1243
+ };
578
1244
  runtime.getBehavior = (state) => {
579
1245
  const index = state === current.candidate ? -1 : states.indexOf(state);
580
1246
  return index === -1 ? [...getPath(current.index), state] : getPath(index);
581
1247
  };
1248
+ runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1249
+ runtime.setLivenessSource = (index) => {
1250
+ current.livenessSource = index ?? -1;
1251
+ };
582
1252
  runtime.getLevel = (state) => {
1253
+ const source = current.livenessSource;
1254
+ if (source !== -1) return state === states[source] ? depths[source] : depths[source] + 1;
583
1255
  if (state === current.candidate) return current.candidateLevel;
584
1256
  if (current.index === -1) return 0;
585
1257
  if (state === states[current.index]) return depths[current.index];
586
1258
  return current.isExpanding ? depths[current.index] + 1 : 0;
587
1259
  };
588
1260
 
589
- for (const state of getInitialStates(spec.init, environment)) {
1261
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1262
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1263
+ level,
1264
+ getLabel: () =>
1265
+ formatState(
1266
+ config.alias === undefined
1267
+ ? toRecord(state)
1268
+ : evaluateAlias(config.alias, state, undefined),
1269
+ ),
1270
+ getText: () => formatState(toRecord(state)),
1271
+ });
1272
+
1273
+ const visitInitialState = (state: Value[]) => {
590
1274
  canonicalizeState(state);
591
1275
  runtime.generatedStates++;
592
1276
  runtime.initialStates++;
@@ -594,111 +1278,269 @@ export const check = (options: CheckOptions): CheckResult => {
594
1278
  current.candidateLevel = 1;
595
1279
  const fingerprintState = getFingerprintState(state);
596
1280
  const hash = getStateHash(fingerprintState);
597
- const isSeen = findStateIndex(hash, fingerprintState) !== -1;
598
- const isInModel = isSeen || search.satisfiesConstraints(state);
1281
+ const isInModel = search.satisfiesConstraints(state);
599
1282
  if (isInModel) search.trackStatePossible(state);
600
- if (isSeen) continue;
1283
+ const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1284
+ if (isSeen) return undefined;
601
1285
  if (isInModel) {
602
1286
  countDistinctState(1);
603
1287
  runtime.queueSize++;
604
1288
  liveness?.addInitialState(states.length, state);
1289
+ stateWriter?.writeInitialState(getGraphState(state, 1));
605
1290
  }
606
1291
  const violated = search.findViolatedInvariant(state);
607
1292
  if (violated) {
608
- return createResult("invariant-violation", {
1293
+ return reportViolation("invariant-violation", {
609
1294
  name: violated.name,
610
- trace: [{ action: undefined, state: toRecord(state) }],
1295
+ trace: toTrace([{ action: undefined, state }], []),
611
1296
  });
612
1297
  }
613
1298
  const failedPredicate = search.findFailedInitialPredicate(state);
614
1299
  if (failedPredicate) {
615
- return createResult("liveness-violation", {
1300
+ return reportViolation("liveness-violation", {
616
1301
  name: failedPredicate.name,
617
- trace: [{ action: undefined, state: toRecord(state) }],
1302
+ trace: toTrace([{ action: undefined, state }], []),
618
1303
  });
619
1304
  }
620
- if (!isInModel) continue;
1305
+ if (!isInModel) return undefined;
621
1306
  markSeen(hash, states.length);
622
1307
  addState(state, fingerprintState, -1, undefined);
623
- }
624
-
625
- for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1308
+ return undefined;
1309
+ };
1310
+ const visitSuccessor = (
1311
+ index: number,
1312
+ successor: Successor,
1313
+ liveSuccessors: LiveSuccessor[],
1314
+ source: GraphState | undefined,
1315
+ action: SpecAction | undefined,
1316
+ ) => {
626
1317
  const state = states[index];
627
- current.index = index;
628
- runtime.queueSize = states.length - index - 1;
629
- current.isExpanding = true;
630
- const successors = getSuccessors(spec.next, state, environment);
631
- current.isExpanding = false;
632
- if (successors.length === 0 && config.checkDeadlock) {
633
- return createResult("deadlock", { name: "deadlock", trace: getTrace(index) });
1318
+ runtime.generatedStates++;
1319
+ current.candidate = successor.state;
1320
+ current.candidateLevel = depths[index] + 1;
1321
+ if (isCanonicalizedFirst) canonicalizeState(successor.state);
1322
+ const fingerprintState = getFingerprintState(successor.state);
1323
+ const hash = getStateHash(fingerprintState);
1324
+ const found = findStateIndex(hash, fingerprintState);
1325
+ const isStateInModel = search.satisfiesConstraints(successor.state, state);
1326
+ if (isStateInModel) search.trackStatePossible(successor.state);
1327
+ const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1328
+ if (isInModel) search.trackActionPossible(state, successor.state);
1329
+ const existing = isInModel ? found : -1;
1330
+ if (source && isInModel) {
1331
+ stateWriter?.writeSuccessor(
1332
+ source,
1333
+ getGraphState(successor.state, depths[index] + 1),
1334
+ existing !== -1,
1335
+ action && { name: action.name, signature: getActionSignature(action) },
1336
+ );
634
1337
  }
635
- const liveSuccessors: LiveSuccessor[] = [];
636
- for (const successor of successors) {
637
- runtime.generatedStates++;
638
- current.candidate = successor.state;
639
- current.candidateLevel = depths[index] + 1;
640
- if (isCanonicalizedFirst) canonicalizeState(successor.state);
641
- const fingerprintState = getFingerprintState(successor.state);
642
- const hash = getStateHash(fingerprintState);
643
- const found = findStateIndex(hash, fingerprintState);
644
- const isStateInModel = found !== -1 || search.satisfiesConstraints(successor.state, state);
645
- if (isStateInModel) search.trackStatePossible(successor.state);
646
- const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
647
- if (isInModel) search.trackActionPossible(state, successor.state);
648
- const existing = isInModel ? found : -1;
649
- if (existing !== -1 && liveness) {
650
- const stored = states[existing];
651
- const isStored = stored.every((value, position) => value === successor.state[position]);
652
- liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
653
- }
654
- const isNew = isInModel && existing === -1;
655
- if (isNew) countDistinctState(depths[index] + 1);
656
- if (existing === -1) {
1338
+ if (existing !== -1 && liveness) {
1339
+ const stored = states[existing];
1340
+ const isStored = stored.every((value, position) => value === successor.state[position]);
1341
+ liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1342
+ }
1343
+ const isNew = isInModel && existing === -1;
1344
+ if (isNew) {
1345
+ countDistinctState(depths[index] + 1);
1346
+ expansion.newStates++;
1347
+ }
1348
+ if (existing === -1) {
1349
+ try {
657
1350
  const violated = search.findViolatedInvariant(successor.state, state);
658
1351
  if (violated) {
659
- return createResult("invariant-violation", {
1352
+ return reportViolation("invariant-violation", {
660
1353
  name: violated.name,
661
1354
  trace: getTrace(index, successor),
662
1355
  });
663
1356
  }
1357
+ } catch (error) {
1358
+ // TLC prints the outdegree when it cannot reproduce the failure, as for an invariant here.
1359
+ return toFailure(error, getTrace(index, successor), undefined, getPartialOutDegrees());
664
1360
  }
665
- const violatedProperty = search.findViolatedActionProperty(state, successor.state);
666
- if (violatedProperty) {
667
- return createResult("liveness-violation", {
668
- name: violatedProperty.name,
669
- trace: getTrace(index, successor),
670
- });
1361
+ }
1362
+ const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1363
+ if (violatedProperty) {
1364
+ return reportViolation("liveness-violation", {
1365
+ name: violatedProperty.name,
1366
+ trace: getTrace(index, successor),
1367
+ });
1368
+ }
1369
+ if (!isNew) return undefined;
1370
+ if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1371
+ markSeen(hash, states.length);
1372
+ if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1373
+ addState(successor.state, fingerprintState, index, successor.action);
1374
+ runtime.queueSize++;
1375
+ return undefined;
1376
+ };
1377
+
1378
+ const outcome: { result: CheckResult | undefined } = { result: undefined };
1379
+ if (spec.init !== undefined) {
1380
+ try {
1381
+ forEachInitialState(
1382
+ spec.init,
1383
+ environment,
1384
+ (state) => {
1385
+ try {
1386
+ outcome.result = visitInitialState(state);
1387
+ } catch (error) {
1388
+ outcome.result = toFailure(error, [], state);
1389
+ }
1390
+ return outcome.result !== undefined;
1391
+ },
1392
+ spec.scope,
1393
+ );
1394
+ } catch (error) {
1395
+ return toFailure(error, []);
1396
+ }
1397
+ }
1398
+ if (outcome.result) return outcome.result;
1399
+
1400
+ const next = spec.next;
1401
+ if (next === undefined) {
1402
+ if (states.length > 0) {
1403
+ throw new TlaEvaluationError(
1404
+ "No next state actions defined to generate successor states from.",
1405
+ );
1406
+ }
1407
+ return createSuccess();
1408
+ }
1409
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1410
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1411
+ const isNamingEdges = Boolean(
1412
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1413
+ );
1414
+ const forEachActionSuccessor = (
1415
+ state: Value[],
1416
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1417
+ ) => {
1418
+ if (!isNamingEdges) {
1419
+ return forEachSuccessor(
1420
+ next,
1421
+ state,
1422
+ environment,
1423
+ (successor) => onSuccessor(successor, undefined),
1424
+ spec.scope,
1425
+ );
1426
+ }
1427
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1428
+ const progress = { isStopped: false };
1429
+ return nextActions.value.reduce((count, action) => {
1430
+ if (progress.isStopped) return count;
1431
+ return (
1432
+ count +
1433
+ forEachSuccessor(
1434
+ action.expression,
1435
+ state,
1436
+ environment,
1437
+ (successor) => {
1438
+ progress.isStopped = onSuccessor(successor, action);
1439
+ return progress.isStopped;
1440
+ },
1441
+ action.scope,
1442
+ )
1443
+ );
1444
+ }, 0);
1445
+ };
1446
+ const expandState = (index: number) => {
1447
+ const state = states[index];
1448
+ const liveSuccessors: LiveSuccessor[] = [];
1449
+ const source = stateWriter && getGraphState(state, depths[index]);
1450
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1451
+ try {
1452
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1453
+ } catch (error) {
1454
+ outcome.result = toFailure(error, getTrace(index, successor));
671
1455
  }
672
- if (!isNew) continue;
673
- if (!isCanonicalizedFirst) canonicalizeState(successor.state);
674
- markSeen(hash, states.length);
675
- if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
676
- addState(successor.state, fingerprintState, index, successor.action);
677
- runtime.queueSize++;
1456
+ return outcome.result !== undefined;
1457
+ });
1458
+ current.isExpanding = false;
1459
+ if (outcome.result) return outcome.result;
1460
+ if (successorCount === 0 && config.checkDeadlock) {
1461
+ return reportViolation("deadlock", { name: "deadlock", trace: getStateTrace(index) });
678
1462
  }
679
- const accepted = liveness?.addState(index, state, liveSuccessors);
680
- if (accepted) {
681
- return createResult("property-violation", {
682
- name: accepted.name,
683
- trace: getPathTrace(accepted.path),
1463
+ try {
1464
+ const accepted = liveness?.addState(index, state, liveSuccessors);
1465
+ if (!liveness || !accepted) return undefined;
1466
+ const steps = getPathSteps(accepted);
1467
+ const properties = liveness.getViolatedProperties(
1468
+ steps.map((step) => step.state),
1469
+ steps.length - 1,
1470
+ );
1471
+ return reportViolation("property-violation", {
1472
+ name: properties[0],
1473
+ properties,
1474
+ trace: toTrace(steps, accepted),
684
1475
  });
1476
+ } catch (error) {
1477
+ return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1478
+ }
1479
+ };
1480
+ // TLC names the properties and the step back into the cycle from the states it prints.
1481
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1482
+ const path = [...lasso.prefix, ...lasso.cycle];
1483
+ const loopStart = lasso.prefix.length;
1484
+ const steps = getPathSteps(path, loopStart);
1485
+ const trace = toTrace(steps, path, loopStart);
1486
+ const properties = checker.getViolatedProperties(
1487
+ steps.map((step) => step.state),
1488
+ loopStart,
1489
+ );
1490
+ const back = path[loopStart];
1491
+ const last = path[path.length - 1];
1492
+ const lastState = steps[steps.length - 1].state;
1493
+ const loopLabel =
1494
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1495
+ return reportViolation(
1496
+ "liveness-violation",
1497
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1498
+ () =>
1499
+ back === last
1500
+ ? trace[trace.length - 1].action
1501
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1502
+ );
1503
+ };
1504
+ const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
1505
+ const startedAt = performance.now();
1506
+ const periodic = { at: startedAt + PERIODIC_START, size: 1, time: 0 };
1507
+ const findPeriodicViolation = (expanded: number) => {
1508
+ const now = performance.now();
1509
+ periodic.at = now + PROGRESS_INTERVAL;
1510
+ const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1511
+ if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1512
+ periodic.size = expanded;
1513
+ const lasso = liveness?.findViolation();
1514
+ periodic.time += performance.now() - now;
1515
+ return lasso;
1516
+ };
1517
+ for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1518
+ current.index = index;
1519
+ current.candidate = undefined;
1520
+ runtime.queueSize = states.length - index - 1;
1521
+ current.isExpanding = true;
1522
+ try {
1523
+ outcome.result = expandState(index);
1524
+ } catch (error) {
1525
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1526
+ }
1527
+ if (outcome.result) return outcome.result;
1528
+ outDegrees[getOutDegreeBucket()]++;
1529
+ expansion.newStates = 0;
1530
+ if (isPeriodic && performance.now() >= periodic.at) {
1531
+ const lasso = findPeriodicViolation(index + 1);
1532
+ if (liveness && lasso) return reportLasso(liveness, lasso);
685
1533
  }
686
1534
  }
687
1535
 
688
1536
  current.index = -1;
689
1537
  current.candidate = undefined;
690
1538
  const lasso = liveness?.findViolation();
691
- if (lasso) {
692
- return createResult("liveness-violation", {
693
- name: lasso.name,
694
- trace: getPathTrace([...lasso.prefix, ...lasso.cycle]),
695
- loopStart: lasso.prefix.length,
696
- });
697
- }
1539
+ if (liveness && lasso) return reportLasso(liveness, lasso);
698
1540
 
699
- const postconditionViolation = search.findPostconditionViolation(print);
1541
+ const postconditionViolation = search.findPostconditionViolation();
700
1542
  if (postconditionViolation) {
701
- return createResult("postcondition-violation", postconditionViolation);
1543
+ return createResult("postcondition-violation", { ...postconditionViolation, trace: [] });
702
1544
  }
703
- return createResult("success");
1545
+ return createSuccess();
704
1546
  };