tla-ts 0.0.3-dev.e946acb → 0.0.3-dev.e9c5857

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 (50) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +53 -22
  4. package/dist/index.d.ts +53 -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 +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +496 -98
  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 +116 -28
  22. package/src/errors.ts +76 -3
  23. package/src/evaluate.ts +251 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/lexer.ts +5 -1
  28. package/src/live-check.ts +772 -0
  29. package/src/liveness.ts +120 -543
  30. package/src/parallel-worker.ts +7 -3
  31. package/src/parallel.ts +20 -4
  32. package/src/parser.ts +33 -11
  33. package/src/resolve.ts +122 -44
  34. package/src/run-cli.ts +99 -19
  35. package/src/runtime.ts +3 -1
  36. package/src/spec-description.ts +19 -8
  37. package/src/standard-modules.ts +10 -9
  38. package/src/state-graph.ts +157 -0
  39. package/src/subexpressions.ts +10 -10
  40. package/src/successors.ts +146 -35
  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/value-sources.ts +29 -0
  50. package/src/values.ts +172 -53
package/src/check.ts CHANGED
@@ -1,32 +1,45 @@
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
+ formatRange,
16
+ STACK_OVERFLOW,
17
+ TlaConfigError,
18
+ TlaEvaluationError,
19
+ TlaIllegalStateError,
20
+ TlaIncompleteStateError,
21
+ TlaModuleError,
22
+ UNEXPECTED_EXCEPTION,
23
+ } from "./errors";
24
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
25
  import {
8
26
  describeRange,
9
27
  evaluate,
10
28
  expectBoolean,
11
- formatRange,
12
- getChildren,
13
29
  getDefinition,
14
30
  isConstantLevel,
15
31
  isImpure,
16
- isLocallyResolved,
17
32
  type Context,
18
33
  type Environment,
19
34
  type Scope,
20
35
  } from "./evaluate";
21
36
  import {
22
37
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
38
  type Lasso,
39
+ type LivenessChecker,
26
40
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
41
+ } from "./live-check";
42
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
43
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
44
  import { prettyPrint } from "./pretty-print";
32
45
  import {
@@ -38,19 +51,29 @@ import {
38
51
  } from "./successors";
39
52
  import {
40
53
  getActionLabel,
54
+ getActionSignature,
41
55
  getNextActions,
42
56
  getSpecificationValue,
43
57
  type SpecAction,
44
58
  } from "./spec-description";
59
+ import {
60
+ createStateWriter,
61
+ type GraphState,
62
+ type StateDump,
63
+ type StateWriter,
64
+ } from "./state-graph";
45
65
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
66
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
47
67
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
68
  import { createCanonicalizer } from "./canonical";
49
69
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
70
  import { createCounterExample } from "./tlc-ext";
71
+ import { getFingerprintTrace, valueSources } from "./value-sources";
51
72
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
52
73
  import {
53
74
  combineHash,
75
+ createModelValue,
76
+ formatState,
54
77
  formatValue,
55
78
  getValueHash,
56
79
  isFunctionValue,
@@ -74,6 +97,8 @@ export interface CheckOptions {
74
97
  workers?: number;
75
98
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
99
  livenessCheck?: "default" | "final";
100
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
101
+ dump?: StateDump;
77
102
  }
78
103
 
79
104
  export type CheckStatus =
@@ -95,6 +120,8 @@ export interface TraceStep {
95
120
 
96
121
  export interface Violation {
97
122
  name: string;
123
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
124
+ properties?: string[];
98
125
  trace: TraceStep[];
99
126
  loopStart: number | undefined;
100
127
  loopLabel?: string;
@@ -115,6 +142,22 @@ export interface EvaluationFailure {
115
142
  trace: TraceStep[];
116
143
  initialState: Record<string, Value> | undefined;
117
144
  exitCode: number;
145
+ replay?: Replay;
146
+ isWithoutStatistics?: boolean;
147
+ }
148
+
149
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
150
+ export interface Replay {
151
+ output: string[];
152
+ callStack: string[] | undefined;
153
+ fingerprint?: Fingerprint;
154
+ }
155
+
156
+ // TLC reports an error from a method of a value that has a source as one it was unable to
157
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
158
+ export interface Fingerprint {
159
+ sources: string[];
160
+ reason: string;
118
161
  }
119
162
 
120
163
  export interface CheckResult {
@@ -226,7 +269,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
226
269
  try {
227
270
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
228
271
  } catch (error) {
229
- if (error instanceof TlaEvaluationError) return undefined;
272
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
230
273
  throw error;
231
274
  }
232
275
  };
@@ -255,8 +298,11 @@ const getInvariants = (names: string[], environment: Environment) => {
255
298
  levels.params.size === 0
256
299
  ? ""
257
300
  : "\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}`,
301
+ throw setExitCode(
302
+ new TlaConfigError(
303
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
304
+ ),
305
+ EXIT_STATUS.safetyEvaluationFailure,
260
306
  );
261
307
  }
262
308
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -354,8 +400,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
354
400
  conjunct.kind === "Always" &&
355
401
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
402
  ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
403
+ throw setExitCode(
404
+ new TlaConfigError(
405
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
406
+ ),
407
+ EXIT_STATUS.error,
359
408
  );
360
409
  }
361
410
  const level = getLevel(conjunct, item.scope, environment);
@@ -425,12 +474,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
425
474
  config.properties.forEach((name) => {
426
475
  const definition = getConfigPredicate("property", name, environment);
427
476
  if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
477
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
429
478
  const conjunct = item.expression;
430
479
  if (isConstantTrue(item, environment, "property")) return;
431
480
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
481
  properties.actionProperties.push({
433
- name,
482
+ name: item.name,
434
483
  box: conjunct.expression,
435
484
  action: conjunct.expression.action,
436
485
  subscript: conjunct.expression.subscript,
@@ -442,12 +491,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
442
491
  conjunct.kind === "Always" &&
443
492
  getLevel(conjunct.expression, item.scope, environment) <= 1
444
493
  ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
494
+ // TLC names the invariant []P after P when P is an operator name.
495
+ const expression = conjunct.expression;
496
+ properties.invariants.push({
497
+ name: expression.kind === "Identifier" ? expression.name : item.name,
498
+ expression,
499
+ scope: item.scope,
500
+ });
446
501
  return;
447
502
  }
448
503
  const level = getLevel(conjunct, item.scope, environment);
449
504
  if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
505
+ properties.initialPredicates.push({
506
+ name: item.name,
507
+ expression: conjunct,
508
+ scope: item.scope,
509
+ });
451
510
  return;
452
511
  }
453
512
  if (level === ACTION_LEVEL) {
@@ -507,7 +566,9 @@ const getMembership = (
507
566
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
567
  named.flatMap((item) =>
509
568
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
569
+ // A LET or an argument in the scope can read variables the expression doesn't name.
570
+ const variables =
571
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
572
  return {
512
573
  name: item.name,
513
574
  expression,
@@ -754,11 +815,13 @@ export const createSearch = (
754
815
  if (view !== undefined || isFingerprintedLikeTlc) {
755
816
  return BigInt64Array.from(states, getTlcStateFingerprint);
756
817
  }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
818
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
819
+ const fingerprint = createTlcFingerprinter(
820
+ getTlcOrder(),
821
+ new Int32Array(fingerprints.buffer),
761
822
  );
823
+ fingerprintStates.forEach(fingerprint);
824
+ return fingerprints;
762
825
  },
763
826
  getFingerprintState: (state) => {
764
827
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -790,11 +853,17 @@ export const createSearch = (
790
853
  }
791
854
  }),
792
855
  satisfiesConstraints: (state, parent) =>
793
- constraints.every(
794
- (constraint) =>
795
- isUnchangedFor(constraint, state, parent) ||
796
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
797
- ),
856
+ constraints.every((constraint) => {
857
+ try {
858
+ return (
859
+ isUnchangedFor(constraint, state, parent) ||
860
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
861
+ );
862
+ } catch (error) {
863
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
864
+ throw parent ? toNextStateError(error) : error;
865
+ }
866
+ }),
798
867
  findFailedInitialPredicate: (state) =>
799
868
  properties.initialPredicates.find(
800
869
  (predicate) =>
@@ -820,18 +889,20 @@ export const createSearch = (
820
889
  )
821
890
  );
822
891
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
892
+ throw withHeadline(
893
+ withNextStateExitCode(error),
894
+ `Evaluating action property ${property.name} failed.`,
895
+ );
824
896
  }
825
897
  }),
826
898
  satisfiesActionConstraints: (state, next) =>
827
- actionConstraints.every((constraint) =>
828
- holdsLikeTlc(
829
- constraint.expression,
830
- 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)}`,
833
- ),
834
- ),
899
+ actionConstraints.every((constraint) => {
900
+ try {
901
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
902
+ } catch (error) {
903
+ throw toNextStateError(error);
904
+ }
905
+ }),
835
906
  trackStatePossible:
836
907
  statePossible.length === 0
837
908
  ? ignorePossible
@@ -857,6 +928,64 @@ export const createSearch = (
857
928
  };
858
929
  };
859
930
 
931
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
932
+ // computation of next states. In every other phase, the phase decides the code.
933
+ const withNextStateExitCode = (error: unknown) =>
934
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
935
+
936
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
937
+ // module raised it as an EvalException.
938
+ const toNextStateError = (error: unknown) =>
939
+ error instanceof TlaEvaluationError &&
940
+ !(error instanceof TlaModuleError) &&
941
+ !(error instanceof TlaIncompleteStateError)
942
+ ? setExitCode(
943
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
944
+ getErrorExitCode(error),
945
+ )
946
+ : withNextStateExitCode(error);
947
+
948
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
949
+ index > 0 && frames[index - 1] === frame;
950
+
951
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
952
+ // first.
953
+ const getSourceTrace = (sources: Expression[]) =>
954
+ sources
955
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
956
+ .filter((source, index, all) => !isRepeated(source, index, all))
957
+ .map((source, index) => `${index}) ${source}`)
958
+ .reverse();
959
+
960
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
961
+ // many times in a row it pushed it.
962
+ const getReplayedCallStack = (
963
+ replay: () => void,
964
+ trace: Expression[],
965
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
966
+ try {
967
+ replay();
968
+ return { callStack: undefined };
969
+ } catch (error) {
970
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
971
+ const callStack = trace
972
+ .flatMap((expression) => {
973
+ const range = expression.location.range;
974
+ return range
975
+ ? [
976
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
977
+ ]
978
+ : [];
979
+ })
980
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
981
+ const sources = getFingerprintTrace(error);
982
+ return {
983
+ callStack,
984
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
985
+ };
986
+ }
987
+ };
988
+
860
989
  const withHeadline = (error: unknown, headline: string) =>
861
990
  error instanceof TlaEvaluationError
862
991
  ? setExitCode(
@@ -865,15 +994,30 @@ const withHeadline = (error: unknown, headline: string) =>
865
994
  )
866
995
  : error;
867
996
 
997
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
998
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
999
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
1000
+ try {
1001
+ return searchStates(options, stateWriter);
1002
+ } catch (error) {
1003
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
1004
+ throw isStackOverflow(error)
1005
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
1006
+ : error;
1007
+ } finally {
1008
+ stateWriter?.close();
1009
+ }
1010
+ };
1011
+
1012
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
870
1013
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
1014
  const onPrint = options.onPrint ?? console.log;
872
1015
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
873
1016
  // before the trace would misplace them, so rebuilding a trace prints nothing.
874
- const output = { isMuted: false };
1017
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
875
1018
  const print = (text: string) => {
876
- if (!output.isMuted) onPrint(text);
1019
+ if (output.replayed) output.replayed.push(text);
1020
+ else if (!output.isMuted) onPrint(text);
877
1021
  };
878
1022
  const withoutOutput = <Result>(rebuild: () => Result) => {
879
1023
  output.isMuted = true;
@@ -935,9 +1079,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
935
1079
  ),
936
1080
  });
937
1081
 
938
- const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
940
- );
1082
+ const getVariableOrder = () =>
1083
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1084
+ const search = createSearch(config, environment, getVariableOrder);
941
1085
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
1086
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
943
1087
  if (!search) return createSuccess();
@@ -961,9 +1105,113 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
961
1105
  const spec = search.spec;
962
1106
  const getFingerprintState = search.getFingerprintState;
963
1107
  const nextActions = { value: undefined as SpecAction[] | undefined };
1108
+ const replayFailure = (
1109
+ result: CheckResult,
1110
+ replay: (tracedSearch: Search, traced: Environment) => void,
1111
+ ): CheckResult => {
1112
+ if (!result.failure) return result;
1113
+ const trace: Expression[] = [];
1114
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1115
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1116
+ if (!tracedSearch) return result;
1117
+ const replayed: string[] = [];
1118
+ output.replayed = replayed;
1119
+ valueSources.current = new WeakMap();
1120
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1121
+ valueSources.current = undefined;
1122
+ output.replayed = undefined;
1123
+ return {
1124
+ ...result,
1125
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack } },
1126
+ };
1127
+ };
1128
+ // TLC fingerprints a state outside CallStackTool, so a failure leaves the stack empty.
1129
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1130
+ try {
1131
+ getStateHash(getFingerprintState(state));
1132
+ } catch (error) {
1133
+ if (traced.trace) traced.trace.length = 0;
1134
+ throw error;
1135
+ }
1136
+ };
1137
+ // TLC checks every initial state again, as when it first generated them.
1138
+ const replayInitialStates = (result: CheckResult) =>
1139
+ replayFailure(result, (tracedSearch, traced) => {
1140
+ if (spec.init === undefined) return;
1141
+ forEachInitialState(
1142
+ spec.init,
1143
+ traced,
1144
+ (state) => {
1145
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1146
+ return (
1147
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1148
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1149
+ );
1150
+ },
1151
+ spec.scope,
1152
+ );
1153
+ });
1154
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1155
+ const rebuildBehavior = (index: number): void => {
1156
+ const parent = parents[index];
1157
+ if (parent === -1) {
1158
+ getSpecInitialStates();
1159
+ return;
1160
+ }
1161
+ rebuildBehavior(parent);
1162
+ getLabel(parent, states[parent], states[index]);
1163
+ };
1164
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1165
+ // only of a successor outside the model, since it has seen the others.
1166
+ const replaySuccessors = (result: CheckResult, index: number) =>
1167
+ replayFailure(result, (tracedSearch, traced) => {
1168
+ rebuildBehavior(index);
1169
+ const state = states[index];
1170
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1171
+ nextActions.value.find((action) =>
1172
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1173
+ const isInModel =
1174
+ tracedSearch.satisfiesConstraints(successor.state) &&
1175
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1176
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1177
+ return (
1178
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1179
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1180
+ );
1181
+ }),
1182
+ );
1183
+ });
964
1184
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1185
+ const tlcFingerprints: number[] = [];
965
1186
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1187
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1188
+ getFingerprint: (index) =>
1189
+ (tlcFingerprints[index] ??= Number(
1190
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1191
+ )),
1192
+ getSuccessors: (state) => {
1193
+ const successors: LiveSuccessor[] = [];
1194
+ if (spec.next === undefined) return successors;
1195
+ forEachSuccessor(
1196
+ spec.next,
1197
+ state,
1198
+ environment,
1199
+ (successor) => {
1200
+ canonicalizeState(successor.state);
1201
+ const isInModel =
1202
+ search.satisfiesConstraints(successor.state, state) &&
1203
+ search.satisfiesActionConstraints(state, successor.state);
1204
+ if (!isInModel) return false;
1205
+ const fingerprintState = getFingerprintState(successor.state);
1206
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1207
+ successors.push({ index, state: successor.state });
1208
+ return false;
1209
+ },
1210
+ spec.scope,
1211
+ );
1212
+ return successors;
1213
+ },
1214
+ }),
967
1215
  );
968
1216
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1217
 
@@ -972,7 +1220,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
1220
  const parents: number[] = [];
973
1221
  const actions: (string | undefined)[] = [];
974
1222
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
1223
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1224
+ // and its index plus one side by side, probed by the hash.
1225
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
1226
  const canonicalizeState = createCanonicalizer();
977
1227
 
978
1228
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +1235,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1235
  position: number,
986
1236
  loopStart: number | undefined,
987
1237
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1238
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1239
  runtime.getLevel = () => position + 1;
992
1240
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1241
+ return evaluateAlias(
1242
+ alias,
1243
+ steps[position].state,
1244
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1245
+ );
1246
+ };
1247
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1248
  try {
994
1249
  const body = getConfigDefinition("alias", alias, environment).body;
995
1250
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1091,7 +1346,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1091
1346
  trace: TraceStep[],
1092
1347
  initialState?: Value[],
1093
1348
  failureOutDegrees?: number[],
1094
- ) => {
1349
+ ): CheckResult => {
1350
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1351
+ // behavior up to the state it was expanding.
1352
+ if (isStackOverflow(error)) {
1353
+ return current.isExpanding
1354
+ ? toFailure(
1355
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1356
+ getStateTrace(current.index),
1357
+ )
1358
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1359
+ }
1095
1360
  if (!(error instanceof TlaEvaluationError)) throw error;
1096
1361
  return {
1097
1362
  ...createResult("error", undefined, {
@@ -1104,7 +1369,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1369
  outDegrees: failureOutDegrees,
1105
1370
  };
1106
1371
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1372
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1373
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1374
  const last = steps[steps.length - 1].state;
1110
1375
  const isClosed =
@@ -1113,7 +1378,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1378
  loopStart === path.length - 1 ||
1114
1379
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1380
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1381
+ return steps;
1117
1382
  };
1118
1383
  const getStateHash = (state: Value[]) => {
1119
1384
  let hash = 0x811c9dc5;
@@ -1127,19 +1392,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1127
1392
  }
1128
1393
  return true;
1129
1394
  };
1395
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1130
1396
  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;
1397
+ const mask = seen.slots.length - 1;
1398
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1399
+ const entry = seen.slots[slot + 1];
1400
+ if (entry === 0) return -1;
1401
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1402
+ return entry - 1;
1403
+ }
1135
1404
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1405
+ };
1406
+ const insertSeen = (hash: number, entry: number) => {
1407
+ const mask = seen.slots.length - 1;
1408
+ let slot = getSlot(hash);
1409
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1410
+ seen.slots[slot] = hash;
1411
+ seen.slots[slot + 1] = entry;
1137
1412
  };
1138
1413
  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);
1414
+ seen.size++;
1415
+ if (seen.size * 4 > seen.slots.length) {
1416
+ const slots = seen.slots;
1417
+ seen.slots = new Int32Array(slots.length * 2);
1418
+ seen.shift--;
1419
+ for (let slot = 0; slot < slots.length; slot += 2) {
1420
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1421
+ }
1422
+ }
1423
+ insertSeen(hash, index + 1);
1143
1424
  };
1144
1425
  const countDistinctState = (depth: number) => {
1145
1426
  runtime.distinctStates = states.length + 1;
@@ -1165,6 +1446,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1165
1446
  isExpanding: false,
1166
1447
  candidate: undefined as Value[] | undefined,
1167
1448
  candidateLevel: 0,
1449
+ isFingerprinting: false,
1168
1450
  livenessSource: -1,
1169
1451
  };
1170
1452
  const getPath = (index: number): Value[][] =>
@@ -1179,7 +1461,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1461
  };
1180
1462
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1463
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1464
+ current.livenessSource = index ?? -1;
1183
1465
  };
1184
1466
  runtime.getLevel = (state) => {
1185
1467
  const source = current.livenessSource;
@@ -1190,6 +1472,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1472
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1473
  };
1192
1474
 
1475
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1476
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1477
+ level,
1478
+ getLabel: () =>
1479
+ formatState(
1480
+ config.alias === undefined
1481
+ ? toRecord(state)
1482
+ : evaluateAlias(config.alias, state, undefined),
1483
+ ),
1484
+ getText: () => formatState(toRecord(state)),
1485
+ });
1486
+
1193
1487
  const visitInitialState = (state: Value[]) => {
1194
1488
  canonicalizeState(state);
1195
1489
  runtime.generatedStates++;
@@ -1206,6 +1500,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1206
1500
  countDistinctState(1);
1207
1501
  runtime.queueSize++;
1208
1502
  liveness?.addInitialState(states.length, state);
1503
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1504
  }
1210
1505
  const violated = search.findViolatedInvariant(state);
1211
1506
  if (violated) {
@@ -1226,20 +1521,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1521
  addState(state, fingerprintState, -1, undefined);
1227
1522
  return undefined;
1228
1523
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1524
+ const visitSuccessor = (
1525
+ index: number,
1526
+ successor: Successor,
1527
+ liveSuccessors: LiveSuccessor[],
1528
+ source: GraphState | undefined,
1529
+ action: SpecAction | undefined,
1530
+ ) => {
1230
1531
  const state = states[index];
1231
1532
  runtime.generatedStates++;
1232
1533
  current.candidate = successor.state;
1233
1534
  current.candidateLevel = depths[index] + 1;
1234
1535
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1536
+ current.isFingerprinting = true;
1235
1537
  const fingerprintState = getFingerprintState(successor.state);
1236
1538
  const hash = getStateHash(fingerprintState);
1539
+ current.isFingerprinting = false;
1237
1540
  const found = findStateIndex(hash, fingerprintState);
1238
1541
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1239
1542
  if (isStateInModel) search.trackStatePossible(successor.state);
1240
1543
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
1544
  if (isInModel) search.trackActionPossible(state, successor.state);
1242
1545
  const existing = isInModel ? found : -1;
1546
+ if (source && isInModel) {
1547
+ stateWriter?.writeSuccessor(
1548
+ source,
1549
+ getGraphState(successor.state, depths[index] + 1),
1550
+ existing !== -1,
1551
+ action && { name: action.name, signature: getActionSignature(action) },
1552
+ );
1553
+ }
1243
1554
  if (existing !== -1 && liveness) {
1244
1555
  const stored = states[existing];
1245
1556
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1297,10 +1608,22 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1297
1608
  spec.scope,
1298
1609
  );
1299
1610
  } catch (error) {
1300
- return toFailure(error, []);
1611
+ if (!(error instanceof TlaIllegalStateError))
1612
+ return replayInitialStates(toFailure(error, []));
1613
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1614
+ // stops before it prints the statistics.
1615
+ const illegal = toFailure(
1616
+ error,
1617
+ [],
1618
+ error.state.map((value) => value ?? createModelValue("null")),
1619
+ );
1620
+ return {
1621
+ ...illegal,
1622
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1623
+ };
1301
1624
  }
1302
1625
  }
1303
- if (outcome.result) return outcome.result;
1626
+ if (outcome.result) return replayInitialStates(outcome.result);
1304
1627
 
1305
1628
  const next = spec.next;
1306
1629
  if (next === undefined) {
@@ -1311,23 +1634,58 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1634
  }
1312
1635
  return createSuccess();
1313
1636
  }
1637
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1638
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1639
+ const isNamingEdges = Boolean(
1640
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1641
+ );
1642
+ const forEachActionSuccessor = (
1643
+ state: Value[],
1644
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1645
+ ) => {
1646
+ if (!isNamingEdges) {
1647
+ return forEachSuccessor(
1648
+ next,
1649
+ state,
1650
+ environment,
1651
+ (successor) => onSuccessor(successor, undefined),
1652
+ spec.scope,
1653
+ );
1654
+ }
1655
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1656
+ const progress = { isStopped: false };
1657
+ return nextActions.value.reduce((count, action) => {
1658
+ if (progress.isStopped) return count;
1659
+ return (
1660
+ count +
1661
+ forEachSuccessor(
1662
+ action.expression,
1663
+ state,
1664
+ environment,
1665
+ (successor) => {
1666
+ progress.isStopped = onSuccessor(successor, action);
1667
+ return progress.isStopped;
1668
+ },
1669
+ action.scope,
1670
+ )
1671
+ );
1672
+ }, 0);
1673
+ };
1314
1674
  const expandState = (index: number) => {
1315
1675
  const state = states[index];
1316
1676
  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
- );
1677
+ const source = stateWriter && getGraphState(state, depths[index]);
1678
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1679
+ try {
1680
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1681
+ } catch (error) {
1682
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1683
+ if (current.isFingerprinting) throw error;
1684
+ const failure = toFailure(error, getTrace(index, successor));
1685
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1686
+ }
1687
+ return outcome.result !== undefined;
1688
+ });
1331
1689
  current.isExpanding = false;
1332
1690
  if (outcome.result) return outcome.result;
1333
1691
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1335,32 +1693,68 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1693
  }
1336
1694
  try {
1337
1695
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1696
+ if (!liveness || !accepted) return undefined;
1697
+ const steps = getPathSteps(accepted);
1698
+ const properties = liveness.getViolatedProperties(
1699
+ steps.map((step) => step.state),
1700
+ steps.length - 1,
1701
+ );
1340
1702
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1703
+ name: properties[0],
1704
+ properties,
1705
+ trace: toTrace(steps, accepted),
1343
1706
  });
1344
1707
  } catch (error) {
1345
1708
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1709
  }
1347
1710
  };
1348
- const reportLasso = (lasso: Lasso) => {
1711
+ // TLC names the action when the next-state relation has more than one, and prints the
1712
+ // incomplete successor with null for each variable it leaves undefined.
1713
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1714
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1715
+ const actions = nextActions.value;
1716
+ const action =
1717
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1718
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1719
+ runtime.generatedStates++;
1720
+ return toFailure(
1721
+ actions.length === 1
1722
+ ? error
1723
+ : new TlaEvaluationError(
1724
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1725
+ ),
1726
+ [
1727
+ ...getStateTrace(index),
1728
+ {
1729
+ action: error.action,
1730
+ label: action && getActionLabel(action),
1731
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1732
+ },
1733
+ ],
1734
+ );
1735
+ };
1736
+ // TLC names the properties and the step back into the cycle from the states it prints.
1737
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1738
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1739
+ const loopStart = lasso.prefix.length;
1740
+ const steps = getPathSteps(path, loopStart);
1741
+ const trace = toTrace(steps, path, loopStart);
1742
+ const properties = checker.getViolatedProperties(
1743
+ steps.map((step) => step.state),
1744
+ loopStart,
1745
+ );
1746
+ const back = path[loopStart];
1352
1747
  const last = path[path.length - 1];
1748
+ const lastState = steps[steps.length - 1].state;
1353
1749
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1750
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1751
  return reportViolation(
1356
1752
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1753
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1754
  () =>
1359
1755
  back === last
1360
1756
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1757
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1758
  );
1365
1759
  };
1366
1760
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1767,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1767
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1768
  periodic.size = expanded;
1375
1769
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1770
  periodic.time += performance.now() - now;
1378
1771
  return lasso;
1379
1772
  };
1380
- setNextStatePhase(true);
1381
1773
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1774
  current.index = index;
1383
1775
  current.candidate = undefined;
@@ -1386,22 +1778,28 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1778
  try {
1387
1779
  outcome.result = expandState(index);
1388
1780
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1781
+ const failure =
1782
+ error instanceof TlaIncompleteStateError
1783
+ ? reportIncompleteSuccessor(error, index)
1784
+ : toFailure(toNextStateError(error), getStateTrace(index));
1785
+ outcome.result =
1786
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1787
+ ? failure
1788
+ : replaySuccessors(failure, index);
1390
1789
  }
1391
1790
  if (outcome.result) return outcome.result;
1392
1791
  outDegrees[getOutDegreeBucket()]++;
1393
1792
  expansion.newStates = 0;
1394
1793
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1794
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1795
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1796
  }
1398
1797
  }
1399
1798
 
1400
1799
  current.index = -1;
1401
1800
  current.candidate = undefined;
1402
1801
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1802
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1803
 
1406
1804
  const postconditionViolation = search.findPostconditionViolation();
1407
1805
  if (postconditionViolation) {