tla-ts 0.0.3-dev.a50fc89 → 0.0.3-dev.a85c0bd

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 (49) hide show
  1. package/README.md +22 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +32 -22
  4. package/dist/index.d.ts +32 -22
  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 +18 -17
  11. package/dist/run-cli.js +14 -13
  12. package/dist/transfer.cjs +30 -15
  13. package/dist/transfer.js +30 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +90 -0
  16. package/src/check.ts +314 -80
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +94 -24
  21. package/src/errors.ts +35 -2
  22. package/src/evaluate.ts +126 -148
  23. package/src/exit-codes.ts +39 -42
  24. package/src/fingerprints.ts +46 -11
  25. package/src/instances.ts +15 -14
  26. package/src/levels.ts +8 -8
  27. package/src/lexer.ts +5 -1
  28. package/src/live-check.ts +772 -0
  29. package/src/liveness.ts +116 -543
  30. package/src/parallel-worker.ts +168 -212
  31. package/src/parallel.ts +78 -37
  32. package/src/parser.ts +12 -1
  33. package/src/resolve.ts +16 -15
  34. package/src/run-cli.ts +58 -13
  35. package/src/runtime.ts +3 -1
  36. package/src/spec-description.ts +18 -6
  37. package/src/standard-modules.ts +2 -7
  38. package/src/state-graph.ts +157 -0
  39. package/src/subexpressions.ts +10 -10
  40. package/src/successors.ts +99 -25
  41. package/src/symmetry.ts +30 -8
  42. package/src/tableau.ts +51 -24
  43. package/src/tlc-ext.ts +29 -12
  44. package/src/tlc-module.ts +14 -33
  45. package/src/tlc-modules.ts +4 -0
  46. package/src/tlc-order.ts +25 -7
  47. package/src/tlc-random.ts +9 -6
  48. package/src/tlc-summary.ts +20 -5
  49. package/src/values.ts +128 -24
package/src/check.ts CHANGED
@@ -1,32 +1,44 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
12
+ import {
13
+ getErrorExitCode,
14
+ isStackOverflow,
15
+ STACK_OVERFLOW,
16
+ TlaConfigError,
17
+ TlaEvaluationError,
18
+ TlaIncompleteStateError,
19
+ TlaModuleError,
20
+ UNEXPECTED_EXCEPTION,
21
+ } from "./errors";
22
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
23
  import {
8
24
  describeRange,
9
25
  evaluate,
10
26
  expectBoolean,
11
27
  formatRange,
12
- getChildren,
13
28
  getDefinition,
14
29
  isConstantLevel,
15
30
  isImpure,
16
- isLocallyResolved,
17
31
  type Context,
18
32
  type Environment,
19
33
  type Scope,
20
34
  } from "./evaluate";
21
35
  import {
22
36
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
37
  type Lasso,
38
+ type LivenessChecker,
26
39
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
40
+ } from "./live-check";
41
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
42
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
43
  import { prettyPrint } from "./pretty-print";
32
44
  import {
@@ -38,12 +50,19 @@ import {
38
50
  } from "./successors";
39
51
  import {
40
52
  getActionLabel,
53
+ getActionSignature,
41
54
  getNextActions,
42
55
  getSpecificationValue,
43
56
  type SpecAction,
44
57
  } from "./spec-description";
58
+ import {
59
+ createStateWriter,
60
+ type GraphState,
61
+ type StateDump,
62
+ type StateWriter,
63
+ } from "./state-graph";
45
64
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
65
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
47
66
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
67
  import { createCanonicalizer } from "./canonical";
49
68
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -51,6 +70,8 @@ import { createCounterExample } from "./tlc-ext";
51
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
52
71
  import {
53
72
  combineHash,
73
+ createModelValue,
74
+ formatState,
54
75
  formatValue,
55
76
  getValueHash,
56
77
  isFunctionValue,
@@ -74,6 +95,8 @@ export interface CheckOptions {
74
95
  workers?: number;
75
96
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
97
  livenessCheck?: "default" | "final";
98
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
99
+ dump?: StateDump;
77
100
  }
78
101
 
79
102
  export type CheckStatus =
@@ -95,6 +118,8 @@ export interface TraceStep {
95
118
 
96
119
  export interface Violation {
97
120
  name: string;
121
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
122
+ properties?: string[];
98
123
  trace: TraceStep[];
99
124
  loopStart: number | undefined;
100
125
  loopLabel?: string;
@@ -226,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
226
251
  try {
227
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
228
253
  } catch (error) {
229
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
230
255
  throw error;
231
256
  }
232
257
  };
@@ -255,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
255
280
  levels.params.size === 0
256
281
  ? ""
257
282
  : "\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.";
258
- throw new TlaConfigError(
259
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ throw setExitCode(
284
+ new TlaConfigError(
285
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
286
+ ),
287
+ EXIT_STATUS.safetyEvaluationFailure,
260
288
  );
261
289
  }
262
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -354,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
354
382
  conjunct.kind === "Always" &&
355
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
384
  ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
385
+ throw setExitCode(
386
+ new TlaConfigError(
387
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
388
+ ),
389
+ EXIT_STATUS.error,
359
390
  );
360
391
  }
361
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -425,12 +456,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
425
456
  config.properties.forEach((name) => {
426
457
  const definition = getConfigPredicate("property", name, environment);
427
458
  if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
459
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
429
460
  const conjunct = item.expression;
430
461
  if (isConstantTrue(item, environment, "property")) return;
431
462
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
463
  properties.actionProperties.push({
433
- name,
464
+ name: item.name,
434
465
  box: conjunct.expression,
435
466
  action: conjunct.expression.action,
436
467
  subscript: conjunct.expression.subscript,
@@ -442,12 +473,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
442
473
  conjunct.kind === "Always" &&
443
474
  getLevel(conjunct.expression, item.scope, environment) <= 1
444
475
  ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
476
+ // TLC names the invariant []P after P when P is an operator name.
477
+ const expression = conjunct.expression;
478
+ properties.invariants.push({
479
+ name: expression.kind === "Identifier" ? expression.name : item.name,
480
+ expression,
481
+ scope: item.scope,
482
+ });
446
483
  return;
447
484
  }
448
485
  const level = getLevel(conjunct, item.scope, environment);
449
486
  if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
487
+ properties.initialPredicates.push({
488
+ name: item.name,
489
+ expression: conjunct,
490
+ scope: item.scope,
491
+ });
451
492
  return;
452
493
  }
453
494
  if (level === ACTION_LEVEL) {
@@ -507,7 +548,9 @@ const getMembership = (
507
548
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
549
  named.flatMap((item) =>
509
550
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
551
+ // A LET or an argument in the scope can read variables the expression doesn't name.
552
+ const variables =
553
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
554
  return {
512
555
  name: item.name,
513
556
  expression,
@@ -754,11 +797,13 @@ export const createSearch = (
754
797
  if (view !== undefined || isFingerprintedLikeTlc) {
755
798
  return BigInt64Array.from(states, getTlcStateFingerprint);
756
799
  }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
800
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
801
+ const fingerprint = createTlcFingerprinter(
802
+ getTlcOrder(),
803
+ new Int32Array(fingerprints.buffer),
761
804
  );
805
+ fingerprintStates.forEach(fingerprint);
806
+ return fingerprints;
762
807
  },
763
808
  getFingerprintState: (state) => {
764
809
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -820,7 +865,10 @@ export const createSearch = (
820
865
  )
821
866
  );
822
867
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
868
+ throw withHeadline(
869
+ withNextStateExitCode(error),
870
+ `Evaluating action property ${property.name} failed.`,
871
+ );
824
872
  }
825
873
  }),
826
874
  satisfiesActionConstraints: (state, next) =>
@@ -828,8 +876,7 @@ export const createSearch = (
828
876
  holdsLikeTlc(
829
877
  constraint.expression,
830
878
  getContext(environment, state, next),
831
- (expression) =>
832
- `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ${getExpectedBoolean(expression, environment)}`,
879
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
880
  ),
834
881
  ),
835
882
  trackStatePossible:
@@ -857,6 +904,23 @@ export const createSearch = (
857
904
  };
858
905
  };
859
906
 
907
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
908
+ // computation of next states. In every other phase, the phase decides the code.
909
+ const withNextStateExitCode = (error: unknown) =>
910
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
911
+
912
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
913
+ // module raised it as an EvalException.
914
+ const toNextStateError = (error: unknown) =>
915
+ error instanceof TlaEvaluationError &&
916
+ !(error instanceof TlaModuleError) &&
917
+ !(error instanceof TlaIncompleteStateError)
918
+ ? setExitCode(
919
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
920
+ getErrorExitCode(error),
921
+ )
922
+ : withNextStateExitCode(error);
923
+
860
924
  const withHeadline = (error: unknown, headline: string) =>
861
925
  error instanceof TlaEvaluationError
862
926
  ? setExitCode(
@@ -865,8 +929,22 @@ const withHeadline = (error: unknown, headline: string) =>
865
929
  )
866
930
  : error;
867
931
 
932
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
933
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
934
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
935
+ try {
936
+ return searchStates(options, stateWriter);
937
+ } catch (error) {
938
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
939
+ throw isStackOverflow(error)
940
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
941
+ : error;
942
+ } finally {
943
+ stateWriter?.close();
944
+ }
945
+ };
946
+
947
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
870
948
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
949
  const onPrint = options.onPrint ?? console.log;
872
950
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -936,7 +1014,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
936
1014
  });
937
1015
 
938
1016
  const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
1017
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
940
1018
  );
941
1019
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
1020
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -962,8 +1040,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
962
1040
  const getFingerprintState = search.getFingerprintState;
963
1041
  const nextActions = { value: undefined as SpecAction[] | undefined };
964
1042
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1043
+ const tlcFingerprints: number[] = [];
965
1044
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1045
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1046
+ getFingerprint: (index) =>
1047
+ (tlcFingerprints[index] ??= Number(
1048
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1049
+ )),
1050
+ getSuccessors: (state) => {
1051
+ const successors: LiveSuccessor[] = [];
1052
+ if (spec.next === undefined) return successors;
1053
+ forEachSuccessor(
1054
+ spec.next,
1055
+ state,
1056
+ environment,
1057
+ (successor) => {
1058
+ canonicalizeState(successor.state);
1059
+ const isInModel =
1060
+ search.satisfiesConstraints(successor.state, state) &&
1061
+ search.satisfiesActionConstraints(state, successor.state);
1062
+ if (!isInModel) return false;
1063
+ const fingerprintState = getFingerprintState(successor.state);
1064
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1065
+ successors.push({ index, state: successor.state });
1066
+ return false;
1067
+ },
1068
+ spec.scope,
1069
+ );
1070
+ return successors;
1071
+ },
1072
+ }),
967
1073
  );
968
1074
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1075
 
@@ -972,7 +1078,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
1078
  const parents: number[] = [];
973
1079
  const actions: (string | undefined)[] = [];
974
1080
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
1081
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1082
+ // and its index plus one side by side, probed by the hash.
1083
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
1084
  const canonicalizeState = createCanonicalizer();
977
1085
 
978
1086
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +1093,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1093
  position: number,
986
1094
  loopStart: number | undefined,
987
1095
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1096
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1097
  runtime.getLevel = () => position + 1;
992
1098
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1099
+ return evaluateAlias(
1100
+ alias,
1101
+ steps[position].state,
1102
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1103
+ );
1104
+ };
1105
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1106
  try {
994
1107
  const body = getConfigDefinition("alias", alias, environment).body;
995
1108
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1091,7 +1204,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1091
1204
  trace: TraceStep[],
1092
1205
  initialState?: Value[],
1093
1206
  failureOutDegrees?: number[],
1094
- ) => {
1207
+ ): CheckResult => {
1208
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1209
+ // behavior up to the state it was expanding.
1210
+ if (isStackOverflow(error)) {
1211
+ return current.isExpanding
1212
+ ? toFailure(
1213
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1214
+ getStateTrace(current.index),
1215
+ )
1216
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1217
+ }
1095
1218
  if (!(error instanceof TlaEvaluationError)) throw error;
1096
1219
  return {
1097
1220
  ...createResult("error", undefined, {
@@ -1104,7 +1227,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1227
  outDegrees: failureOutDegrees,
1105
1228
  };
1106
1229
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1230
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1231
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1232
  const last = steps[steps.length - 1].state;
1110
1233
  const isClosed =
@@ -1113,7 +1236,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1236
  loopStart === path.length - 1 ||
1114
1237
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1238
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1239
+ return steps;
1117
1240
  };
1118
1241
  const getStateHash = (state: Value[]) => {
1119
1242
  let hash = 0x811c9dc5;
@@ -1127,19 +1250,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1127
1250
  }
1128
1251
  return true;
1129
1252
  };
1253
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1130
1254
  const findStateIndex = (hash: number, state: Value[]) => {
1131
- const bucket = buckets.get(hash);
1132
- if (bucket === undefined) return -1;
1133
- if (typeof bucket === "number") {
1134
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1255
+ const mask = seen.slots.length - 1;
1256
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1257
+ const entry = seen.slots[slot + 1];
1258
+ if (entry === 0) return -1;
1259
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1260
+ return entry - 1;
1261
+ }
1135
1262
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1263
+ };
1264
+ const insertSeen = (hash: number, entry: number) => {
1265
+ const mask = seen.slots.length - 1;
1266
+ let slot = getSlot(hash);
1267
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1268
+ seen.slots[slot] = hash;
1269
+ seen.slots[slot + 1] = entry;
1137
1270
  };
1138
1271
  const markSeen = (hash: number, index: number) => {
1139
- const bucket = buckets.get(hash);
1140
- if (bucket === undefined) buckets.set(hash, index);
1141
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1142
- else bucket.push(index);
1272
+ seen.size++;
1273
+ if (seen.size * 4 > seen.slots.length) {
1274
+ const slots = seen.slots;
1275
+ seen.slots = new Int32Array(slots.length * 2);
1276
+ seen.shift--;
1277
+ for (let slot = 0; slot < slots.length; slot += 2) {
1278
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1279
+ }
1280
+ }
1281
+ insertSeen(hash, index + 1);
1143
1282
  };
1144
1283
  const countDistinctState = (depth: number) => {
1145
1284
  runtime.distinctStates = states.length + 1;
@@ -1179,7 +1318,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1318
  };
1180
1319
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1320
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1321
+ current.livenessSource = index ?? -1;
1183
1322
  };
1184
1323
  runtime.getLevel = (state) => {
1185
1324
  const source = current.livenessSource;
@@ -1190,6 +1329,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1329
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1330
  };
1192
1331
 
1332
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1333
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1334
+ level,
1335
+ getLabel: () =>
1336
+ formatState(
1337
+ config.alias === undefined
1338
+ ? toRecord(state)
1339
+ : evaluateAlias(config.alias, state, undefined),
1340
+ ),
1341
+ getText: () => formatState(toRecord(state)),
1342
+ });
1343
+
1193
1344
  const visitInitialState = (state: Value[]) => {
1194
1345
  canonicalizeState(state);
1195
1346
  runtime.generatedStates++;
@@ -1206,6 +1357,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1206
1357
  countDistinctState(1);
1207
1358
  runtime.queueSize++;
1208
1359
  liveness?.addInitialState(states.length, state);
1360
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1361
  }
1210
1362
  const violated = search.findViolatedInvariant(state);
1211
1363
  if (violated) {
@@ -1226,7 +1378,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1378
  addState(state, fingerprintState, -1, undefined);
1227
1379
  return undefined;
1228
1380
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1381
+ const visitSuccessor = (
1382
+ index: number,
1383
+ successor: Successor,
1384
+ liveSuccessors: LiveSuccessor[],
1385
+ source: GraphState | undefined,
1386
+ action: SpecAction | undefined,
1387
+ ) => {
1230
1388
  const state = states[index];
1231
1389
  runtime.generatedStates++;
1232
1390
  current.candidate = successor.state;
@@ -1240,6 +1398,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1240
1398
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
1399
  if (isInModel) search.trackActionPossible(state, successor.state);
1242
1400
  const existing = isInModel ? found : -1;
1401
+ if (source && isInModel) {
1402
+ stateWriter?.writeSuccessor(
1403
+ source,
1404
+ getGraphState(successor.state, depths[index] + 1),
1405
+ existing !== -1,
1406
+ action && { name: action.name, signature: getActionSignature(action) },
1407
+ );
1408
+ }
1243
1409
  if (existing !== -1 && liveness) {
1244
1410
  const stored = states[existing];
1245
1411
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1311,23 +1477,55 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1477
  }
1312
1478
  return createSuccess();
1313
1479
  }
1480
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1481
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1482
+ const isNamingEdges = Boolean(
1483
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1484
+ );
1485
+ const forEachActionSuccessor = (
1486
+ state: Value[],
1487
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1488
+ ) => {
1489
+ if (!isNamingEdges) {
1490
+ return forEachSuccessor(
1491
+ next,
1492
+ state,
1493
+ environment,
1494
+ (successor) => onSuccessor(successor, undefined),
1495
+ spec.scope,
1496
+ );
1497
+ }
1498
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1499
+ const progress = { isStopped: false };
1500
+ return nextActions.value.reduce((count, action) => {
1501
+ if (progress.isStopped) return count;
1502
+ return (
1503
+ count +
1504
+ forEachSuccessor(
1505
+ action.expression,
1506
+ state,
1507
+ environment,
1508
+ (successor) => {
1509
+ progress.isStopped = onSuccessor(successor, action);
1510
+ return progress.isStopped;
1511
+ },
1512
+ action.scope,
1513
+ )
1514
+ );
1515
+ }, 0);
1516
+ };
1314
1517
  const expandState = (index: number) => {
1315
1518
  const state = states[index];
1316
1519
  const liveSuccessors: LiveSuccessor[] = [];
1317
- const successorCount = forEachSuccessor(
1318
- next,
1319
- state,
1320
- environment,
1321
- (successor) => {
1322
- try {
1323
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1324
- } catch (error) {
1325
- outcome.result = toFailure(error, getTrace(index, successor));
1326
- }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
1520
+ const source = stateWriter && getGraphState(state, depths[index]);
1521
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1522
+ try {
1523
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1524
+ } catch (error) {
1525
+ outcome.result = toFailure(error, getTrace(index, successor));
1526
+ }
1527
+ return outcome.result !== undefined;
1528
+ });
1331
1529
  current.isExpanding = false;
1332
1530
  if (outcome.result) return outcome.result;
1333
1531
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1335,32 +1533,68 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1533
  }
1336
1534
  try {
1337
1535
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1536
+ if (!liveness || !accepted) return undefined;
1537
+ const steps = getPathSteps(accepted);
1538
+ const properties = liveness.getViolatedProperties(
1539
+ steps.map((step) => step.state),
1540
+ steps.length - 1,
1541
+ );
1340
1542
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1543
+ name: properties[0],
1544
+ properties,
1545
+ trace: toTrace(steps, accepted),
1343
1546
  });
1344
1547
  } catch (error) {
1345
1548
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1549
  }
1347
1550
  };
1348
- const reportLasso = (lasso: Lasso) => {
1551
+ // TLC names the action when the next-state relation has more than one, and prints the
1552
+ // incomplete successor with null for each variable it leaves undefined.
1553
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1554
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1555
+ const actions = nextActions.value;
1556
+ const action =
1557
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1558
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1559
+ runtime.generatedStates++;
1560
+ return toFailure(
1561
+ actions.length === 1
1562
+ ? error
1563
+ : new TlaEvaluationError(
1564
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1565
+ ),
1566
+ [
1567
+ ...getStateTrace(index),
1568
+ {
1569
+ action: error.action,
1570
+ label: action && getActionLabel(action),
1571
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1572
+ },
1573
+ ],
1574
+ );
1575
+ };
1576
+ // TLC names the properties and the step back into the cycle from the states it prints.
1577
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1578
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1579
+ const loopStart = lasso.prefix.length;
1580
+ const steps = getPathSteps(path, loopStart);
1581
+ const trace = toTrace(steps, path, loopStart);
1582
+ const properties = checker.getViolatedProperties(
1583
+ steps.map((step) => step.state),
1584
+ loopStart,
1585
+ );
1586
+ const back = path[loopStart];
1352
1587
  const last = path[path.length - 1];
1588
+ const lastState = steps[steps.length - 1].state;
1353
1589
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1590
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1591
  return reportViolation(
1356
1592
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1593
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1594
  () =>
1359
1595
  back === last
1360
1596
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1597
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1598
  );
1365
1599
  };
1366
1600
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1607,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1607
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1608
  periodic.size = expanded;
1375
1609
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1610
  periodic.time += performance.now() - now;
1378
1611
  return lasso;
1379
1612
  };
1380
- setNextStatePhase(true);
1381
1613
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1614
  current.index = index;
1383
1615
  current.candidate = undefined;
@@ -1386,22 +1618,24 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1618
  try {
1387
1619
  outcome.result = expandState(index);
1388
1620
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1621
+ outcome.result =
1622
+ error instanceof TlaIncompleteStateError
1623
+ ? reportIncompleteSuccessor(error, index)
1624
+ : toFailure(toNextStateError(error), getStateTrace(index));
1390
1625
  }
1391
1626
  if (outcome.result) return outcome.result;
1392
1627
  outDegrees[getOutDegreeBucket()]++;
1393
1628
  expansion.newStates = 0;
1394
1629
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1630
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1631
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1632
  }
1398
1633
  }
1399
1634
 
1400
1635
  current.index = -1;
1401
1636
  current.candidate = undefined;
1402
1637
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1638
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1639
 
1406
1640
  const postconditionViolation = search.findPostconditionViolation();
1407
1641
  if (postconditionViolation) {