tla-ts 0.0.3-dev.2032e26 → 0.0.3-dev.27a0c3a

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 (47) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +31 -22
  4. package/dist/index.d.ts +31 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  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 +17 -16
  11. package/dist/run-cli.js +6 -5
  12. package/dist/transfer.cjs +29 -15
  13. package/dist/transfer.js +29 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +90 -0
  16. package/src/check.ts +329 -89
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +94 -24
  22. package/src/errors.ts +30 -2
  23. package/src/evaluate.ts +123 -147
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +15 -14
  26. package/src/levels.ts +8 -8
  27. package/src/live-check.ts +772 -0
  28. package/src/liveness.ts +116 -543
  29. package/src/parallel-worker.ts +2 -2
  30. package/src/parallel.ts +5 -2
  31. package/src/resolve.ts +16 -15
  32. package/src/run-cli.ts +58 -13
  33. package/src/runtime.ts +3 -1
  34. package/src/spec-description.ts +18 -6
  35. package/src/standard-modules.ts +2 -7
  36. package/src/state-graph.ts +157 -0
  37. package/src/subexpressions.ts +10 -10
  38. package/src/successors.ts +96 -25
  39. package/src/symmetry.ts +16 -6
  40. package/src/tableau.ts +51 -24
  41. package/src/tlc-ext.ts +29 -12
  42. package/src/tlc-module.ts +14 -33
  43. package/src/tlc-modules.ts +4 -0
  44. package/src/tlc-order.ts +8 -4
  45. package/src/tlc-random.ts +9 -6
  46. package/src/tlc-summary.ts +20 -5
  47. package/src/values.ts +121 -20
package/src/check.ts CHANGED
@@ -1,38 +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
12
  import {
6
13
  getErrorExitCode,
14
+ isStackOverflow,
15
+ STACK_OVERFLOW,
7
16
  TlaConfigError,
8
17
  TlaEvaluationError,
18
+ TlaIncompleteStateError,
9
19
  TlaModuleError,
10
20
  UNEXPECTED_EXCEPTION,
11
21
  } from "./errors";
12
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
22
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
13
23
  import {
14
24
  describeRange,
15
25
  evaluate,
16
26
  expectBoolean,
17
27
  formatRange,
18
- getChildren,
19
28
  getDefinition,
20
29
  isConstantLevel,
21
30
  isImpure,
22
- isLocallyResolved,
23
31
  type Context,
24
32
  type Environment,
25
33
  type Scope,
26
34
  } from "./evaluate";
27
35
  import {
28
36
  createLivenessChecker,
29
- expandTemporal,
30
- getLevel,
31
37
  type Lasso,
38
+ type LivenessChecker,
32
39
  type LiveSuccessor,
33
- type ScopedExpression,
34
- type TemporalProperty,
35
- } from "./liveness";
40
+ } from "./live-check";
41
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
36
42
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
37
43
  import { prettyPrint } from "./pretty-print";
38
44
  import {
@@ -44,12 +50,19 @@ import {
44
50
  } from "./successors";
45
51
  import {
46
52
  getActionLabel,
53
+ getActionSignature,
47
54
  getNextActions,
48
55
  getSpecificationValue,
49
56
  type SpecAction,
50
57
  } from "./spec-description";
58
+ import {
59
+ createStateWriter,
60
+ type GraphState,
61
+ type StateDump,
62
+ type StateWriter,
63
+ } from "./state-graph";
51
64
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
52
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
65
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
53
66
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
54
67
  import { createCanonicalizer } from "./canonical";
55
68
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -57,6 +70,8 @@ import { createCounterExample } from "./tlc-ext";
57
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
58
71
  import {
59
72
  combineHash,
73
+ createModelValue,
74
+ formatState,
60
75
  formatValue,
61
76
  getValueHash,
62
77
  isFunctionValue,
@@ -80,6 +95,8 @@ export interface CheckOptions {
80
95
  workers?: number;
81
96
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
82
97
  livenessCheck?: "default" | "final";
98
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
99
+ dump?: StateDump;
83
100
  }
84
101
 
85
102
  export type CheckStatus =
@@ -101,6 +118,8 @@ export interface TraceStep {
101
118
 
102
119
  export interface Violation {
103
120
  name: string;
121
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
122
+ properties?: string[];
104
123
  trace: TraceStep[];
105
124
  loopStart: number | undefined;
106
125
  loopLabel?: string;
@@ -232,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
232
251
  try {
233
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
234
253
  } catch (error) {
235
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
236
255
  throw error;
237
256
  }
238
257
  };
@@ -261,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
261
280
  levels.params.size === 0
262
281
  ? ""
263
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.";
264
- throw new TlaConfigError(
265
- `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,
266
288
  );
267
289
  }
268
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -360,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
360
382
  conjunct.kind === "Always" &&
361
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
362
384
  ) {
363
- throw new TlaConfigError(
364
- `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,
365
390
  );
366
391
  }
367
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -431,12 +456,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
431
456
  config.properties.forEach((name) => {
432
457
  const definition = getConfigPredicate("property", name, environment);
433
458
  if (!definition) return;
434
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
459
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
435
460
  const conjunct = item.expression;
436
461
  if (isConstantTrue(item, environment, "property")) return;
437
462
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
438
463
  properties.actionProperties.push({
439
- name,
464
+ name: item.name,
440
465
  box: conjunct.expression,
441
466
  action: conjunct.expression.action,
442
467
  subscript: conjunct.expression.subscript,
@@ -448,12 +473,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
448
473
  conjunct.kind === "Always" &&
449
474
  getLevel(conjunct.expression, item.scope, environment) <= 1
450
475
  ) {
451
- 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
+ });
452
483
  return;
453
484
  }
454
485
  const level = getLevel(conjunct, item.scope, environment);
455
486
  if (level < ACTION_LEVEL) {
456
- 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
+ });
457
492
  return;
458
493
  }
459
494
  if (level === ACTION_LEVEL) {
@@ -513,7 +548,9 @@ const getMembership = (
513
548
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
514
549
  named.flatMap((item) =>
515
550
  getConjuncts(item.expression, environment).map((expression) => {
516
- 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;
517
554
  return {
518
555
  name: item.name,
519
556
  expression,
@@ -760,11 +797,13 @@ export const createSearch = (
760
797
  if (view !== undefined || isFingerprintedLikeTlc) {
761
798
  return BigInt64Array.from(states, getTlcStateFingerprint);
762
799
  }
763
- const indices = getTlcOrder();
764
- const getFingerprint = createTlcFingerprinter();
765
- return BigInt64Array.from(fingerprintStates, (state) =>
766
- getFingerprint(indices.map((index) => state[index])),
800
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
801
+ const fingerprint = createTlcFingerprinter(
802
+ getTlcOrder(),
803
+ new Int32Array(fingerprints.buffer),
767
804
  );
805
+ fingerprintStates.forEach(fingerprint);
806
+ return fingerprints;
768
807
  },
769
808
  getFingerprintState: (state) => {
770
809
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -796,11 +835,17 @@ export const createSearch = (
796
835
  }
797
836
  }),
798
837
  satisfiesConstraints: (state, parent) =>
799
- constraints.every(
800
- (constraint) =>
801
- isUnchangedFor(constraint, state, parent) ||
802
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
803
- ),
838
+ constraints.every((constraint) => {
839
+ try {
840
+ return (
841
+ isUnchangedFor(constraint, state, parent) ||
842
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
843
+ );
844
+ } catch (error) {
845
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
846
+ throw parent ? toNextStateError(error) : error;
847
+ }
848
+ }),
804
849
  findFailedInitialPredicate: (state) =>
805
850
  properties.initialPredicates.find(
806
851
  (predicate) =>
@@ -826,17 +871,20 @@ export const createSearch = (
826
871
  )
827
872
  );
828
873
  } catch (error) {
829
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
874
+ throw withHeadline(
875
+ withNextStateExitCode(error),
876
+ `Evaluating action property ${property.name} failed.`,
877
+ );
830
878
  }
831
879
  }),
832
880
  satisfiesActionConstraints: (state, next) =>
833
- actionConstraints.every((constraint) =>
834
- holdsLikeTlc(
835
- constraint.expression,
836
- getContext(environment, state, next),
837
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
838
- ),
839
- ),
881
+ actionConstraints.every((constraint) => {
882
+ try {
883
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
884
+ } catch (error) {
885
+ throw toNextStateError(error);
886
+ }
887
+ }),
840
888
  trackStatePossible:
841
889
  statePossible.length === 0
842
890
  ? ignorePossible
@@ -862,6 +910,23 @@ export const createSearch = (
862
910
  };
863
911
  };
864
912
 
913
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
914
+ // computation of next states. In every other phase, the phase decides the code.
915
+ const withNextStateExitCode = (error: unknown) =>
916
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
917
+
918
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
919
+ // module raised it as an EvalException.
920
+ const toNextStateError = (error: unknown) =>
921
+ error instanceof TlaEvaluationError &&
922
+ !(error instanceof TlaModuleError) &&
923
+ !(error instanceof TlaIncompleteStateError)
924
+ ? setExitCode(
925
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
926
+ getErrorExitCode(error),
927
+ )
928
+ : withNextStateExitCode(error);
929
+
865
930
  const withHeadline = (error: unknown, headline: string) =>
866
931
  error instanceof TlaEvaluationError
867
932
  ? setExitCode(
@@ -870,8 +935,22 @@ const withHeadline = (error: unknown, headline: string) =>
870
935
  )
871
936
  : error;
872
937
 
938
+ // TLC finishes the -dump file whether or not the search finds a violation.
873
939
  export const checkSequentially = (options: CheckOptions): CheckResult => {
874
- setNextStatePhase(false);
940
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
941
+ try {
942
+ return searchStates(options, stateWriter);
943
+ } catch (error) {
944
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
945
+ throw isStackOverflow(error)
946
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
947
+ : error;
948
+ } finally {
949
+ stateWriter?.close();
950
+ }
951
+ };
952
+
953
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
875
954
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
876
955
  const onPrint = options.onPrint ?? console.log;
877
956
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -941,7 +1020,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
941
1020
  });
942
1021
 
943
1022
  const search = createSearch(config, environment, () =>
944
- getTlcVariableOrder(options.source, options.loadModule),
1023
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
945
1024
  );
946
1025
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
947
1026
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -967,8 +1046,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
967
1046
  const getFingerprintState = search.getFingerprintState;
968
1047
  const nextActions = { value: undefined as SpecAction[] | undefined };
969
1048
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1049
+ const tlcFingerprints: number[] = [];
970
1050
  const liveness = withLivenessExitCode(() =>
971
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1051
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1052
+ getFingerprint: (index) =>
1053
+ (tlcFingerprints[index] ??= Number(
1054
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1055
+ )),
1056
+ getSuccessors: (state) => {
1057
+ const successors: LiveSuccessor[] = [];
1058
+ if (spec.next === undefined) return successors;
1059
+ forEachSuccessor(
1060
+ spec.next,
1061
+ state,
1062
+ environment,
1063
+ (successor) => {
1064
+ canonicalizeState(successor.state);
1065
+ const isInModel =
1066
+ search.satisfiesConstraints(successor.state, state) &&
1067
+ search.satisfiesActionConstraints(state, successor.state);
1068
+ if (!isInModel) return false;
1069
+ const fingerprintState = getFingerprintState(successor.state);
1070
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1071
+ successors.push({ index, state: successor.state });
1072
+ return false;
1073
+ },
1074
+ spec.scope,
1075
+ );
1076
+ return successors;
1077
+ },
1078
+ }),
972
1079
  );
973
1080
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
974
1081
 
@@ -977,7 +1084,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
977
1084
  const parents: number[] = [];
978
1085
  const actions: (string | undefined)[] = [];
979
1086
  const depths: number[] = [];
980
- const buckets = new Map<number, number | number[]>();
1087
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1088
+ // and its index plus one side by side, probed by the hash.
1089
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
981
1090
  const canonicalizeState = createCanonicalizer();
982
1091
 
983
1092
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -990,11 +1099,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
990
1099
  position: number,
991
1100
  loopStart: number | undefined,
992
1101
  ) => {
993
- const state = steps[position].state;
994
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
995
1102
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
996
1103
  runtime.getLevel = () => position + 1;
997
1104
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1105
+ return evaluateAlias(
1106
+ alias,
1107
+ steps[position].state,
1108
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1109
+ );
1110
+ };
1111
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
998
1112
  try {
999
1113
  const body = getConfigDefinition("alias", alias, environment).body;
1000
1114
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1096,7 +1210,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1096
1210
  trace: TraceStep[],
1097
1211
  initialState?: Value[],
1098
1212
  failureOutDegrees?: number[],
1099
- ) => {
1213
+ ): CheckResult => {
1214
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1215
+ // behavior up to the state it was expanding.
1216
+ if (isStackOverflow(error)) {
1217
+ return current.isExpanding
1218
+ ? toFailure(
1219
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1220
+ getStateTrace(current.index),
1221
+ )
1222
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1223
+ }
1100
1224
  if (!(error instanceof TlaEvaluationError)) throw error;
1101
1225
  return {
1102
1226
  ...createResult("error", undefined, {
@@ -1109,7 +1233,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1109
1233
  outDegrees: failureOutDegrees,
1110
1234
  };
1111
1235
  };
1112
- const getPathTrace = (path: number[], loopStart?: number) => {
1236
+ const getPathSteps = (path: number[], loopStart?: number) => {
1113
1237
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1114
1238
  const last = steps[steps.length - 1].state;
1115
1239
  const isClosed =
@@ -1118,7 +1242,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1118
1242
  loopStart === path.length - 1 ||
1119
1243
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1120
1244
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1121
- return toTrace(steps, path, loopStart);
1245
+ return steps;
1122
1246
  };
1123
1247
  const getStateHash = (state: Value[]) => {
1124
1248
  let hash = 0x811c9dc5;
@@ -1132,19 +1256,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1132
1256
  }
1133
1257
  return true;
1134
1258
  };
1259
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1135
1260
  const findStateIndex = (hash: number, state: Value[]) => {
1136
- const bucket = buckets.get(hash);
1137
- if (bucket === undefined) return -1;
1138
- if (typeof bucket === "number") {
1139
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1261
+ const mask = seen.slots.length - 1;
1262
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1263
+ const entry = seen.slots[slot + 1];
1264
+ if (entry === 0) return -1;
1265
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1266
+ return entry - 1;
1267
+ }
1140
1268
  }
1141
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1269
+ };
1270
+ const insertSeen = (hash: number, entry: number) => {
1271
+ const mask = seen.slots.length - 1;
1272
+ let slot = getSlot(hash);
1273
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1274
+ seen.slots[slot] = hash;
1275
+ seen.slots[slot + 1] = entry;
1142
1276
  };
1143
1277
  const markSeen = (hash: number, index: number) => {
1144
- const bucket = buckets.get(hash);
1145
- if (bucket === undefined) buckets.set(hash, index);
1146
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1147
- else bucket.push(index);
1278
+ seen.size++;
1279
+ if (seen.size * 4 > seen.slots.length) {
1280
+ const slots = seen.slots;
1281
+ seen.slots = new Int32Array(slots.length * 2);
1282
+ seen.shift--;
1283
+ for (let slot = 0; slot < slots.length; slot += 2) {
1284
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1285
+ }
1286
+ }
1287
+ insertSeen(hash, index + 1);
1148
1288
  };
1149
1289
  const countDistinctState = (depth: number) => {
1150
1290
  runtime.distinctStates = states.length + 1;
@@ -1170,6 +1310,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1170
1310
  isExpanding: false,
1171
1311
  candidate: undefined as Value[] | undefined,
1172
1312
  candidateLevel: 0,
1313
+ isFingerprinting: false,
1173
1314
  livenessSource: -1,
1174
1315
  };
1175
1316
  const getPath = (index: number): Value[][] =>
@@ -1184,7 +1325,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1184
1325
  };
1185
1326
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1186
1327
  runtime.setLivenessSource = (index) => {
1187
- current.livenessSource = index;
1328
+ current.livenessSource = index ?? -1;
1188
1329
  };
1189
1330
  runtime.getLevel = (state) => {
1190
1331
  const source = current.livenessSource;
@@ -1195,6 +1336,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1195
1336
  return current.isExpanding ? depths[current.index] + 1 : 0;
1196
1337
  };
1197
1338
 
1339
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1340
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1341
+ level,
1342
+ getLabel: () =>
1343
+ formatState(
1344
+ config.alias === undefined
1345
+ ? toRecord(state)
1346
+ : evaluateAlias(config.alias, state, undefined),
1347
+ ),
1348
+ getText: () => formatState(toRecord(state)),
1349
+ });
1350
+
1198
1351
  const visitInitialState = (state: Value[]) => {
1199
1352
  canonicalizeState(state);
1200
1353
  runtime.generatedStates++;
@@ -1211,6 +1364,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1211
1364
  countDistinctState(1);
1212
1365
  runtime.queueSize++;
1213
1366
  liveness?.addInitialState(states.length, state);
1367
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1214
1368
  }
1215
1369
  const violated = search.findViolatedInvariant(state);
1216
1370
  if (violated) {
@@ -1231,20 +1385,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1231
1385
  addState(state, fingerprintState, -1, undefined);
1232
1386
  return undefined;
1233
1387
  };
1234
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1388
+ const visitSuccessor = (
1389
+ index: number,
1390
+ successor: Successor,
1391
+ liveSuccessors: LiveSuccessor[],
1392
+ source: GraphState | undefined,
1393
+ action: SpecAction | undefined,
1394
+ ) => {
1235
1395
  const state = states[index];
1236
1396
  runtime.generatedStates++;
1237
1397
  current.candidate = successor.state;
1238
1398
  current.candidateLevel = depths[index] + 1;
1239
1399
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1400
+ current.isFingerprinting = true;
1240
1401
  const fingerprintState = getFingerprintState(successor.state);
1241
1402
  const hash = getStateHash(fingerprintState);
1403
+ current.isFingerprinting = false;
1242
1404
  const found = findStateIndex(hash, fingerprintState);
1243
1405
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1244
1406
  if (isStateInModel) search.trackStatePossible(successor.state);
1245
1407
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1246
1408
  if (isInModel) search.trackActionPossible(state, successor.state);
1247
1409
  const existing = isInModel ? found : -1;
1410
+ if (source && isInModel) {
1411
+ stateWriter?.writeSuccessor(
1412
+ source,
1413
+ getGraphState(successor.state, depths[index] + 1),
1414
+ existing !== -1,
1415
+ action && { name: action.name, signature: getActionSignature(action) },
1416
+ );
1417
+ }
1248
1418
  if (existing !== -1 && liveness) {
1249
1419
  const stored = states[existing];
1250
1420
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1316,23 +1486,57 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1316
1486
  }
1317
1487
  return createSuccess();
1318
1488
  }
1489
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1490
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1491
+ const isNamingEdges = Boolean(
1492
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1493
+ );
1494
+ const forEachActionSuccessor = (
1495
+ state: Value[],
1496
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1497
+ ) => {
1498
+ if (!isNamingEdges) {
1499
+ return forEachSuccessor(
1500
+ next,
1501
+ state,
1502
+ environment,
1503
+ (successor) => onSuccessor(successor, undefined),
1504
+ spec.scope,
1505
+ );
1506
+ }
1507
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1508
+ const progress = { isStopped: false };
1509
+ return nextActions.value.reduce((count, action) => {
1510
+ if (progress.isStopped) return count;
1511
+ return (
1512
+ count +
1513
+ forEachSuccessor(
1514
+ action.expression,
1515
+ state,
1516
+ environment,
1517
+ (successor) => {
1518
+ progress.isStopped = onSuccessor(successor, action);
1519
+ return progress.isStopped;
1520
+ },
1521
+ action.scope,
1522
+ )
1523
+ );
1524
+ }, 0);
1525
+ };
1319
1526
  const expandState = (index: number) => {
1320
1527
  const state = states[index];
1321
1528
  const liveSuccessors: LiveSuccessor[] = [];
1322
- const successorCount = forEachSuccessor(
1323
- next,
1324
- state,
1325
- environment,
1326
- (successor) => {
1327
- try {
1328
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1329
- } catch (error) {
1330
- outcome.result = toFailure(error, getTrace(index, successor));
1331
- }
1332
- return outcome.result !== undefined;
1333
- },
1334
- spec.scope,
1335
- );
1529
+ const source = stateWriter && getGraphState(state, depths[index]);
1530
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1531
+ try {
1532
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1533
+ } catch (error) {
1534
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1535
+ if (current.isFingerprinting) throw error;
1536
+ outcome.result = toFailure(error, getTrace(index, successor));
1537
+ }
1538
+ return outcome.result !== undefined;
1539
+ });
1336
1540
  current.isExpanding = false;
1337
1541
  if (outcome.result) return outcome.result;
1338
1542
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1340,32 +1544,68 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1340
1544
  }
1341
1545
  try {
1342
1546
  const accepted = liveness?.addState(index, state, liveSuccessors);
1343
- current.livenessSource = -1;
1344
- if (!accepted) return undefined;
1547
+ if (!liveness || !accepted) return undefined;
1548
+ const steps = getPathSteps(accepted);
1549
+ const properties = liveness.getViolatedProperties(
1550
+ steps.map((step) => step.state),
1551
+ steps.length - 1,
1552
+ );
1345
1553
  return reportViolation("property-violation", {
1346
- name: accepted.name,
1347
- trace: getPathTrace(accepted.path),
1554
+ name: properties[0],
1555
+ properties,
1556
+ trace: toTrace(steps, accepted),
1348
1557
  });
1349
1558
  } catch (error) {
1350
1559
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1351
1560
  }
1352
1561
  };
1353
- const reportLasso = (lasso: Lasso) => {
1562
+ // TLC names the action when the next-state relation has more than one, and prints the
1563
+ // incomplete successor with null for each variable it leaves undefined.
1564
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1565
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1566
+ const actions = nextActions.value;
1567
+ const action =
1568
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1569
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1570
+ runtime.generatedStates++;
1571
+ return toFailure(
1572
+ actions.length === 1
1573
+ ? error
1574
+ : new TlaEvaluationError(
1575
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1576
+ ),
1577
+ [
1578
+ ...getStateTrace(index),
1579
+ {
1580
+ action: error.action,
1581
+ label: action && getActionLabel(action),
1582
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1583
+ },
1584
+ ],
1585
+ );
1586
+ };
1587
+ // TLC names the properties and the step back into the cycle from the states it prints.
1588
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1354
1589
  const path = [...lasso.prefix, ...lasso.cycle];
1355
- const trace = getPathTrace(path, lasso.prefix.length);
1356
- const back = path[lasso.prefix.length];
1590
+ const loopStart = lasso.prefix.length;
1591
+ const steps = getPathSteps(path, loopStart);
1592
+ const trace = toTrace(steps, path, loopStart);
1593
+ const properties = checker.getViolatedProperties(
1594
+ steps.map((step) => step.state),
1595
+ loopStart,
1596
+ );
1597
+ const back = path[loopStart];
1357
1598
  const last = path[path.length - 1];
1599
+ const lastState = steps[steps.length - 1].state;
1358
1600
  const loopLabel =
1359
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1601
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1360
1602
  return reportViolation(
1361
1603
  "liveness-violation",
1362
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1604
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1363
1605
  () =>
1364
1606
  back === last
1365
1607
  ? trace[trace.length - 1].action
1366
- : getTraceSuccessors(states[last]).find((successor) =>
1367
- isSameState(successor.state, states[back]),
1368
- )?.action,
1608
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1369
1609
  );
1370
1610
  };
1371
1611
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1378,11 +1618,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1378
1618
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1379
1619
  periodic.size = expanded;
1380
1620
  const lasso = liveness?.findViolation();
1381
- current.livenessSource = -1;
1382
1621
  periodic.time += performance.now() - now;
1383
1622
  return lasso;
1384
1623
  };
1385
- setNextStatePhase(true);
1386
1624
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1387
1625
  current.index = index;
1388
1626
  current.candidate = undefined;
@@ -1391,22 +1629,24 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1391
1629
  try {
1392
1630
  outcome.result = expandState(index);
1393
1631
  } catch (error) {
1394
- outcome.result = toFailure(error, getStateTrace(index));
1632
+ outcome.result =
1633
+ error instanceof TlaIncompleteStateError
1634
+ ? reportIncompleteSuccessor(error, index)
1635
+ : toFailure(toNextStateError(error), getStateTrace(index));
1395
1636
  }
1396
1637
  if (outcome.result) return outcome.result;
1397
1638
  outDegrees[getOutDegreeBucket()]++;
1398
1639
  expansion.newStates = 0;
1399
1640
  if (isPeriodic && performance.now() >= periodic.at) {
1400
1641
  const lasso = findPeriodicViolation(index + 1);
1401
- if (lasso) return reportLasso(lasso);
1642
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1402
1643
  }
1403
1644
  }
1404
1645
 
1405
1646
  current.index = -1;
1406
1647
  current.candidate = undefined;
1407
1648
  const lasso = liveness?.findViolation();
1408
- current.livenessSource = -1;
1409
- if (lasso) return reportLasso(lasso);
1649
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1410
1650
 
1411
1651
  const postconditionViolation = search.findPostconditionViolation();
1412
1652
  if (postconditionViolation) {